This commit is contained in:
2021-04-06 00:45:28 +02:00
commit 17fabc368e
836 changed files with 3042963 additions and 0 deletions

View File

@@ -0,0 +1,148 @@
package org.fog.application;
/**
* Class represents application edges which connect modules together and represent data dependency between them.
* @author Harshit Gupta
*
*/
public class AppEdge {
public static final int SENSOR = 1; // App Edge originates from a sensor
public static final int ACTUATOR = 2; // App Edge leads to an actuator
public static final int MODULE = 3; // App Edge is between application modules
/**
* Name of source application module
*/
private String source;
/**
* Name of destination application module
*/
private String destination;
/**
* CPU length (in MIPS) of tuples carried by the application edge
*/
private double tupleCpuLength;
/**
* Network length (in bytes) of tuples carried by the application edge
*/
private double tupleNwLength;
/**
* Type of tuples carried by the application edge
*/
private String tupleType;
/**
* Direction of tuples carried by the application edge.
*/
private int direction;
private int edgeType;
/**
* Periodicity of application edge (in case it is periodic).
*/
private double periodicity;
/**
* Denotes if the application edge is a periodic edge.
*/
private boolean isPeriodic;
public AppEdge(){
}
public AppEdge(String source, String destination, double tupleCpuLength,
double tupleNwLength, String tupleType, int direction, int edgeType){
setSource(source);
setDestination(destination);
setTupleCpuLength(tupleCpuLength);
setTupleNwLength(tupleNwLength);
setTupleType(tupleType);
setDirection(direction);
setEdgeType(edgeType);
setPeriodic(false);
}
public AppEdge(String source, String destination, double periodicity, double tupleCpuLength,
double tupleNwLength, String tupleType, int direction, int edgeType){
setSource(source);
setDestination(destination);
setTupleCpuLength(tupleCpuLength);
setTupleNwLength(tupleNwLength);
setTupleType(tupleType);
setDirection(direction);
setEdgeType(edgeType);
setPeriodic(true);
setPeriodicity(periodicity);
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public double getTupleCpuLength() {
return tupleCpuLength;
}
public void setTupleCpuLength(double tupleCpuLength) {
this.tupleCpuLength = tupleCpuLength;
}
public double getTupleNwLength() {
return tupleNwLength;
}
public void setTupleNwLength(double tupleNwLength) {
this.tupleNwLength = tupleNwLength;
}
public String getTupleType() {
return tupleType;
}
public void setTupleType(String tupleType) {
this.tupleType = tupleType;
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public int getEdgeType() {
return edgeType;
}
public void setEdgeType(int edgeType) {
this.edgeType = edgeType;
}
public double getPeriodicity() {
return periodicity;
}
public void setPeriodicity(double periodicity) {
this.periodicity = periodicity;
}
public boolean isPeriodic() {
return isPeriodic;
}
public void setPeriodic(boolean isPeriodic) {
this.isPeriodic = isPeriodic;
}
@Override
public String toString() {
return "AppEdge [source=" + source + ", destination=" + destination
+ ", tupleType=" + tupleType + "]";
}
}

View File

@@ -0,0 +1,70 @@
package org.fog.application;
import java.util.List;
import org.fog.utils.TimeKeeper;
public class AppLoop {
private int loopId;
private List<String> modules;
public AppLoop(List<String> modules){
setLoopId(TimeKeeper.getInstance().getUniqueId());
setModules(modules);
}
public boolean hasEdge(String src, String dest){
for(int i=0;i<modules.size()-1;i++){
if(modules.get(i).equals(src) && modules.get(i+1).equals(dest))
return true;
}
return false;
}
public String getStartModule(){
return modules.get(0);
}
public String getEndModule(){
return modules.get(modules.size()-1);
}
public boolean isStartModule(String module){
if(getStartModule().equals(module))
return true;
return false;
}
public boolean isEndModule(String module){
if(getEndModule().equals(module))
return true;
return false;
}
public String getNextModuleInLoop(String module){
String result = null;int i=0;
for(String mod : modules){
if(mod.equals(module)){
result = modules.get(i+1);
break;
}
i++;
}
return result;
}
public List<String> getModules() {
return modules;
}
public void setModules(List<String> modules) {
this.modules = modules;
}
public int getLoopId() {
return loopId;
}
public void setLoopId(int loopId) {
this.loopId = loopId;
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.util.Pair;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.power.PowerVm;
import org.fog.application.selectivity.SelectivityModel;
import org.fog.scheduler.TupleScheduler;
import org.fog.utils.FogUtils;
/**
* Class representing an application module, the processing elements of the application model of iFogSim.
* @author Harshit Gupta
*
*/
public class AppModule extends PowerVm{
private String name;
private String appId;
private Map<Pair<String, String>, SelectivityModel> selectivityMap;
/**
* A map from the AppModules sending tuples UP to this module to their instance IDs.
* If a new instance ID is detected, the number of instances is incremented.
*/
private Map<String, List<Integer>> downInstanceIdsMaps;
/**
* Number of instances of this module
*/
private int numInstances;
/**
* Mapping from tupleType emitted by this AppModule to Actuators subscribing to that tupleType
*/
private Map<String, List<Integer>> actuatorSubscriptions;
public AppModule(
int id,
String name,
String appId,
int userId,
double mips,
int ram,
long bw,
long size,
String vmm,
CloudletScheduler cloudletScheduler,
Map<Pair<String, String>, SelectivityModel> selectivityMap) {
super(id, userId, mips, 1, ram, bw, size, 1, vmm, cloudletScheduler, 300);
setName(name);
setId(id);
setAppId(appId);
setUserId(userId);
setUid(getUid(userId, id));
setMips(mips);
setNumberOfPes(1);
setRam(ram);
setBw(bw);
setSize(size);
setVmm(vmm);
setCloudletScheduler(cloudletScheduler);
setInMigration(false);
setBeingInstantiated(true);
setCurrentAllocatedBw(0);
setCurrentAllocatedMips(null);
setCurrentAllocatedRam(0);
setCurrentAllocatedSize(0);
setSelectivityMap(selectivityMap);
setActuatorSubscriptions(new HashMap<String, List<Integer>>());
setNumInstances(0);
setDownInstanceIdsMaps(new HashMap<String, List<Integer>>());
}
public AppModule(AppModule operator) {
super(FogUtils.generateEntityId(), operator.getUserId(), operator.getMips(), 1, operator.getRam(), operator.getBw(), operator.getSize(), 1, operator.getVmm(), new TupleScheduler(operator.getMips(), 1), operator.getSchedulingInterval());
setName(operator.getName());
setAppId(operator.getAppId());
setInMigration(false);
setBeingInstantiated(true);
setCurrentAllocatedBw(0);
setCurrentAllocatedMips(null);
setCurrentAllocatedRam(0);
setCurrentAllocatedSize(0);
setSelectivityMap(operator.getSelectivityMap());
setDownInstanceIdsMaps(new HashMap<String, List<Integer>>());
}
public void subscribeActuator(int id, String tuplyType){
if(!getActuatorSubscriptions().containsKey(tuplyType))
getActuatorSubscriptions().put(tuplyType, new ArrayList<Integer>());
getActuatorSubscriptions().get(tuplyType).add(id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Pair<String, String>, SelectivityModel> getSelectivityMap() {
return selectivityMap;
}
public void setSelectivityMap(Map<Pair<String, String>, SelectivityModel> selectivityMap) {
this.selectivityMap = selectivityMap;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public Map<String, List<Integer>> getActuatorSubscriptions() {
return actuatorSubscriptions;
}
public void setActuatorSubscriptions(Map<String, List<Integer>> actuatorSubscriptions) {
this.actuatorSubscriptions = actuatorSubscriptions;
}
public Map<String, List<Integer>> getDownInstanceIdsMaps() {
return downInstanceIdsMaps;
}
public void setDownInstanceIdsMaps(Map<String, List<Integer>> downInstanceIdsMaps) {
this.downInstanceIdsMaps = downInstanceIdsMaps;
}
public int getNumInstances() {
return numInstances;
}
public void setNumInstances(int numInstances) {
this.numInstances = numInstances;
}
}

View File

@@ -0,0 +1,341 @@
package org.fog.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.util.Pair;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.fog.application.selectivity.SelectivityModel;
import org.fog.entities.Tuple;
import org.fog.scheduler.TupleScheduler;
import org.fog.utils.FogUtils;
import org.fog.utils.GeoCoverage;
/**
* Class represents an application in the Distributed Dataflow Model.
* @author Harshit Gupta
*
*/
public class Application {
private String appId;
private int userId;
private GeoCoverage geoCoverage;
/**
* List of application modules in the application
*/
private List<AppModule> modules;
/**
* List of application edges in the application
*/
private List<AppEdge> edges;
/**
* List of application loops to monitor for delay
*/
private List<AppLoop> loops;
private Map<String, AppEdge> edgeMap;
/**
* Creates a plain vanilla application with no modules and edges.
* @param appId
* @param userId
* @return
*/
public static Application createApplication(String appId, int userId){
return new Application(appId, userId);
}
/**
* Adds an application module to the application.
* @param moduleName
* @param ram
*/
public void addAppModule(String moduleName, int ram){
int mips = 1000;
long size = 10000;
long bw = 1000;
String vmm = "Xen";
AppModule module = new AppModule(FogUtils.generateEntityId(), moduleName, appId, userId,
mips, ram, bw, size, vmm, new TupleScheduler(mips, 1), new HashMap<Pair<String, String>, SelectivityModel>());
getModules().add(module);
}
/**
* Adds a non-periodic edge to the application model.
* @param source
* @param destination
* @param tupleCpuLength
* @param tupleNwLength
* @param tupleType
* @param direction
* @param edgeType
*/
public void addAppEdge(String source, String destination, double tupleCpuLength,
double tupleNwLength, String tupleType, int direction, int edgeType){
AppEdge edge = new AppEdge(source, destination, tupleCpuLength, tupleNwLength, tupleType, direction, edgeType);
getEdges().add(edge);
getEdgeMap().put(edge.getTupleType(), edge);
}
/**
* Adds a periodic edge to the application model.
* @param source
* @param destination
* @param tupleCpuLength
* @param tupleNwLength
* @param tupleType
* @param direction
* @param edgeType
*/
public void addAppEdge(String source, String destination, double periodicity, double tupleCpuLength,
double tupleNwLength, String tupleType, int direction, int edgeType){
AppEdge edge = new AppEdge(source, destination, periodicity, tupleCpuLength, tupleNwLength, tupleType, direction, edgeType);
getEdges().add(edge);
getEdgeMap().put(edge.getTupleType(), edge);
}
/**
* Define the input-output relationship of an application module for a given input tuple type.
* @param moduleName Name of the module
* @param inputTupleType Type of tuples carried by the incoming edge
* @param outputTupleType Type of tuples carried by the output edge
* @param selectivityModel Selectivity model governing the relation between the incoming and outgoing edge
*/
public void addTupleMapping(String moduleName, String inputTupleType, String outputTupleType, SelectivityModel selectivityModel){
AppModule module = getModuleByName(moduleName);
module.getSelectivityMap().put(new Pair<String, String>(inputTupleType, outputTupleType), selectivityModel);
}
/**
* Get a list of all periodic edges in the application.
* @param srcModule
* @return
*/
public List<AppEdge> getPeriodicEdges(String srcModule){
List<AppEdge> result = new ArrayList<AppEdge>();
for(AppEdge edge : edges){
if(edge.isPeriodic() && edge.getSource().equals(srcModule))
result.add(edge);
}
return result;
}
public Application(String appId, int userId) {
setAppId(appId);
setUserId(userId);
setModules(new ArrayList<AppModule>());
setEdges(new ArrayList<AppEdge>());
setGeoCoverage(null);
setLoops(new ArrayList<AppLoop>());
setEdgeMap(new HashMap<String, AppEdge>());
}
public Application(String appId, List<AppModule> modules,
List<AppEdge> edges, List<AppLoop> loops, GeoCoverage geoCoverage) {
setAppId(appId);
setModules(modules);
setEdges(edges);
setGeoCoverage(geoCoverage);
setLoops(loops);
setEdgeMap(new HashMap<String, AppEdge>());
for(AppEdge edge : edges){
getEdgeMap().put(edge.getTupleType(), edge);
}
}
/**
* Search and return an application module by its module name
* @param name the module name to be returned
* @return
*/
public AppModule getModuleByName(String name){
for(AppModule module : modules){
if(module.getName().equals(name))
return module;
}
return null;
}
/**
* Get the tuples generated upon execution of incoming tuple <i>inputTuple</i> by module named <i>moduleName</i>
* @param moduleName name of the module performing execution of incoming tuple and emitting resultant tuples
* @param inputTuple incoming tuple, whose execution creates resultant tuples
* @param sourceDeviceId
* @return
*/
public List<Tuple> getResultantTuples(String moduleName, Tuple inputTuple, int sourceDeviceId, int sourceModuleId){
List<Tuple> tuples = new ArrayList<Tuple>();
AppModule module = getModuleByName(moduleName);
for(AppEdge edge : getEdges()){
if(edge.getSource().equals(moduleName)){
Pair<String, String> pair = new Pair<String, String>(inputTuple.getTupleType(), edge.getTupleType());
if(module.getSelectivityMap().get(pair)==null)
continue;
SelectivityModel selectivityModel = module.getSelectivityMap().get(pair);
if(selectivityModel.canSelect()){
//TODO check if the edge is ACTUATOR, then create multiple tuples
if(edge.getEdgeType() == AppEdge.ACTUATOR){
//for(Integer actuatorId : module.getActuatorSubscriptions().get(edge.getTupleType())){
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
inputTuple.getNumberOfPes(),
(long) (edge.getTupleNwLength()),
inputTuple.getCloudletOutputSize(),
inputTuple.getUtilizationModelCpu(),
inputTuple.getUtilizationModelRam(),
inputTuple.getUtilizationModelBw()
);
tuple.setActualTupleId(inputTuple.getActualTupleId());
tuple.setUserId(inputTuple.getUserId());
tuple.setAppId(inputTuple.getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(Tuple.ACTUATOR);
tuple.setTupleType(edge.getTupleType());
tuple.setSourceDeviceId(sourceDeviceId);
tuple.setSourceModuleId(sourceModuleId);
//tuple.setActuatorId(actuatorId);
tuples.add(tuple);
//}
}else{
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
inputTuple.getNumberOfPes(),
(long) (edge.getTupleNwLength()),
inputTuple.getCloudletOutputSize(),
inputTuple.getUtilizationModelCpu(),
inputTuple.getUtilizationModelRam(),
inputTuple.getUtilizationModelBw()
);
tuple.setActualTupleId(inputTuple.getActualTupleId());
tuple.setUserId(inputTuple.getUserId());
tuple.setAppId(inputTuple.getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(edge.getDirection());
tuple.setTupleType(edge.getTupleType());
tuple.setSourceModuleId(sourceModuleId);
tuples.add(tuple);
}
}
}
}
return tuples;
}
/**
* Create a tuple for a given application edge
* @param edge
* @param sourceDeviceId
* @return
*/
public Tuple createTuple(AppEdge edge, int sourceDeviceId, int sourceModuleId){
AppModule module = getModuleByName(edge.getSource());
if(edge.getEdgeType() == AppEdge.ACTUATOR){
for(Integer actuatorId : module.getActuatorSubscriptions().get(edge.getTupleType())){
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
1,
(long) (edge.getTupleNwLength()),
100,
new UtilizationModelFull(),
new UtilizationModelFull(),
new UtilizationModelFull()
);
tuple.setUserId(getUserId());
tuple.setAppId(getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(Tuple.ACTUATOR);
tuple.setTupleType(edge.getTupleType());
tuple.setSourceDeviceId(sourceDeviceId);
tuple.setActuatorId(actuatorId);
tuple.setSourceModuleId(sourceModuleId);
return tuple;
}
}else{
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
1,
(long) (edge.getTupleNwLength()),
100,
new UtilizationModelFull(),
new UtilizationModelFull(),
new UtilizationModelFull()
);
//tuple.setActualTupleId(inputTuple.getActualTupleId());
tuple.setUserId(getUserId());
tuple.setAppId(getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(edge.getDirection());
tuple.setTupleType(edge.getTupleType());
tuple.setSourceModuleId(sourceModuleId);
return tuple;
}
return null;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public List<AppModule> getModules() {
return modules;
}
public void setModules(List<AppModule> modules) {
this.modules = modules;
}
public List<AppEdge> getEdges() {
return edges;
}
public void setEdges(List<AppEdge> edges) {
this.edges = edges;
}
public GeoCoverage getGeoCoverage() {
return geoCoverage;
}
public void setGeoCoverage(GeoCoverage geoCoverage) {
this.geoCoverage = geoCoverage;
}
public List<AppLoop> getLoops() {
return loops;
}
public void setLoops(List<AppLoop> loops) {
this.loops = loops;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Map<String, AppEdge> getEdgeMap() {
return edgeMap;
}
public void setEdgeMap(Map<String, AppEdge> edgeMap) {
this.edgeMap = edgeMap;
}
}

View File

@@ -0,0 +1,360 @@
package org.fog.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.util.Pair;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.fog.application.selectivity.SelectivityModel;
import org.fog.entities.Tuple;
import org.fog.scheduler.TupleScheduler;
import org.fog.utils.FogUtils;
import org.fog.utils.GeoCoverage;
/**
* Class represents an application in the Distributed Dataflow Model.
* @author Harshit Gupta
*
*/
public class MyApplication {
private String appId;
private int userId;
private GeoCoverage geoCoverage;
/**
* List of application modules in the application
*/
private List<AppModule> modules;
/**
* List of application edges in the application
*/
private List<AppEdge> edges;
/**
* List of application loops to monitor for delay
*/
private List<AppLoop> loops;
private Map<String, AppEdge> edgeMap;
/**
* Creates a plain vanilla application with no modules and edges.
* @param appId
* @param userId
* @return
*/
public static MyApplication createApplication(String appId, int userId){
return new MyApplication(appId, userId);
}
/**
* Adds an application module to the application.
* @param moduleName
* @param ram
*/
/**
* Adds a non-periodic edge to the application model.
* @param source
* @param destination
* @param tupleCpuLength
* @param tupleNwLength
* @param tupleType
* @param direction
* @param edgeType
*/
public void addAppEdge(String source, String destination, double tupleCpuLength,
double tupleNwLength, String tupleType, int direction, int edgeType){
AppEdge edge = new AppEdge(source, destination, tupleCpuLength, tupleNwLength, tupleType, direction, edgeType);
getEdges().add(edge);
getEdgeMap().put(edge.getTupleType(), edge);
}
/**
* Adds a periodic edge to the application model.
* @param source
* @param destination
* @param tupleCpuLength
* @param tupleNwLength
* @param tupleType
* @param direction
* @param edgeType
*/
public void addAppEdge(String source, String destination, double periodicity, double tupleCpuLength,
double tupleNwLength, String tupleType, int direction, int edgeType){
AppEdge edge = new AppEdge(source, destination, periodicity, tupleCpuLength, tupleNwLength, tupleType, direction, edgeType);
getEdges().add(edge);
getEdgeMap().put(edge.getTupleType(), edge);
}
/**
* Define the input-output relationship of an application module for a given input tuple type.
* @param moduleName Name of the module
* @param inputTupleType Type of tuples carried by the incoming edge
* @param outputTupleType Type of tuples carried by the output edge
* @param selectivityModel Selectivity model governing the relation between the incoming and outgoing edge
*/
public void addTupleMapping(String moduleName, String inputTupleType, String outputTupleType, SelectivityModel selectivityModel){
AppModule module = getModuleByName(moduleName);
module.getSelectivityMap().put(new Pair<String, String>(inputTupleType, outputTupleType), selectivityModel);
}
/**
* Get a list of all periodic edges in the application.
* @param srcModule
* @return
*/
public List<AppEdge> getPeriodicEdges(String srcModule){
List<AppEdge> result = new ArrayList<AppEdge>();
for(AppEdge edge : edges){
if(edge.isPeriodic() && edge.getSource().equals(srcModule))
result.add(edge);
}
return result;
}
public MyApplication(String appId, int userId) {
setAppId(appId);
setUserId(userId);
setModules(new ArrayList<AppModule>());
setEdges(new ArrayList<AppEdge>());
setGeoCoverage(null);
setLoops(new ArrayList<AppLoop>());
setEdgeMap(new HashMap<String, AppEdge>());
}
public MyApplication(String appId, List<AppModule> modules,
List<AppEdge> edges, List<AppLoop> loops, GeoCoverage geoCoverage) {
setAppId(appId);
setModules(modules);
setEdges(edges);
setGeoCoverage(geoCoverage);
setLoops(loops);
setEdgeMap(new HashMap<String, AppEdge>());
for(AppEdge edge : edges){
getEdgeMap().put(edge.getTupleType(), edge);
}
}
/**
* Search and return an application module by its module name
* @param name the module name to be returned
* @return
*/
public AppModule getModuleByName(String name){
for(AppModule module : modules){
if(module.getName().equals(name))
return module;
}
return null;
}
/**
* Get the tuples generated upon execution of incoming tuple <i>inputTuple</i> by module named <i>moduleName</i>
* @param moduleName name of the module performing execution of incoming tuple and emitting resultant tuples
* @param inputTuple incoming tuple, whose execution creates resultant tuples
* @param sourceDeviceId
* @return
*/
public List<Tuple> getResultantTuples(String moduleName, Tuple inputTuple, int sourceDeviceId, int sourceModuleId){
List<Tuple> tuples = new ArrayList<Tuple>();
AppModule module = getModuleByName(moduleName);
for(AppEdge edge : getEdges()){
if(edge.getSource().equals(moduleName)){
Pair<String, String> pair = new Pair<String, String>(inputTuple.getTupleType(), edge.getTupleType());
if(module.getSelectivityMap().get(pair)==null)
continue;
SelectivityModel selectivityModel = module.getSelectivityMap().get(pair);
if(selectivityModel.canSelect()){
//TODO check if the edge is ACTUATOR, then create multiple tuples
if(edge.getEdgeType() == AppEdge.ACTUATOR){
//for(Integer actuatorId : module.getActuatorSubscriptions().get(edge.getTupleType())){
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
inputTuple.getNumberOfPes(),
(long) (edge.getTupleNwLength()),
inputTuple.getCloudletOutputSize(),
inputTuple.getUtilizationModelCpu(),
inputTuple.getUtilizationModelRam(),
inputTuple.getUtilizationModelBw()
);
tuple.setActualTupleId(inputTuple.getActualTupleId());
tuple.setUserId(inputTuple.getUserId());
tuple.setAppId(inputTuple.getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(Tuple.ACTUATOR);
tuple.setTupleType(edge.getTupleType());
tuple.setSourceDeviceId(sourceDeviceId);
tuple.setSourceModuleId(sourceModuleId);
//tuple.setActuatorId(actuatorId);
tuples.add(tuple);
//}
}else{
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
inputTuple.getNumberOfPes(),
(long) (edge.getTupleNwLength()),
inputTuple.getCloudletOutputSize(),
inputTuple.getUtilizationModelCpu(),
inputTuple.getUtilizationModelRam(),
inputTuple.getUtilizationModelBw()
);
tuple.setActualTupleId(inputTuple.getActualTupleId());
tuple.setUserId(inputTuple.getUserId());
tuple.setAppId(inputTuple.getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(edge.getDirection());
tuple.setTupleType(edge.getTupleType());
tuple.setSourceModuleId(sourceModuleId);
tuples.add(tuple);
}
}
}
}
return tuples;
}
/**
* Create a tuple for a given application edge
* @param edge
* @param sourceDeviceId
* @return
*/
public Tuple createTuple(AppEdge edge, int sourceDeviceId, int sourceModuleId){
AppModule module = getModuleByName(edge.getSource());
if(edge.getEdgeType() == AppEdge.ACTUATOR){
for(Integer actuatorId : module.getActuatorSubscriptions().get(edge.getTupleType())){
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
1,
(long) (edge.getTupleNwLength()),
100,
new UtilizationModelFull(),
new UtilizationModelFull(),
new UtilizationModelFull()
);
tuple.setUserId(getUserId());
tuple.setAppId(getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(Tuple.ACTUATOR);
tuple.setTupleType(edge.getTupleType());
tuple.setSourceDeviceId(sourceDeviceId);
tuple.setActuatorId(actuatorId);
tuple.setSourceModuleId(sourceModuleId);
return tuple;
}
}else{
Tuple tuple = new Tuple(appId, FogUtils.generateTupleId(), edge.getDirection(),
(long) (edge.getTupleCpuLength()),
1,
(long) (edge.getTupleNwLength()),
100,
new UtilizationModelFull(),
new UtilizationModelFull(),
new UtilizationModelFull()
);
//tuple.setActualTupleId(inputTuple.getActualTupleId());
tuple.setUserId(getUserId());
tuple.setAppId(getAppId());
tuple.setDestModuleName(edge.getDestination());
tuple.setSrcModuleName(edge.getSource());
tuple.setDirection(edge.getDirection());
tuple.setTupleType(edge.getTupleType());
tuple.setSourceModuleId(sourceModuleId);
return tuple;
}
return null;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public List<AppModule> getModules() {
return modules;
}
public void setModules(List<AppModule> modules) {
this.modules = modules;
}
public List<AppEdge> getEdges() {
return edges;
}
public void setEdges(List<AppEdge> edges) {
this.edges = edges;
}
public GeoCoverage getGeoCoverage() {
return geoCoverage;
}
public void setGeoCoverage(GeoCoverage geoCoverage) {
this.geoCoverage = geoCoverage;
}
public List<AppLoop> getLoops() {
return loops;
}
public void setLoops(List<AppLoop> loops) {
this.loops = loops;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Map<String, AppEdge> getEdgeMap() {
return edgeMap;
}
public void setEdgeMap(Map<String, AppEdge> edgeMap) {
this.edgeMap = edgeMap;
}
////////////////////////////////////////////////////////////// inclusion
private Map<Integer, Map<String, Double>> deadlineInfo;
private Map<Integer, Map<String, Integer>> additionalMipsInfo;
public Map<Integer, Map<String, Integer>> getAdditionalMipsInfo() {
return additionalMipsInfo;
}
public void setAdditionalMipsInfo(
Map<Integer, Map<String, Integer>> additionalMipsInfo) {
this.additionalMipsInfo = additionalMipsInfo;
}
public void setDeadlineInfo(Map<Integer, Map<String, Double>> deadlineInfo) {
this.deadlineInfo = deadlineInfo;
}
public Map<Integer, Map<String, Double>> getDeadlineInfo() {
return deadlineInfo;
}
public void addAppModule(String moduleName,int ram, int mips, long size, long bw){
String vmm = "Xen";
AppModule module = new AppModule(FogUtils.generateEntityId(), moduleName, appId, userId,
mips, ram, bw, size, vmm, new TupleScheduler(mips, 1), new HashMap<Pair<String, String>, SelectivityModel>());
getModules().add(module);
}
}

View File

@@ -0,0 +1,89 @@
package org.fog.application.selectivity;
import org.cloudbus.cloudsim.core.CloudSim;
/**
* Generates an output tuple for every input tuple according to a bursty model.
* During high burst period, all input tuples result in an output tuple.
* During low burst period, no input tuples result in an output tuple.
* @author Harshit Gupta
*
*/
public class BurstySelectivity implements SelectivityModel{
/**
* Duration of the low burst period
*/
double burstLowPeriod;
/**
* Duration of the high burst period
*/
double burstHighPeriod;
/**
* First instance of the start of high burst period, using which subsequent burst periods will be calculated.
*/
double firstHighTime;
public BurstySelectivity(double burstLowPeriod, double burstHighPeriod, double firstHighTime){
setBurstLowPeriod(burstLowPeriod);
setBurstHighPeriod(burstHighPeriod);
setFirstHighTime(firstHighTime);
}
/**
* If the current time falls in the high burst period of the specified burst model, an output tuple is generated for the incoming tuple.
*/
@Override
public boolean canSelect() {
double time = CloudSim.clock() + getFirstHighTime();
double burstPeriod = getBurstHighPeriod()+getBurstLowPeriod();
double burstStartTime = burstPeriod*((int)(time/burstPeriod));
if(time <= burstStartTime + getBurstHighPeriod())
return true;
else
return false;
}
/**
* The mean tuple generation rate is the fraction of high burst period in the total burst period.
*/
@Override
public double getMeanRate() {
return getBurstHighPeriod()/(getBurstHighPeriod()+getBurstLowPeriod());
}
/**
* Maximum tuple generation rate equals 1 (when the burst is high)
*/
@Override
public double getMaxRate() {
return 1;
}
public double getBurstLowPeriod() {
return burstLowPeriod;
}
public void setBurstLowPeriod(double burstLowPeriod) {
this.burstLowPeriod = burstLowPeriod;
}
public double getBurstHighPeriod() {
return burstHighPeriod;
}
public void setBurstHighPeriod(double burstHighPeriod) {
this.burstHighPeriod = burstHighPeriod;
}
public double getFirstHighTime() {
return firstHighTime;
}
public void setFirstHighTime(double firstHighTime) {
this.firstHighTime = firstHighTime;
}
}

View File

@@ -0,0 +1,42 @@
package org.fog.application.selectivity;
/**
* Generates an output tuple for an incoming input tuple with a fixed probability
* @author Harshit Gupta
*
*/
public class FractionalSelectivity implements SelectivityModel{
/**
* The fixed probability of output tuple creation per incoming input tuple
*/
double selectivity;
public FractionalSelectivity(double selectivity){
setSelectivity(selectivity);
}
public double getSelectivity() {
return selectivity;
}
public void setSelectivity(double selectivity) {
this.selectivity = selectivity;
}
@Override
public boolean canSelect() {
if(Math.random() < getSelectivity()) // if the probability condition is satisfied
return true;
return false;
}
@Override
public double getMeanRate() {
return getSelectivity(); // the average rate of tuple generation is the fixed probability value
}
@Override
public double getMaxRate() {
return getSelectivity(); // the maximum rate of tuple generation is the fixed probability value
}
}

View File

@@ -0,0 +1,28 @@
package org.fog.application.selectivity;
/**
* Class representing the input-output relationships of application modules.
* @author Harshit Gupta
*
*/
public interface SelectivityModel {
/**
* Function called to check whether incoming tuple can generate an output tuple.
* @return true if a tuple can be emitted (selection possible)
*/
public boolean canSelect();
/**
* Average number of tuples generated per incoming input tuple.
* @return avg tuple generation rate
*/
public double getMeanRate();
/**
* Maximum number of tuples generated per incoming input tuple.
* @return max tuple generation rate
*/
public double getMaxRate();
}

View File

@@ -0,0 +1,144 @@
package org.fog.entities;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.utils.FogEvents;
import org.fog.utils.GeoLocation;
import org.fog.utils.Logger;
import org.fog.utils.TimeKeeper;
public class Actuator extends SimEntity{
private int gatewayDeviceId;
private double latency;
private GeoLocation geoLocation;
private String appId;
private int userId;
private String actuatorType;
private Application app;
public Actuator(String name, int userId, String appId, int gatewayDeviceId, double latency, GeoLocation geoLocation, String actuatorType, String srcModuleName) {
super(name);
this.setAppId(appId);
this.gatewayDeviceId = gatewayDeviceId;
this.geoLocation = geoLocation;
setUserId(userId);
setActuatorType(actuatorType);
setLatency(latency);
}
public Actuator(String name, int userId, String appId, String actuatorType) {
super(name);
this.setAppId(appId);
setUserId(userId);
setActuatorType(actuatorType);
}
@Override
public void startEntity() {
sendNow(gatewayDeviceId, FogEvents.ACTUATOR_JOINED, getLatency());
}
@Override
public void processEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.TUPLE_ARRIVAL:
processTupleArrival(ev);
break;
}
}
private void processTupleArrival(SimEvent ev) {
Tuple tuple = (Tuple)ev.getData();
Logger.debug(getName(), "Received tuple "+tuple.getCloudletId()+"on "+tuple.getDestModuleName());
String srcModule = tuple.getSrcModuleName();
String destModule = tuple.getDestModuleName();
Application app = getApp();
for(AppLoop loop : app.getLoops()){
if(loop.hasEdge(srcModule, destModule) && loop.isEndModule(destModule)){
Double startTime = TimeKeeper.getInstance().getEmitTimes().get(tuple.getActualTupleId());
if(startTime==null)
break;
if(!TimeKeeper.getInstance().getLoopIdToCurrentAverage().containsKey(loop.getLoopId())){
TimeKeeper.getInstance().getLoopIdToCurrentAverage().put(loop.getLoopId(), 0.0);
TimeKeeper.getInstance().getLoopIdToCurrentNum().put(loop.getLoopId(), 0);
}
double currentAverage = TimeKeeper.getInstance().getLoopIdToCurrentAverage().get(loop.getLoopId());
int currentCount = TimeKeeper.getInstance().getLoopIdToCurrentNum().get(loop.getLoopId());
double delay = CloudSim.clock()- TimeKeeper.getInstance().getEmitTimes().get(tuple.getActualTupleId());
TimeKeeper.getInstance().getEmitTimes().remove(tuple.getActualTupleId());
double newAverage = (currentAverage*currentCount + delay)/(currentCount+1);
TimeKeeper.getInstance().getLoopIdToCurrentAverage().put(loop.getLoopId(), newAverage);
TimeKeeper.getInstance().getLoopIdToCurrentNum().put(loop.getLoopId(), currentCount+1);
break;
}
}
}
@Override
public void shutdownEntity() {
}
public int getGatewayDeviceId() {
return gatewayDeviceId;
}
public void setGatewayDeviceId(int gatewayDeviceId) {
this.gatewayDeviceId = gatewayDeviceId;
}
public GeoLocation getGeoLocation() {
return geoLocation;
}
public void setGeoLocation(GeoLocation geoLocation) {
this.geoLocation = geoLocation;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getActuatorType() {
return actuatorType;
}
public void setActuatorType(String actuatorType) {
this.actuatorType = actuatorType;
}
public Application getApp() {
return app;
}
public void setApp(Application app) {
this.app = app;
}
public double getLatency() {
return latency;
}
public void setLatency(double latency) {
this.latency = latency;
}
}

View File

@@ -0,0 +1,33 @@
package org.fog.entities;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.power.PowerDatacenterBroker;
public class FogBroker extends PowerDatacenterBroker{
public FogBroker(String name) throws Exception {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void startEntity() {
// TODO Auto-generated method stub
}
@Override
public void processEvent(SimEvent ev) {
// TODO Auto-generated method stub
}
@Override
public void shutdownEntity() {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,987 @@
package org.fog.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import org.apache.commons.math3.util.Pair;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
import org.cloudbus.cloudsim.power.PowerDatacenter;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.power.models.PowerModel;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.AppModule;
import org.fog.application.Application;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.Config;
import org.fog.utils.FogEvents;
import org.fog.utils.FogUtils;
import org.fog.utils.Logger;
import org.fog.utils.ModuleLaunchConfig;
import org.fog.utils.NetworkUsageMonitor;
import org.fog.utils.TimeKeeper;
public class FogDevice extends PowerDatacenter {
protected Queue<Tuple> northTupleQueue;
protected Queue<Pair<Tuple, Integer>> southTupleQueue;
protected List<String> activeApplications;
protected Map<String, Application> applicationMap;
protected Map<String, List<String>> appToModulesMap;
protected Map<Integer, Double> childToLatencyMap;
protected Map<Integer, Integer> cloudTrafficMap;
protected double lockTime;
/**
* ID of the parent Fog Device
*/
protected int parentId;
/**
* ID of the Controller
*/
protected int controllerId;
/**
* IDs of the children Fog devices
*/
protected List<Integer> childrenIds;
protected Map<Integer, List<String>> childToOperatorsMap;
/**
* Flag denoting whether the link southwards from this FogDevice is busy
*/
protected boolean isSouthLinkBusy;
/**
* Flag denoting whether the link northwards from this FogDevice is busy
*/
protected boolean isNorthLinkBusy;
protected double uplinkBandwidth;
protected double downlinkBandwidth;
protected double uplinkLatency;
protected List<Pair<Integer, Double>> associatedActuatorIds;
protected double energyConsumption;
protected double lastUtilizationUpdateTime;
protected double lastUtilization;
private int level;
protected double ratePerMips;
protected double totalCost;
protected Map<String, Map<String, Integer>> moduleInstanceCount;
public FogDevice(
String name,
FogDeviceCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<Storage> storageList,
double schedulingInterval,
double uplinkBandwidth, double downlinkBandwidth, double uplinkLatency, double ratePerMips) throws Exception {
super(name, characteristics, vmAllocationPolicy, storageList, schedulingInterval);
setCharacteristics(characteristics);
setVmAllocationPolicy(vmAllocationPolicy);
setLastProcessTime(0.0);
setStorageList(storageList);
setVmList(new ArrayList<Vm>());
setSchedulingInterval(schedulingInterval);
setUplinkBandwidth(uplinkBandwidth);
setDownlinkBandwidth(downlinkBandwidth);
setUplinkLatency(uplinkLatency);
setRatePerMips(ratePerMips);
setAssociatedActuatorIds(new ArrayList<Pair<Integer, Double>>());
for (Host host : getCharacteristics().getHostList()) {
host.setDatacenter(this);
}
setActiveApplications(new ArrayList<String>());
// If this resource doesn't have any PEs then no useful at all
if (getCharacteristics().getNumberOfPes() == 0) {
throw new Exception(super.getName()
+ " : Error - this entity has no PEs. Therefore, can't process any Cloudlets.");
}
// stores id of this class
getCharacteristics().setId(super.getId());
applicationMap = new HashMap<String, Application>();
appToModulesMap = new HashMap<String, List<String>>();
northTupleQueue = new LinkedList<Tuple>();
southTupleQueue = new LinkedList<Pair<Tuple, Integer>>();
setNorthLinkBusy(false);
setSouthLinkBusy(false);
setChildrenIds(new ArrayList<Integer>());
setChildToOperatorsMap(new HashMap<Integer, List<String>>());
this.cloudTrafficMap = new HashMap<Integer, Integer>();
this.lockTime = 0;
this.energyConsumption = 0;
this.lastUtilization = 0;
setTotalCost(0);
setModuleInstanceCount(new HashMap<String, Map<String, Integer>>());
setChildToLatencyMap(new HashMap<Integer, Double>());
}
public FogDevice(
String name, long mips, int ram,
double uplinkBandwidth, double downlinkBandwidth, double ratePerMips, PowerModel powerModel) throws Exception {
super(name, null, null, new LinkedList<Storage>(), 0);
List<Pe> peList = new ArrayList<Pe>();
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); // need to store Pe id and MIPS Rating
int hostId = FogUtils.generateEntityId();
long storage = 1000000; // host storage
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
powerModel
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
setVmAllocationPolicy(new AppModuleAllocationPolicy(hostList));
String arch = Config.FOG_DEVICE_ARCH;
String os = Config.FOG_DEVICE_OS;
String vmm = Config.FOG_DEVICE_VMM;
double time_zone = Config.FOG_DEVICE_TIMEZONE;
double cost = Config.FOG_DEVICE_COST;
double costPerMem = Config.FOG_DEVICE_COST_PER_MEMORY;
double costPerStorage = Config.FOG_DEVICE_COST_PER_STORAGE;
double costPerBw = Config.FOG_DEVICE_COST_PER_BW;
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
setCharacteristics(characteristics);
setLastProcessTime(0.0);
setVmList(new ArrayList<Vm>());
setUplinkBandwidth(uplinkBandwidth);
setDownlinkBandwidth(downlinkBandwidth);
setUplinkLatency(uplinkLatency);
setAssociatedActuatorIds(new ArrayList<Pair<Integer, Double>>());
for (Host host1 : getCharacteristics().getHostList()) {
host1.setDatacenter(this);
}
setActiveApplications(new ArrayList<String>());
if (getCharacteristics().getNumberOfPes() == 0) {
throw new Exception(super.getName()
+ " : Error - this entity has no PEs. Therefore, can't process any Cloudlets.");
}
getCharacteristics().setId(super.getId());
applicationMap = new HashMap<String, Application>();
appToModulesMap = new HashMap<String, List<String>>();
northTupleQueue = new LinkedList<Tuple>();
southTupleQueue = new LinkedList<Pair<Tuple, Integer>>();
setNorthLinkBusy(false);
setSouthLinkBusy(false);
setChildrenIds(new ArrayList<Integer>());
setChildToOperatorsMap(new HashMap<Integer, List<String>>());
this.cloudTrafficMap = new HashMap<Integer, Integer>();
this.lockTime = 0;
this.energyConsumption = 0;
this.lastUtilization = 0;
setTotalCost(0);
setChildToLatencyMap(new HashMap<Integer, Double>());
setModuleInstanceCount(new HashMap<String, Map<String, Integer>>());
}
/**
* Overrides this method when making a new and different type of resource. <br>
* <b>NOTE:</b> You do not need to override {@link #body()} method, if you use this method.
*
* @pre $none
* @post $none
*/
protected void registerOtherEntity() {
}
@Override
protected void processOtherEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.TUPLE_ARRIVAL:
processTupleArrival(ev);
break;
case FogEvents.LAUNCH_MODULE:
processModuleArrival(ev);
break;
case FogEvents.RELEASE_OPERATOR:
processOperatorRelease(ev);
break;
case FogEvents.SENSOR_JOINED:
processSensorJoining(ev);
break;
case FogEvents.SEND_PERIODIC_TUPLE:
sendPeriodicTuple(ev);
break;
case FogEvents.APP_SUBMIT:
processAppSubmit(ev);
break;
case FogEvents.UPDATE_NORTH_TUPLE_QUEUE:
updateNorthTupleQueue();
break;
case FogEvents.UPDATE_SOUTH_TUPLE_QUEUE:
updateSouthTupleQueue();
break;
case FogEvents.ACTIVE_APP_UPDATE:
updateActiveApplications(ev);
break;
case FogEvents.ACTUATOR_JOINED:
processActuatorJoined(ev);
break;
case FogEvents.LAUNCH_MODULE_INSTANCE:
updateModuleInstanceCount(ev);
break;
case FogEvents.RESOURCE_MGMT:
manageResources(ev);
default:
break;
}
}
/**
* Perform miscellaneous resource management tasks
* @param ev
*/
private void manageResources(SimEvent ev) {
updateEnergyConsumption();
send(getId(), Config.RESOURCE_MGMT_INTERVAL, FogEvents.RESOURCE_MGMT);
}
/**
* Updating the number of modules of an application module on this device
* @param ev instance of SimEvent containing the module and no of instances
*/
private void updateModuleInstanceCount(SimEvent ev) {
ModuleLaunchConfig config = (ModuleLaunchConfig)ev.getData();
String appId = config.getModule().getAppId();
if(!moduleInstanceCount.containsKey(appId))
moduleInstanceCount.put(appId, new HashMap<String, Integer>());
moduleInstanceCount.get(appId).put(config.getModule().getName(), config.getInstanceCount());
System.out.println(getName()+ " Creating "+config.getInstanceCount()+" instances of module "+config.getModule().getName());
}
private AppModule getModuleByName(String moduleName){
AppModule module = null;
for(Vm vm : getHost().getVmList()){
if(((AppModule)vm).getName().equals(moduleName)){
module=(AppModule)vm;
break;
}
}
return module;
}
/**
* Sending periodic tuple for an application edge. Note that for multiple instances of a single source module, only one tuple is sent DOWN while instanceCount number of tuples are sent UP.
* @param ev SimEvent instance containing the edge to send tuple on
*/
private void sendPeriodicTuple(SimEvent ev) {
AppEdge edge = (AppEdge)ev.getData();
String srcModule = edge.getSource();
AppModule module = getModuleByName(srcModule);
if(module == null)
return;
int instanceCount = module.getNumInstances();
/*
* Since tuples sent through a DOWN application edge are anyways broadcasted, only UP tuples are replicated
*/
for(int i = 0;i<((edge.getDirection()==Tuple.UP)?instanceCount:1);i++){
//System.out.println(CloudSim.clock()+" : Sending periodic tuple "+edge.getTupleType());
Tuple tuple = applicationMap.get(module.getAppId()).createTuple(edge, getId(), module.getId());
updateTimingsOnSending(tuple);
sendToSelf(tuple);
}
send(getId(), edge.getPeriodicity(), FogEvents.SEND_PERIODIC_TUPLE, edge);
}
protected void processActuatorJoined(SimEvent ev) {
int actuatorId = ev.getSource();
double delay = (double)ev.getData();
getAssociatedActuatorIds().add(new Pair<Integer, Double>(actuatorId, delay));
}
protected void updateActiveApplications(SimEvent ev) {
Application app = (Application)ev.getData();
getActiveApplications().add(app.getAppId());
}
public String getOperatorName(int vmId){
for(Vm vm : this.getHost().getVmList()){
if(vm.getId() == vmId)
return ((AppModule)vm).getName();
}
return null;
}
/**
* Update cloudet processing without scheduling future events.
*
* @return the double
*/
protected double updateCloudetProcessingWithoutSchedulingFutureEventsForce() {
double currentTime = CloudSim.clock();
double minTime = Double.MAX_VALUE;
double timeDiff = currentTime - getLastProcessTime();
double timeFrameDatacenterEnergy = 0.0;
for (PowerHost host : this.<PowerHost> getHostList()) {
Log.printLine();
double time = host.updateVmsProcessing(currentTime); // inform VMs to update processing
if (time < minTime) {
minTime = time;
}
Log.formatLine(
"%.2f: [Host #%d] utilization is %.2f%%",
currentTime,
host.getId(),
host.getUtilizationOfCpu() * 100);
}
if (timeDiff > 0) {
Log.formatLine(
"\nEnergy consumption for the last time frame from %.2f to %.2f:",
getLastProcessTime(),
currentTime);
for (PowerHost host : this.<PowerHost> getHostList()) {
double previousUtilizationOfCpu = host.getPreviousUtilizationOfCpu();
double utilizationOfCpu = host.getUtilizationOfCpu();
double timeFrameHostEnergy = host.getEnergyLinearInterpolation(
previousUtilizationOfCpu,
utilizationOfCpu,
timeDiff);
timeFrameDatacenterEnergy += timeFrameHostEnergy;
Log.printLine();
Log.formatLine(
"%.2f: [Host #%d] utilization at %.2f was %.2f%%, now is %.2f%%",
currentTime,
host.getId(),
getLastProcessTime(),
previousUtilizationOfCpu * 100,
utilizationOfCpu * 100);
Log.formatLine(
"%.2f: [Host #%d] energy is %.2f W*sec",
currentTime,
host.getId(),
timeFrameHostEnergy);
}
Log.formatLine(
"\n%.2f: Data center's energy is %.2f W*sec\n",
currentTime,
timeFrameDatacenterEnergy);
}
setPower(getPower() + timeFrameDatacenterEnergy);
checkCloudletCompletion();
/** Remove completed VMs **/
/**
* Change made by HARSHIT GUPTA
*/
/*for (PowerHost host : this.<PowerHost> getHostList()) {
for (Vm vm : host.getCompletedVms()) {
getVmAllocationPolicy().deallocateHostForVm(vm);
getVmList().remove(vm);
Log.printLine("VM #" + vm.getId() + " has been deallocated from host #" + host.getId());
}
}*/
Log.printLine();
setLastProcessTime(currentTime);
return minTime;
}
protected void checkCloudletCompletion() {
boolean cloudletCompleted = false;
List<? extends Host> list = getVmAllocationPolicy().getHostList();
for (int i = 0; i < list.size(); i++) {
Host host = list.get(i);
for (Vm vm : host.getVmList()) {
while (vm.getCloudletScheduler().isFinishedCloudlets()) {
Cloudlet cl = vm.getCloudletScheduler().getNextFinishedCloudlet();
if (cl != null) {
cloudletCompleted = true;
Tuple tuple = (Tuple)cl;
TimeKeeper.getInstance().tupleEndedExecution(tuple);
Application application = getApplicationMap().get(tuple.getAppId());
Logger.debug(getName(), "Completed execution of tuple "+tuple.getCloudletId()+"on "+tuple.getDestModuleName());
List<Tuple> resultantTuples = application.getResultantTuples(tuple.getDestModuleName(), tuple, getId(), vm.getId());
for(Tuple resTuple : resultantTuples){
resTuple.setModuleCopyMap(new HashMap<String, Integer>(tuple.getModuleCopyMap()));
resTuple.getModuleCopyMap().put(((AppModule)vm).getName(), vm.getId());
updateTimingsOnSending(resTuple);
sendToSelf(resTuple);
}
sendNow(cl.getUserId(), CloudSimTags.CLOUDLET_RETURN, cl);
}
}
}
}
if(cloudletCompleted)
updateAllocatedMips(null);
}
protected void updateTimingsOnSending(Tuple resTuple) {
// TODO ADD CODE FOR UPDATING TIMINGS WHEN A TUPLE IS GENERATED FROM A PREVIOUSLY RECIEVED TUPLE.
// WILL NEED TO CHECK IF A NEW LOOP STARTS AND INSERT A UNIQUE TUPLE ID TO IT.
String srcModule = resTuple.getSrcModuleName();
String destModule = resTuple.getDestModuleName();
for(AppLoop loop : getApplicationMap().get(resTuple.getAppId()).getLoops()){
if(loop.hasEdge(srcModule, destModule) && loop.isStartModule(srcModule)){
int tupleId = TimeKeeper.getInstance().getUniqueId();
resTuple.setActualTupleId(tupleId);
if(!TimeKeeper.getInstance().getLoopIdToTupleIds().containsKey(loop.getLoopId()))
TimeKeeper.getInstance().getLoopIdToTupleIds().put(loop.getLoopId(), new ArrayList<Integer>());
TimeKeeper.getInstance().getLoopIdToTupleIds().get(loop.getLoopId()).add(tupleId);
TimeKeeper.getInstance().getEmitTimes().put(tupleId, CloudSim.clock());
//Logger.debug(getName(), "\tSENDING\t"+tuple.getActualTupleId()+"\tSrc:"+srcModule+"\tDest:"+destModule);
}
}
}
protected int getChildIdWithRouteTo(int targetDeviceId){
for(Integer childId : getChildrenIds()){
if(targetDeviceId == childId)
return childId;
if(((FogDevice)CloudSim.getEntity(childId)).getChildIdWithRouteTo(targetDeviceId) != -1)
return childId;
}
return -1;
}
protected int getChildIdForTuple(Tuple tuple){
if(tuple.getDirection() == Tuple.ACTUATOR){
int gatewayId = ((Actuator)CloudSim.getEntity(tuple.getActuatorId())).getGatewayDeviceId();
return getChildIdWithRouteTo(gatewayId);
}
return -1;
}
protected void updateAllocatedMips(String incomingOperator){
getHost().getVmScheduler().deallocatePesForAllVms();
for(final Vm vm : getHost().getVmList()){
if(vm.getCloudletScheduler().runningCloudlets() > 0 || ((AppModule)vm).getName().equals(incomingOperator)){
getHost().getVmScheduler().allocatePesForVm(vm, new ArrayList<Double>(){
protected static final long serialVersionUID = 1L;
{add((double) getHost().getTotalMips());}});
}else{
getHost().getVmScheduler().allocatePesForVm(vm, new ArrayList<Double>(){
protected static final long serialVersionUID = 1L;
{add(0.0);}});
}
}
updateEnergyConsumption();
}
private void updateEnergyConsumption() {
double totalMipsAllocated = 0;
for(final Vm vm : getHost().getVmList()){
AppModule operator = (AppModule)vm;
operator.updateVmProcessing(CloudSim.clock(), getVmAllocationPolicy().getHost(operator).getVmScheduler()
.getAllocatedMipsForVm(operator));
totalMipsAllocated += getHost().getTotalAllocatedMipsForVm(vm);
}
double timeNow = CloudSim.clock();
double currentEnergyConsumption = getEnergyConsumption();
double newEnergyConsumption = currentEnergyConsumption + (timeNow-lastUtilizationUpdateTime)*getHost().getPowerModel().getPower(lastUtilization);
setEnergyConsumption(newEnergyConsumption);
/*if(getName().equals("d-0")){
System.out.println("------------------------");
System.out.println("Utilization = "+lastUtilization);
System.out.println("Power = "+getHost().getPowerModel().getPower(lastUtilization));
System.out.println(timeNow-lastUtilizationUpdateTime);
}*/
double currentCost = getTotalCost();
double newcost = currentCost + (timeNow-lastUtilizationUpdateTime)*getRatePerMips()*lastUtilization*getHost().getTotalMips();
setTotalCost(newcost);
lastUtilization = Math.min(1, totalMipsAllocated/getHost().getTotalMips());
lastUtilizationUpdateTime = timeNow;
}
protected void processAppSubmit(SimEvent ev) {
Application app = (Application)ev.getData();
applicationMap.put(app.getAppId(), app);
}
protected void addChild(int childId){
if(CloudSim.getEntityName(childId).toLowerCase().contains("sensor"))
return;
if(!getChildrenIds().contains(childId) && childId != getId())
getChildrenIds().add(childId);
if(!getChildToOperatorsMap().containsKey(childId))
getChildToOperatorsMap().put(childId, new ArrayList<String>());
}
protected void updateCloudTraffic(){
int time = (int)CloudSim.clock()/1000;
if(!cloudTrafficMap.containsKey(time))
cloudTrafficMap.put(time, 0);
cloudTrafficMap.put(time, cloudTrafficMap.get(time)+1);
}
protected void sendTupleToActuator(Tuple tuple){
/*for(Pair<Integer, Double> actuatorAssociation : getAssociatedActuatorIds()){
int actuatorId = actuatorAssociation.getFirst();
double delay = actuatorAssociation.getSecond();
if(actuatorId == tuple.getActuatorId()){
send(actuatorId, delay, FogEvents.TUPLE_ARRIVAL, tuple);
return;
}
}
int childId = getChildIdForTuple(tuple);
if(childId != -1)
sendDown(tuple, childId);*/
for(Pair<Integer, Double> actuatorAssociation : getAssociatedActuatorIds()){
int actuatorId = actuatorAssociation.getFirst();
double delay = actuatorAssociation.getSecond();
String actuatorType = ((Actuator)CloudSim.getEntity(actuatorId)).getActuatorType();
if(tuple.getDestModuleName().equals(actuatorType)){
send(actuatorId, delay, FogEvents.TUPLE_ARRIVAL, tuple);
return;
}
}
for(int childId : getChildrenIds()){
sendDown(tuple, childId);
}
}
int numClients=0;
protected void processTupleArrival(SimEvent ev){
Tuple tuple = (Tuple)ev.getData();
if(getName().equals("cloud")){
updateCloudTraffic();
}
/*if(getName().equals("d-0") && tuple.getTupleType().equals("_SENSOR")){
System.out.println(++numClients);
}*/
Logger.debug(getName(), "Received tuple "+tuple.getCloudletId()+"with tupleType = "+tuple.getTupleType()+"\t| Source : "+
CloudSim.getEntityName(ev.getSource())+"|Dest : "+CloudSim.getEntityName(ev.getDestination()));
send(ev.getSource(), CloudSim.getMinTimeBetweenEvents(), FogEvents.TUPLE_ACK);
if(FogUtils.appIdToGeoCoverageMap.containsKey(tuple.getAppId())){
}
if(tuple.getDirection() == Tuple.ACTUATOR){
sendTupleToActuator(tuple);
return;
}
if(getHost().getVmList().size() > 0){
final AppModule operator = (AppModule)getHost().getVmList().get(0);
if(CloudSim.clock() > 0){
getHost().getVmScheduler().deallocatePesForVm(operator);
getHost().getVmScheduler().allocatePesForVm(operator, new ArrayList<Double>(){
protected static final long serialVersionUID = 1L;
{add((double) getHost().getTotalMips());}});
}
}
if(getName().equals("cloud") && tuple.getDestModuleName()==null){
sendNow(getControllerId(), FogEvents.TUPLE_FINISHED, null);
}
if(appToModulesMap.containsKey(tuple.getAppId())){
if(appToModulesMap.get(tuple.getAppId()).contains(tuple.getDestModuleName())){
int vmId = -1;
for(Vm vm : getHost().getVmList()){
if(((AppModule)vm).getName().equals(tuple.getDestModuleName()))
vmId = vm.getId();
}
if(vmId < 0
|| (tuple.getModuleCopyMap().containsKey(tuple.getDestModuleName()) &&
tuple.getModuleCopyMap().get(tuple.getDestModuleName())!=vmId )){
return;
}
tuple.setVmId(vmId);
//Logger.error(getName(), "Executing tuple for operator " + moduleName);
updateTimingsOnReceipt(tuple);
executeTuple(ev, tuple.getDestModuleName());
}else if(tuple.getDestModuleName()!=null){
if(tuple.getDirection() == Tuple.UP)
sendUp(tuple);
else if(tuple.getDirection() == Tuple.DOWN){
for(int childId : getChildrenIds())
sendDown(tuple, childId);
}
}else{
sendUp(tuple);
}
}else{
if(tuple.getDirection() == Tuple.UP)
sendUp(tuple);
else if(tuple.getDirection() == Tuple.DOWN){
for(int childId : getChildrenIds())
sendDown(tuple, childId);
}
}
}
protected void updateTimingsOnReceipt(Tuple tuple) {
Application app = getApplicationMap().get(tuple.getAppId());
String srcModule = tuple.getSrcModuleName();
String destModule = tuple.getDestModuleName();
List<AppLoop> loops = app.getLoops();
for(AppLoop loop : loops){
if(loop.hasEdge(srcModule, destModule) && loop.isEndModule(destModule)){
Double startTime = TimeKeeper.getInstance().getEmitTimes().get(tuple.getActualTupleId());
if(startTime==null)
break;
if(!TimeKeeper.getInstance().getLoopIdToCurrentAverage().containsKey(loop.getLoopId())){
TimeKeeper.getInstance().getLoopIdToCurrentAverage().put(loop.getLoopId(), 0.0);
TimeKeeper.getInstance().getLoopIdToCurrentNum().put(loop.getLoopId(), 0);
}
double currentAverage = TimeKeeper.getInstance().getLoopIdToCurrentAverage().get(loop.getLoopId());
int currentCount = TimeKeeper.getInstance().getLoopIdToCurrentNum().get(loop.getLoopId());
double delay = CloudSim.clock()- TimeKeeper.getInstance().getEmitTimes().get(tuple.getActualTupleId());
TimeKeeper.getInstance().getEmitTimes().remove(tuple.getActualTupleId());
double newAverage = (currentAverage*currentCount + delay)/(currentCount+1);
TimeKeeper.getInstance().getLoopIdToCurrentAverage().put(loop.getLoopId(), newAverage);
TimeKeeper.getInstance().getLoopIdToCurrentNum().put(loop.getLoopId(), currentCount+1);
break;
}
}
}
protected void processSensorJoining(SimEvent ev){
send(ev.getSource(), CloudSim.getMinTimeBetweenEvents(), FogEvents.TUPLE_ACK);
}
protected void executeTuple(SimEvent ev, String moduleName){
Logger.debug(getName(), "Executing tuple on module "+moduleName);
Tuple tuple = (Tuple)ev.getData();
AppModule module = getModuleByName(moduleName);
if(tuple.getDirection() == Tuple.UP){
String srcModule = tuple.getSrcModuleName();
if(!module.getDownInstanceIdsMaps().containsKey(srcModule))
module.getDownInstanceIdsMaps().put(srcModule, new ArrayList<Integer>());
if(!module.getDownInstanceIdsMaps().get(srcModule).contains(tuple.getSourceModuleId()))
module.getDownInstanceIdsMaps().get(srcModule).add(tuple.getSourceModuleId());
int instances = -1;
for(String _moduleName : module.getDownInstanceIdsMaps().keySet()){
instances = Math.max(module.getDownInstanceIdsMaps().get(_moduleName).size(), instances);
}
module.setNumInstances(instances);
}
TimeKeeper.getInstance().tupleStartedExecution(tuple);
updateAllocatedMips(moduleName);
processCloudletSubmit(ev, false);
updateAllocatedMips(moduleName);
/*for(Vm vm : getHost().getVmList()){
Logger.error(getName(), "MIPS allocated to "+((AppModule)vm).getName()+" = "+getHost().getTotalAllocatedMipsForVm(vm));
}*/
}
protected void processModuleArrival(SimEvent ev){
AppModule module = (AppModule)ev.getData();
String appId = module.getAppId();
if(!appToModulesMap.containsKey(appId)){
appToModulesMap.put(appId, new ArrayList<String>());
}
appToModulesMap.get(appId).add(module.getName());
processVmCreate(ev, false);
if (module.isBeingInstantiated()) {
module.setBeingInstantiated(false);
}
initializePeriodicTuples(module);
module.updateVmProcessing(CloudSim.clock(), getVmAllocationPolicy().getHost(module).getVmScheduler()
.getAllocatedMipsForVm(module));
}
private void initializePeriodicTuples(AppModule module) {
String appId = module.getAppId();
Application app = getApplicationMap().get(appId);
List<AppEdge> periodicEdges = app.getPeriodicEdges(module.getName());
for(AppEdge edge : periodicEdges){
send(getId(), edge.getPeriodicity(), FogEvents.SEND_PERIODIC_TUPLE, edge);
}
}
protected void processOperatorRelease(SimEvent ev){
this.processVmMigrate(ev, false);
}
protected void updateNorthTupleQueue(){
if(!getNorthTupleQueue().isEmpty()){
Tuple tuple = getNorthTupleQueue().poll();
sendUpFreeLink(tuple);
}else{
setNorthLinkBusy(false);
}
}
protected void sendUpFreeLink(Tuple tuple){
double networkDelay = tuple.getCloudletFileSize()/getUplinkBandwidth();
setNorthLinkBusy(true);
send(getId(), networkDelay, FogEvents.UPDATE_NORTH_TUPLE_QUEUE);
send(parentId, networkDelay+getUplinkLatency(), FogEvents.TUPLE_ARRIVAL, tuple);
NetworkUsageMonitor.sendingTuple(getUplinkLatency(), tuple.getCloudletFileSize());
}
protected void sendUp(Tuple tuple){
if(parentId > 0){
if(!isNorthLinkBusy()){
sendUpFreeLink(tuple);
}else{
northTupleQueue.add(tuple);
}
}
}
protected void updateSouthTupleQueue(){
if(!getSouthTupleQueue().isEmpty()){
Pair<Tuple, Integer> pair = getSouthTupleQueue().poll();
sendDownFreeLink(pair.getFirst(), pair.getSecond());
}else{
setSouthLinkBusy(false);
}
}
protected void sendDownFreeLink(Tuple tuple, int childId){
double networkDelay = tuple.getCloudletFileSize()/getDownlinkBandwidth();
//Logger.debug(getName(), "Sending tuple with tupleType = "+tuple.getTupleType()+" DOWN");
setSouthLinkBusy(true);
double latency = getChildToLatencyMap().get(childId);
send(getId(), networkDelay, FogEvents.UPDATE_SOUTH_TUPLE_QUEUE);
send(childId, networkDelay+latency, FogEvents.TUPLE_ARRIVAL, tuple);
NetworkUsageMonitor.sendingTuple(latency, tuple.getCloudletFileSize());
}
protected void sendDown(Tuple tuple, int childId){
if(getChildrenIds().contains(childId)){
if(!isSouthLinkBusy()){
sendDownFreeLink(tuple, childId);
}else{
southTupleQueue.add(new Pair<Tuple, Integer>(tuple, childId));
}
}
}
protected void sendToSelf(Tuple tuple){
send(getId(), CloudSim.getMinTimeBetweenEvents(), FogEvents.TUPLE_ARRIVAL, tuple);
}
public PowerHost getHost(){
return (PowerHost) getHostList().get(0);
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
public List<Integer> getChildrenIds() {
return childrenIds;
}
public void setChildrenIds(List<Integer> childrenIds) {
this.childrenIds = childrenIds;
}
public double getUplinkBandwidth() {
return uplinkBandwidth;
}
public void setUplinkBandwidth(double uplinkBandwidth) {
this.uplinkBandwidth = uplinkBandwidth;
}
public double getUplinkLatency() {
return uplinkLatency;
}
public void setUplinkLatency(double uplinkLatency) {
this.uplinkLatency = uplinkLatency;
}
public boolean isSouthLinkBusy() {
return isSouthLinkBusy;
}
public boolean isNorthLinkBusy() {
return isNorthLinkBusy;
}
public void setSouthLinkBusy(boolean isSouthLinkBusy) {
this.isSouthLinkBusy = isSouthLinkBusy;
}
public void setNorthLinkBusy(boolean isNorthLinkBusy) {
this.isNorthLinkBusy = isNorthLinkBusy;
}
public int getControllerId() {
return controllerId;
}
public void setControllerId(int controllerId) {
this.controllerId = controllerId;
}
public List<String> getActiveApplications() {
return activeApplications;
}
public void setActiveApplications(List<String> activeApplications) {
this.activeApplications = activeApplications;
}
public Map<Integer, List<String>> getChildToOperatorsMap() {
return childToOperatorsMap;
}
public void setChildToOperatorsMap(Map<Integer, List<String>> childToOperatorsMap) {
this.childToOperatorsMap = childToOperatorsMap;
}
public Map<String, Application> getApplicationMap() {
return applicationMap;
}
public void setApplicationMap(Map<String, Application> applicationMap) {
this.applicationMap = applicationMap;
}
public Queue<Tuple> getNorthTupleQueue() {
return northTupleQueue;
}
public void setNorthTupleQueue(Queue<Tuple> northTupleQueue) {
this.northTupleQueue = northTupleQueue;
}
public Queue<Pair<Tuple, Integer>> getSouthTupleQueue() {
return southTupleQueue;
}
public void setSouthTupleQueue(Queue<Pair<Tuple, Integer>> southTupleQueue) {
this.southTupleQueue = southTupleQueue;
}
public double getDownlinkBandwidth() {
return downlinkBandwidth;
}
public void setDownlinkBandwidth(double downlinkBandwidth) {
this.downlinkBandwidth = downlinkBandwidth;
}
public List<Pair<Integer, Double>> getAssociatedActuatorIds() {
return associatedActuatorIds;
}
public void setAssociatedActuatorIds(List<Pair<Integer, Double>> associatedActuatorIds) {
this.associatedActuatorIds = associatedActuatorIds;
}
public double getEnergyConsumption() {
return energyConsumption;
}
public void setEnergyConsumption(double energyConsumption) {
this.energyConsumption = energyConsumption;
}
public Map<Integer, Double> getChildToLatencyMap() {
return childToLatencyMap;
}
public void setChildToLatencyMap(Map<Integer, Double> childToLatencyMap) {
this.childToLatencyMap = childToLatencyMap;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public double getRatePerMips() {
return ratePerMips;
}
public void setRatePerMips(double ratePerMips) {
this.ratePerMips = ratePerMips;
}
public double getTotalCost() {
return totalCost;
}
public void setTotalCost(double totalCost) {
this.totalCost = totalCost;
}
public Map<String, Map<String, Integer>> getModuleInstanceCount() {
return moduleInstanceCount;
}
public void setModuleInstanceCount(
Map<String, Map<String, Integer>> moduleInstanceCount) {
this.moduleInstanceCount = moduleInstanceCount;
}
}

View File

@@ -0,0 +1,575 @@
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009-2012, The University of Melbourne, Australia
*/
package org.fog.entities;
import java.util.ArrayList;
import java.util.List;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.lists.HostList;
import org.cloudbus.cloudsim.lists.PeList;
import org.fog.utils.GeoCoverage;
public class FogDeviceCharacteristics extends DatacenterCharacteristics{
/** The geographical coverage of the fog device */
private GeoCoverage geoCoverage;
/** The resource id -- setup when Resource is created. */
private int id;
/** The architecture. */
private String architecture;
/** The os. */
private String os;
/** The host list. */
private List<? extends Host> hostList;
/** The time zone -- difference from GMT. */
private double timeZone;
/** Price/CPU-unit if unit = sec., then G$/CPU-sec. */
private double costPerSecond;
/** Resource Types -- allocation policy. */
private int allocationPolicy;
/** Time-shared system using Round-Robin algorithm. */
public static final int TIME_SHARED = 0;
/** Spaced-shared system using First Come First Serve (FCFS) algorithm. */
public static final int SPACE_SHARED = 1;
/** Assuming all PEs in all Machines have the same rating. */
public static final int OTHER_POLICY_SAME_RATING = 2;
/**
* Assuming all PEs in a Machine have the same rating. However, each Machine has different
* rating to each other.
*/
public static final int OTHER_POLICY_DIFFERENT_RATING = 3;
/** A resource that supports Advanced Reservation mechanisms. */
public static final int ADVANCE_RESERVATION = 4;
/** The vmm. */
private String vmm;
/** The cost per mem. */
private double costPerMem;
/** The cost per storage. */
private double costPerStorage;
/** The cost per bw. */
private double costPerBw;
/**
*
* @param architecture the architecture of a resource
* @param os the operating system used
* @param vmm the virtual machine monitor used
* @param hostList list of machines in a resource
* @param timeZone local time zone of a user that owns this reservation. Time zone should be of
* range [GMT-12 ... GMT+13]
* @param costPerSec the cost per sec to use this resource
* @param costPerMem the cost to use memory in this resource
* @param costPerStorage the cost to use storage in this resource
* @param costPerBw the cost per bw
* @pre architecture != null
* @pre OS != null
* @pre VMM != null
* @pre machineList != null
* @pre timeZone >= -12 && timeZone <= 13
* @pre costPerSec >= 0.0
* @pre costPerMem >= 0
* @pre costPerStorage >= 0
* @post $none
*/
@SuppressWarnings("serial")
public FogDeviceCharacteristics(
String architecture,
String os,
String vmm,
final Host host,
double timeZone,
double costPerSec,
double costPerMem,
double costPerStorage,
double costPerBw) {
super(architecture, os, vmm, new ArrayList<Host>(){{add(host);}} , timeZone, costPerSec, costPerMem, costPerStorage, costPerBw);
setHostList(new ArrayList<Host>(){{add(host);}});
setId(-1);
setArchitecture(architecture);
setOs(os);
setHostList(hostList);
setAllocationPolicy(allocationPolicy);
setCostPerSecond(costPerSec);
setTimeZone(0.0);
setVmm(vmm);
setCostPerMem(costPerMem);
setCostPerStorage(costPerStorage);
setCostPerBw(costPerBw);
}
/**
* Gets the name of a resource.
*
* @return the resource name
* @pre $none
* @post $result != null
*/
public String getResourceName() {
return CloudSim.getEntityName(getId());
}
/**
* Gets a Machine with at least one empty Pe.
*
* @return a Machine object or if not found
* @pre $none
* @post $none
*/
public Host getHostWithFreePe() {
return HostList.getHostWithFreePe(getHostList());
}
/**
* Gets a Machine with at least a given number of free Pe.
*
* @param peNumber the pe number
* @return a Machine object or if not found
* @pre $none
* @post $none
*/
public Host getHostWithFreePe(int peNumber) {
return HostList.getHostWithFreePe(getHostList(), peNumber);
}
/**
* Gets Millions Instructions Per Second (MIPS) Rating of a Processing Element (Pe). It is
* assumed all PEs' rating is same in a given machine.
*
* @return the MIPS Rating or if no PEs are exists.
* @pre $none
* @post $result >= -1
*/
public int getMipsOfOnePe() {
if (getHostList().size() == 0) {
return -1;
}
return PeList.getMips(getHostList().get(0).getPeList(), 0);
}
/**
* Gets Millions Instructions Per Second (MIPS) Rating of a Processing Element (Pe). It is
* essential to use this method when a resource is made up of heterogenous PEs/machines.
*
* @param id the machine ID
* @param peId the Pe ID
* @return the MIPS Rating or if no PEs are exists.
* @pre id >= 0
* @pre peID >= 0
* @post $result >= -1
*/
public int getMipsOfOnePe(int id, int peId) {
if (getHostList().size() == 0) {
return -1;
}
return PeList.getMips(HostList.getById(getHostList(), id).getPeList(), peId);
}
/**
* Gets the total MIPS rating, which is the sum of MIPS rating of all machines in a resource.
* <p>
* Total MIPS rating for:
* <ul>
* <li>TimeShared = 1 Rating of a Pe * Total number of PEs
* <li>Other policy same rating = same as TimeShared
* <li>SpaceShared = Sum of all PEs in all Machines
* <li>Other policy different rating = same as SpaceShared
* <li>Advance Reservation = 0 or unknown. You need to calculate this manually.
* </ul>
*
* @return the sum of MIPS ratings
* @pre $none
* @post $result >= 0
*/
public int getMips() {
int mips = 0;
switch (getAllocationPolicy()) {
// Assuming all PEs in all Machine have same rating.
case FogDeviceCharacteristics.TIME_SHARED:
case FogDeviceCharacteristics.OTHER_POLICY_SAME_RATING:
mips = getMipsOfOnePe() * HostList.getNumberOfPes(getHostList());
break;
// Assuming all PEs in a given Machine have the same rating.
// But different machines in a Cluster can have different rating
case FogDeviceCharacteristics.SPACE_SHARED:
case FogDeviceCharacteristics.OTHER_POLICY_DIFFERENT_RATING:
for (Host host : getHostList()) {
mips += host.getTotalMips();
}
break;
default:
break;
}
return mips;
}
/**
* Gets the CPU time given the specified parameters (only for TIME_SHARED). <tt>NOTE:</tt> The
* CPU time for SPACE_SHARED and ADVANCE_RESERVATION are not yet implemented.
*
* @param cloudletLength the length of a Cloudlet
* @param load the load of a Cloudlet
* @return the CPU time
* @pre cloudletLength >= 0.0
* @pre load >= 0.0
* @post $result >= 0.0
*/
public double getCpuTime(double cloudletLength, double load) {
double cpuTime = 0.0;
switch (getAllocationPolicy()) {
case FogDeviceCharacteristics.TIME_SHARED:
cpuTime = cloudletLength / (getMipsOfOnePe() * (1.0 - load));
break;
default:
break;
}
return cpuTime;
}
/**
* Gets the total number of PEs for all Machines.
*
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public int getNumberOfPes() {
return HostList.getNumberOfPes(getHostList());
}
/**
* Gets the total number of <tt>FREE</tt> or non-busy PEs for all Machines.
*
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public int getNumberOfFreePes() {
return HostList.getNumberOfFreePes(getHostList());
}
/**
* Gets the total number of <tt>BUSY</tt> PEs for all Machines.
*
* @return number of PEs
* @pre $none
* @post $result >= 0
*/
public int getNumberOfBusyPes() {
return HostList.getNumberOfBusyPes(getHostList());
}
/**
* Sets the particular Pe status on a Machine.
*
* @param status Pe status, either <tt>Pe.FREE</tt> or <tt>Pe.BUSY</tt>
* @param hostId Machine ID
* @param peId Pe id
* @return otherwise (Machine id or Pe id might not be exist)
* @pre machineID >= 0
* @pre peID >= 0
* @post $none
*/
public boolean setPeStatus(int status, int hostId, int peId) {
return HostList.setPeStatus(getHostList(), status, hostId, peId);
}
/**
* Gets the cost per Millions Instruction (MI) associated with a resource.
*
* @return the cost using a resource
* @pre $none
* @post $result >= 0.0
*/
public double getCostPerMi() {
return getCostPerSecond() / getMipsOfOnePe();
}
/**
* Gets the total number of machines.
*
* @return total number of machines this resource has.
*/
public int getNumberOfHosts() {
return getHostList().size();
}
/**
* Gets the current number of failed machines.
*
* @return current number of failed machines this resource has.
*/
public int getNumberOfFailedHosts() {
int numberOfFailedHosts = 0;
for (Host host : getHostList()) {
if (host.isFailed()) {
numberOfFailedHosts++;
}
}
return numberOfFailedHosts;
}
/**
* Checks whether all machines of this resource are working properly or not.
*
* @return if all machines are working, otherwise
*/
public boolean isWorking() {
boolean result = false;
if (getNumberOfFailedHosts() == 0) {
result = true;
}
return result;
}
/**
* Get the cost to use memory in this resource.
*
* @return the cost to use memory
*/
public double getCostPerMem() {
return costPerMem;
}
/**
* Sets cost to use memory.
*
* @param costPerMem cost to use memory
* @pre costPerMem >= 0
* @post $none
*/
public void setCostPerMem(double costPerMem) {
this.costPerMem = costPerMem;
}
/**
* Get the cost to use storage in this resource.
*
* @return the cost to use storage
*/
public double getCostPerStorage() {
return costPerStorage;
}
/**
* Sets cost to use storage.
*
* @param costPerStorage cost to use storage
* @pre costPerStorage >= 0
* @post $none
*/
public void setCostPerStorage(double costPerStorage) {
this.costPerStorage = costPerStorage;
}
/**
* Get the cost to use bandwidth in this resource.
*
* @return the cost to use bw
*/
public double getCostPerBw() {
return costPerBw;
}
/**
* Sets cost to use bw cost to use bw.
*
* @param costPerBw the cost per bw
* @pre costPerBw >= 0
* @post $none
*/
public void setCostPerBw(double costPerBw) {
this.costPerBw = costPerBw;
}
/**
* Gets the VMM in use in the datacenter.
*
* @return the VMM name
*/
public String getVmm() {
return vmm;
}
/**
* Gets the id.
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(int id) {
this.id = id;
}
/**
* Gets the architecture.
*
* @return the architecture
*/
protected String getArchitecture() {
return architecture;
}
/**
* Sets the architecture.
*
* @param architecture the new architecture
*/
protected void setArchitecture(String architecture) {
this.architecture = architecture;
}
/**
* Gets the os.
*
* @return the os
*/
protected String getOs() {
return os;
}
/**
* Sets the os.
*
* @param os the new os
*/
protected void setOs(String os) {
this.os = os;
}
/**
* Gets the host list.
*
* @param <T> the generic type
* @return the host list
*/
@SuppressWarnings("unchecked")
public <T extends Host> List<T> getHostList() {
return (List<T>) hostList;
}
/**
* Sets the host list.
*
* @param <T> the generic type
* @param hostList the new host list
*/
protected <T extends Host> void setHostList(List<T> hostList) {
this.hostList = hostList;
}
/**
* Gets the time zone.
*
* @return the time zone
*/
protected double getTimeZone() {
return timeZone;
}
/**
* Sets the time zone.
*
* @param timeZone the new time zone
*/
protected void setTimeZone(double timeZone) {
this.timeZone = timeZone;
}
/**
* Gets the cost per second.
*
* @return the cost per second
*/
public double getCostPerSecond() {
return costPerSecond;
}
/**
* Sets the cost per second.
*
* @param costPerSecond the new cost per second
*/
protected void setCostPerSecond(double costPerSecond) {
this.costPerSecond = costPerSecond;
}
/**
* Gets the allocation policy.
*
* @return the allocation policy
*/
protected int getAllocationPolicy() {
return allocationPolicy;
}
/**
* Sets the allocation policy.
*
* @param allocationPolicy the new allocation policy
*/
protected void setAllocationPolicy(int allocationPolicy) {
this.allocationPolicy = allocationPolicy;
}
/**
* Sets the vmm.
*
* @param vmm the new vmm
*/
protected void setVmm(String vmm) {
this.vmm = vmm;
}
public GeoCoverage getGeoCoverage() {
return geoCoverage;
}
public void setGeoCoverage(GeoCoverage geoCoverage) {
this.geoCoverage = geoCoverage;
}
}

View File

@@ -0,0 +1,144 @@
package org.fog.entities;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.fog.application.AppLoop;
import org.fog.application.MyApplication;
import org.fog.utils.FogEvents;
import org.fog.utils.GeoLocation;
import org.fog.utils.Logger;
import org.fog.utils.TimeKeeper;
public class MyActuator extends SimEntity{
private int gatewayDeviceId;
private double latency;
private GeoLocation geoLocation;
private String appId;
private int userId;
private String actuatorType;
private MyApplication app;
public MyActuator(String name, int userId, String appId, int gatewayDeviceId, double latency, GeoLocation geoLocation, String actuatorType, String srcModuleName) {
super(name);
this.setAppId(appId);
this.gatewayDeviceId = gatewayDeviceId;
this.geoLocation = geoLocation;
setUserId(userId);
setMyActuatorType(actuatorType);
setLatency(latency);
}
public MyActuator(String name, int userId, String appId, String actuatorType) {
super(name);
this.setAppId(appId);
setUserId(userId);
setMyActuatorType(actuatorType);
}
@Override
public void startEntity() {
sendNow(gatewayDeviceId, FogEvents.ACTUATOR_JOINED, getLatency());
}
@Override
public void processEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.TUPLE_ARRIVAL:
processTupleArrival(ev);
break;
}
}
private void processTupleArrival(SimEvent ev) {
Tuple tuple = (Tuple)ev.getData();
Logger.debug(getName(), "Received tuple "+tuple.getCloudletId()+"on "+tuple.getDestModuleName());
String srcModule = tuple.getSrcModuleName();
String destModule = tuple.getDestModuleName();
MyApplication app = getApp();
for(AppLoop loop : app.getLoops()){
if(loop.hasEdge(srcModule, destModule) && loop.isEndModule(destModule)){
Double startTime = TimeKeeper.getInstance().getEmitTimes().get(tuple.getActualTupleId());
if(startTime==null)
break;
if(!TimeKeeper.getInstance().getLoopIdToCurrentAverage().containsKey(loop.getLoopId())){
TimeKeeper.getInstance().getLoopIdToCurrentAverage().put(loop.getLoopId(), 0.0);
TimeKeeper.getInstance().getLoopIdToCurrentNum().put(loop.getLoopId(), 0);
}
double currentAverage = TimeKeeper.getInstance().getLoopIdToCurrentAverage().get(loop.getLoopId());
int currentCount = TimeKeeper.getInstance().getLoopIdToCurrentNum().get(loop.getLoopId());
double delay = CloudSim.clock()- TimeKeeper.getInstance().getEmitTimes().get(tuple.getActualTupleId());
TimeKeeper.getInstance().getEmitTimes().remove(tuple.getActualTupleId());
double newAverage = (currentAverage*currentCount + delay)/(currentCount+1);
TimeKeeper.getInstance().getLoopIdToCurrentAverage().put(loop.getLoopId(), newAverage);
TimeKeeper.getInstance().getLoopIdToCurrentNum().put(loop.getLoopId(), currentCount+1);
break;
}
}
}
@Override
public void shutdownEntity() {
}
public int getGatewayDeviceId() {
return gatewayDeviceId;
}
public void setGatewayDeviceId(int gatewayDeviceId) {
this.gatewayDeviceId = gatewayDeviceId;
}
public GeoLocation getGeoLocation() {
return geoLocation;
}
public void setGeoLocation(GeoLocation geoLocation) {
this.geoLocation = geoLocation;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getMyActuatorType() {
return actuatorType;
}
public void setMyActuatorType(String actuatorType) {
this.actuatorType = actuatorType;
}
public MyApplication getApp() {
return app;
}
public void setApp(MyApplication app) {
this.app = app;
}
public double getLatency() {
return latency;
}
public void setLatency(double latency) {
this.latency = latency;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,234 @@
package org.fog.entities;
import java.util.ArrayList;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.MyApplication;
import org.fog.utils.FogEvents;
import org.fog.utils.FogUtils;
import org.fog.utils.GeoLocation;
import org.fog.utils.Logger;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.Distribution;
public class MySensor extends SimEntity{
private int gatewayDeviceId;
private GeoLocation geoLocation;
private long outputSize;
private String appId;
private int userId;
private String tupleType;
private String sensorName;
private String destModuleName;
private Distribution transmitDistribution;
private int controllerId;
private MyApplication app;
private double latency;
public MySensor(String name, int userId, String appId, int gatewayDeviceId, double latency, GeoLocation geoLocation,
Distribution transmitDistribution, int cpuLength, int nwLength, String tupleType, String destModuleName) {
super(name);
this.setAppId(appId);
this.gatewayDeviceId = gatewayDeviceId;
this.geoLocation = geoLocation;
this.outputSize = 3;
this.setTransmitDistribution(transmitDistribution);
setUserId(userId);
setDestModuleName(destModuleName);
setTupleType(tupleType);
setSensorName(sensorName);
setLatency(latency);
}
public MySensor(String name, int userId, String appId, int gatewayDeviceId, double latency, GeoLocation geoLocation,
Distribution transmitDistribution, String tupleType) {
super(name);
this.setAppId(appId);
this.gatewayDeviceId = gatewayDeviceId;
this.geoLocation = geoLocation;
this.outputSize = 3;
this.setTransmitDistribution(transmitDistribution);
setUserId(userId);
setTupleType(tupleType);
setSensorName(sensorName);
setLatency(latency);
}
/**
* This constructor is called from the code that generates PhysicalTopology from JSON
* @param name
* @param tupleType
* @param string
* @param userId
* @param appId
* @param transmitDistribution
*/
public MySensor(String name, String tupleType, int userId, String appId, Distribution transmitDistribution) {
super(name);
this.setAppId(appId);
this.setTransmitDistribution(transmitDistribution);
setTupleType(tupleType);
setSensorName(tupleType);
setUserId(userId);
}
public void transmit(){
AppEdge _edge = null;
for(AppEdge edge : getApp().getEdges()){
if(edge.getSource().equals(getTupleType()))
_edge = edge;
}
long cpuLength = (long) _edge.getTupleCpuLength();
long nwLength = (long) _edge.getTupleNwLength();
Tuple tuple = new Tuple(getAppId(), FogUtils.generateTupleId(), Tuple.UP, cpuLength, 1, nwLength, outputSize,
new UtilizationModelFull(), new UtilizationModelFull(), new UtilizationModelFull());
tuple.setUserId(getUserId());
tuple.setTupleType(getTupleType());
tuple.setDestModuleName(_edge.getDestination());
tuple.setSrcModuleName(getSensorName());
Logger.debug(getName(), "Sending tuple with tupleId = "+tuple.getCloudletId());
int actualTupleId = updateTimings(getSensorName(), tuple.getDestModuleName());
tuple.setActualTupleId(actualTupleId);
send(gatewayDeviceId, getLatency(), FogEvents.TUPLE_ARRIVAL,tuple);
}
private int updateTimings(String src, String dest){
MyApplication application = getApp();
for(AppLoop loop : application.getLoops()){
if(loop.hasEdge(src, dest)){
int tupleId = TimeKeeper.getInstance().getUniqueId();
if(!TimeKeeper.getInstance().getLoopIdToTupleIds().containsKey(loop.getLoopId()))
TimeKeeper.getInstance().getLoopIdToTupleIds().put(loop.getLoopId(), new ArrayList<Integer>());
TimeKeeper.getInstance().getLoopIdToTupleIds().get(loop.getLoopId()).add(tupleId);
TimeKeeper.getInstance().getEmitTimes().put(tupleId, CloudSim.clock());
return tupleId;
}
}
return -1;
}
@Override
public void startEntity() {
send(gatewayDeviceId, CloudSim.getMinTimeBetweenEvents(), FogEvents.SENSOR_JOINED, geoLocation);
send(getId(), getTransmitDistribution().getNextValue(), FogEvents.EMIT_TUPLE);
}
@Override
public void processEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.TUPLE_ACK:
//transmit(transmitDistribution.getNextValue());
break;
case FogEvents.EMIT_TUPLE:
transmit();
send(getId(), getTransmitDistribution().getNextValue(), FogEvents.EMIT_TUPLE);
break;
}
}
@Override
public void shutdownEntity() {
}
public int getGatewayDeviceId() {
return gatewayDeviceId;
}
public void setGatewayDeviceId(int gatewayDeviceId) {
this.gatewayDeviceId = gatewayDeviceId;
}
public GeoLocation getGeoLocation() {
return geoLocation;
}
public void setGeoLocation(GeoLocation geoLocation) {
this.geoLocation = geoLocation;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTupleType() {
return tupleType;
}
public void setTupleType(String tupleType) {
this.tupleType = tupleType;
}
public String getSensorName() {
return sensorName;
}
public void setSensorName(String sensorName) {
this.sensorName = sensorName;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getDestModuleName() {
return destModuleName;
}
public void setDestModuleName(String destModuleName) {
this.destModuleName = destModuleName;
}
public Distribution getTransmitDistribution() {
return transmitDistribution;
}
public void setTransmitDistribution(Distribution transmitDistribution) {
this.transmitDistribution = transmitDistribution;
}
public int getControllerId() {
return controllerId;
}
public void setControllerId(int controllerId) {
this.controllerId = controllerId;
}
public MyApplication getApp() {
return app;
}
public void setApp(MyApplication app) {
this.app = app;
}
public Double getLatency() {
return latency;
}
public void setLatency(Double latency) {
this.latency = latency;
}
}

View File

@@ -0,0 +1,29 @@
package org.fog.entities;
import java.util.List;
public class PhysicalTopology {
private List<FogDevice> fogDevices;
private List<Sensor> sensors;
private List<Actuator> actuators;
public List<FogDevice> getFogDevices() {
return fogDevices;
}
public void setFogDevices(List<FogDevice> fogDevices) {
this.fogDevices = fogDevices;
}
public List<Sensor> getSensors() {
return sensors;
}
public void setSensors(List<Sensor> sensors) {
this.sensors = sensors;
}
public List<Actuator> getActuators() {
return actuators;
}
public void setActuators(List<Actuator> actuators) {
this.actuators = actuators;
}
}

View File

@@ -0,0 +1,234 @@
package org.fog.entities;
import java.util.ArrayList;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.utils.FogEvents;
import org.fog.utils.FogUtils;
import org.fog.utils.GeoLocation;
import org.fog.utils.Logger;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.Distribution;
public class Sensor extends SimEntity{
private int gatewayDeviceId;
private GeoLocation geoLocation;
private long outputSize;
private String appId;
private int userId;
private String tupleType;
private String sensorName;
private String destModuleName;
private Distribution transmitDistribution;
private int controllerId;
private Application app;
private double latency;
public Sensor(String name, int userId, String appId, int gatewayDeviceId, double latency, GeoLocation geoLocation,
Distribution transmitDistribution, int cpuLength, int nwLength, String tupleType, String destModuleName) {
super(name);
this.setAppId(appId);
this.gatewayDeviceId = gatewayDeviceId;
this.geoLocation = geoLocation;
this.outputSize = 3;
this.setTransmitDistribution(transmitDistribution);
setUserId(userId);
setDestModuleName(destModuleName);
setTupleType(tupleType);
setSensorName(sensorName);
setLatency(latency);
}
public Sensor(String name, int userId, String appId, int gatewayDeviceId, double latency, GeoLocation geoLocation,
Distribution transmitDistribution, String tupleType) {
super(name);
this.setAppId(appId);
this.gatewayDeviceId = gatewayDeviceId;
this.geoLocation = geoLocation;
this.outputSize = 3;
this.setTransmitDistribution(transmitDistribution);
setUserId(userId);
setTupleType(tupleType);
setSensorName(sensorName);
setLatency(latency);
}
/**
* This constructor is called from the code that generates PhysicalTopology from JSON
* @param name
* @param tupleType
* @param string
* @param userId
* @param appId
* @param transmitDistribution
*/
public Sensor(String name, String tupleType, int userId, String appId, Distribution transmitDistribution) {
super(name);
this.setAppId(appId);
this.setTransmitDistribution(transmitDistribution);
setTupleType(tupleType);
setSensorName(tupleType);
setUserId(userId);
}
public void transmit(){
AppEdge _edge = null;
for(AppEdge edge : getApp().getEdges()){
if(edge.getSource().equals(getTupleType()))
_edge = edge;
}
long cpuLength = (long) _edge.getTupleCpuLength();
long nwLength = (long) _edge.getTupleNwLength();
Tuple tuple = new Tuple(getAppId(), FogUtils.generateTupleId(), Tuple.UP, cpuLength, 1, nwLength, outputSize,
new UtilizationModelFull(), new UtilizationModelFull(), new UtilizationModelFull());
tuple.setUserId(getUserId());
tuple.setTupleType(getTupleType());
tuple.setDestModuleName(_edge.getDestination());
tuple.setSrcModuleName(getSensorName());
Logger.debug(getName(), "Sending tuple with tupleId = "+tuple.getCloudletId());
int actualTupleId = updateTimings(getSensorName(), tuple.getDestModuleName());
tuple.setActualTupleId(actualTupleId);
send(gatewayDeviceId, getLatency(), FogEvents.TUPLE_ARRIVAL,tuple);
}
private int updateTimings(String src, String dest){
Application application = getApp();
for(AppLoop loop : application.getLoops()){
if(loop.hasEdge(src, dest)){
int tupleId = TimeKeeper.getInstance().getUniqueId();
if(!TimeKeeper.getInstance().getLoopIdToTupleIds().containsKey(loop.getLoopId()))
TimeKeeper.getInstance().getLoopIdToTupleIds().put(loop.getLoopId(), new ArrayList<Integer>());
TimeKeeper.getInstance().getLoopIdToTupleIds().get(loop.getLoopId()).add(tupleId);
TimeKeeper.getInstance().getEmitTimes().put(tupleId, CloudSim.clock());
return tupleId;
}
}
return -1;
}
@Override
public void startEntity() {
send(gatewayDeviceId, CloudSim.getMinTimeBetweenEvents(), FogEvents.SENSOR_JOINED, geoLocation);
send(getId(), getTransmitDistribution().getNextValue(), FogEvents.EMIT_TUPLE);
}
@Override
public void processEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.TUPLE_ACK:
//transmit(transmitDistribution.getNextValue());
break;
case FogEvents.EMIT_TUPLE:
transmit();
send(getId(), getTransmitDistribution().getNextValue(), FogEvents.EMIT_TUPLE);
break;
}
}
@Override
public void shutdownEntity() {
}
public int getGatewayDeviceId() {
return gatewayDeviceId;
}
public void setGatewayDeviceId(int gatewayDeviceId) {
this.gatewayDeviceId = gatewayDeviceId;
}
public GeoLocation getGeoLocation() {
return geoLocation;
}
public void setGeoLocation(GeoLocation geoLocation) {
this.geoLocation = geoLocation;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getTupleType() {
return tupleType;
}
public void setTupleType(String tupleType) {
this.tupleType = tupleType;
}
public String getSensorName() {
return sensorName;
}
public void setSensorName(String sensorName) {
this.sensorName = sensorName;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getDestModuleName() {
return destModuleName;
}
public void setDestModuleName(String destModuleName) {
this.destModuleName = destModuleName;
}
public Distribution getTransmitDistribution() {
return transmitDistribution;
}
public void setTransmitDistribution(Distribution transmitDistribution) {
this.transmitDistribution = transmitDistribution;
}
public int getControllerId() {
return controllerId;
}
public void setControllerId(int controllerId) {
this.controllerId = controllerId;
}
public Application getApp() {
return app;
}
public void setApp(Application app) {
this.app = app;
}
public Double getLatency() {
return latency;
}
public void setLatency(Double latency) {
this.latency = latency;
}
}

View File

@@ -0,0 +1,126 @@
package org.fog.entities;
import java.util.HashMap;
import java.util.Map;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.UtilizationModel;
public class Tuple extends Cloudlet{
public static final int UP = 1;
public static final int DOWN = 2;
public static final int ACTUATOR = 3;
private String appId;
private String tupleType;
private String destModuleName;
private String srcModuleName;
private int actualTupleId;
private int direction;
private int actuatorId;
private int sourceDeviceId;
private int sourceModuleId;
/**
* Map to keep track of which module instances has a tuple traversed.
*
* Map from moduleName to vmId of a module instance
*/
private Map<String, Integer> moduleCopyMap;
public Tuple(String appId, int cloudletId, int direction, long cloudletLength, int pesNumber,
long cloudletFileSize, long cloudletOutputSize,
UtilizationModel utilizationModelCpu,
UtilizationModel utilizationModelRam,
UtilizationModel utilizationModelBw) {
super(cloudletId, cloudletLength, pesNumber, cloudletFileSize,
cloudletOutputSize, utilizationModelCpu, utilizationModelRam,
utilizationModelBw);
setAppId(appId);
setDirection(direction);
setSourceDeviceId(-1);
setModuleCopyMap(new HashMap<String, Integer>());
}
public int getActualTupleId() {
return actualTupleId;
}
public void setActualTupleId(int actualTupleId) {
this.actualTupleId = actualTupleId;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getTupleType() {
return tupleType;
}
public void setTupleType(String tupleType) {
this.tupleType = tupleType;
}
public String getDestModuleName() {
return destModuleName;
}
public void setDestModuleName(String destModuleName) {
this.destModuleName = destModuleName;
}
public String getSrcModuleName() {
return srcModuleName;
}
public void setSrcModuleName(String srcModuleName) {
this.srcModuleName = srcModuleName;
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public int getActuatorId() {
return actuatorId;
}
public void setActuatorId(int actuatorId) {
this.actuatorId = actuatorId;
}
public int getSourceDeviceId() {
return sourceDeviceId;
}
public void setSourceDeviceId(int sourceDeviceId) {
this.sourceDeviceId = sourceDeviceId;
}
public Map<String, Integer> getModuleCopyMap() {
return moduleCopyMap;
}
public void setModuleCopyMap(Map<String, Integer> moduleCopyMap) {
this.moduleCopyMap = moduleCopyMap;
}
public int getSourceModuleId() {
return sourceModuleId;
}
public void setSourceModuleId(int sourceModuleId) {
this.sourceModuleId = sourceModuleId;
}
}

View File

@@ -0,0 +1,40 @@
package org.fog.gui.core;
import java.io.Serializable;
public class ActuatorGui extends Node implements Serializable{
private static final long serialVersionUID = 4087896123649020073L;
private String name;
private String actuatorType;
public ActuatorGui(String name, String actuatorType){
super(name, "ACTUATOR");
setName(name);
setActuatorType(actuatorType);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Actuator []";
}
public String getActuatorType() {
return actuatorType;
}
public void setActuatorType(String actuatorType) {
this.actuatorType = actuatorType;
}
}

View File

@@ -0,0 +1,34 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class ActuatorModule extends Node {
private static final long serialVersionUID = 804858850147477656L;
String actuatorType;
public ActuatorModule() {
}
public ActuatorModule(String actuatorType) {
super(actuatorType, "ACTUATOR_MODULE");
setActuatorType(actuatorType);
}
public String getActuatorType() {
return actuatorType;
}
public void setActuatorType(String actuatorType) {
this.actuatorType = actuatorType;
}
@Override
public String toString() {
return "Node []";
}
}

View File

@@ -0,0 +1,25 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class AppModule extends Node {
private static final long serialVersionUID = 804858850147477656L;
public AppModule() {
}
public AppModule(String name) {
super(name, "APP_MODULE");
}
@Override
public String toString() {
return "Node []";
}
}

View File

@@ -0,0 +1,323 @@
package org.fog.gui.core;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.fog.utils.distribution.DeterministicDistribution;
import org.fog.utils.distribution.Distribution;
import org.fog.utils.distribution.NormalDistribution;
import org.fog.utils.distribution.UniformDistribution;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class Bridge {
private static Node getNode(Graph graph, String name){
for(Node node : graph.getAdjacencyList().keySet()){
if(node!=null){
if(node.getName().equals(name)){
return node;
}
}
}
return null;
}
// convert from JSON object to Graph object
public static Graph jsonToGraph(String fileName, int type){
Graph graph = new Graph();
// type 0->physical topology 1->virtual topology
if(0 == type){
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(fileName));
JSONArray nodes = (JSONArray) doc.get("nodes");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter =nodes.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String nodeType = (String) node.get("type");
String nodeName = (String) node.get("name");
if(nodeType.equalsIgnoreCase("host")){ //host
long pes = (Long) node.get("pes");
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long storage = (Long) node.get("storage");
long bw = new BigDecimal((Long)node.get("bw")).intValueExact();
int num = 1;
if (node.get("nums")!= null)
num = new BigDecimal((Long)node.get("nums")).intValueExact();
for(int n = 0; n< num; n++) {
Node hNode = new HostNode(nodeName, nodeType, pes, mips, ram, storage, bw);
graph.addNode(hNode);
}
} else if(nodeType.equals("FOG_DEVICE")){
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long upBw = new BigDecimal((Long)node.get("upBw")).intValueExact();
long downBw = new BigDecimal((Long)node.get("downBw")).intValueExact();
int level = new BigDecimal((Long)node.get("level")).intValue();
double rate = new BigDecimal((Double)node.get("ratePerMips")).doubleValue();
Node fogDevice = new FogDeviceGui(nodeName, mips, ram, upBw, downBw, level, rate);
graph.addNode(fogDevice);
} else if(nodeType.equals("SENSOR")){
String sensorType = node.get("sensorType").toString();
int distType = new BigDecimal((Long)node.get("distribution")).intValue();
Distribution distribution = null;
if(distType == Distribution.DETERMINISTIC)
distribution = new DeterministicDistribution(new BigDecimal((Double)node.get("value")).doubleValue());
else if(distType == Distribution.NORMAL){
distribution = new NormalDistribution(new BigDecimal((Double)node.get("mean")).doubleValue(),
new BigDecimal((Double)node.get("stdDev")).doubleValue());
} else if(distType == Distribution.UNIFORM){
distribution = new UniformDistribution(new BigDecimal((Double)node.get("min")).doubleValue(),
new BigDecimal((Double)node.get("max")).doubleValue());
}
System.out.println("Sensor type : "+sensorType);
Node sensor = new SensorGui(nodeName, sensorType, distribution);
graph.addNode(sensor);
} else if(nodeType.equals("ACTUATOR")){
String actuatorType = node.get("actuatorType").toString();
Node actuator = new ActuatorGui(nodeName, actuatorType);
graph.addNode(actuator);
} else { //switch
int bw = new BigDecimal((Long)node.get("bw")).intValueExact();
long iops = (Long) node.get("iops");
int upports = new BigDecimal((Long)node.get("upports")).intValueExact();
int downports = new BigDecimal((Long)node.get("downports")).intValueExact();
Node sNode = new SwitchNode(nodeName, nodeType, iops, upports, downports, bw);
graph.addNode(sNode);
}
}
JSONArray links = (JSONArray) doc.get("links");
@SuppressWarnings("unchecked")
Iterator<JSONObject> linksIter =links.iterator();
while(linksIter.hasNext()){
JSONObject link = linksIter.next();
String src = (String) link.get("source");
String dst = (String) link.get("destination");
double lat = (Double) link.get("latency");
Node source = (Node) getNode(graph, src);
Node target = (Node) getNode(graph, dst);
if(source!=null && target!=null){
System.out.println("Adding edge between "+source.getName()+" & "+target.getName());
Edge edge = new Edge(target, lat);
graph.addEdge(source, edge);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else if(1 == type){
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(fileName));
JSONArray nodes = (JSONArray) doc.get("nodes");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter = nodes.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String nodeType = (String) node.get("type");
String nodeName = (String) node.get("name");
int pes = new BigDecimal((Long)node.get("pes")).intValueExact();
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long size = (Long) node.get("size");
Node vmNode = new VmNode(nodeName, nodeType, size, pes, mips, ram);
graph.addNode(vmNode);
}
JSONArray links = (JSONArray) doc.get("links");
@SuppressWarnings("unchecked")
Iterator<JSONObject> linksIter = links.iterator();
while(linksIter.hasNext()){
JSONObject link = linksIter.next();
String name = (String) link.get("name");
String src = (String) link.get("source");
String dst = (String) link.get("destination");
Object reqBw = link.get("bandwidth");
long bw = 0;
if(reqBw != null)
bw = (Long) reqBw;
Node source = getNode(graph, src);
Node target = getNode(graph, dst);
Edge edge = new Edge(target, name, bw);
graph.addEdge(source, edge);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
System.out.println("############################");
System.out.println(graph.getAdjacencyList());
System.out.println("############################");
return graph;
}
// convert from Graph object to JSON object
@SuppressWarnings("unchecked")
public static String graphToJson(Graph graph){
System.out.println();
System.out.println("****************************");
System.out.println(graph.getAdjacencyList());
System.out.println("****************************");
if(graph.getAdjacencyList().size() < 1){
return "Graph is Empty";
}
Map<Node, List<Node>> edgeList = new HashMap<Node, List<Node>>();
JSONObject topo = new JSONObject();
JSONArray nodes = new JSONArray();
JSONArray links = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.getAdjacencyList().entrySet()) {
Node srcNode = entry.getKey();
// add node
JSONObject jobj = new JSONObject();
switch(srcNode.getType()){
case "ACTUATOR":
ActuatorGui actuator = (ActuatorGui)srcNode;
jobj.put("name", actuator.getName());
jobj.put("type", actuator.getType());
jobj.put("actuatorType", actuator.getActuatorType());
break;
case "SENSOR":
SensorGui sensor = (SensorGui)srcNode;
jobj.put("name", sensor.getName());
jobj.put("sensorType", sensor.getSensorType());
jobj.put("type", sensor.getType());
jobj.put("distribution", sensor.getDistributionType());
if(sensor.getDistributionType()==Distribution.DETERMINISTIC)
jobj.put("value", ((DeterministicDistribution)sensor.getDistribution()).getValue());
else if(sensor.getDistributionType()==Distribution.NORMAL){
jobj.put("mean", ((NormalDistribution)sensor.getDistribution()).getMean());
jobj.put("stdDev", ((NormalDistribution)sensor.getDistribution()).getStdDev());
} else if(sensor.getDistributionType()==Distribution.UNIFORM){
jobj.put("min", ((UniformDistribution)sensor.getDistribution()).getMin());
jobj.put("max", ((UniformDistribution)sensor.getDistribution()).getMax());
}
break;
case "FOG_DEVICE":
FogDeviceGui fogDevice = (FogDeviceGui)srcNode;
jobj.put("name", fogDevice.getName());
jobj.put("type", fogDevice.getType());
jobj.put("mips", fogDevice.getMips());
jobj.put("ram", fogDevice.getRam());
jobj.put("upBw", fogDevice.getUpBw());
jobj.put("downBw", fogDevice.getDownBw());
jobj.put("level", fogDevice.getLevel());
jobj.put("ratePerMips", fogDevice.getRatePerMips());
break;
case "host":
HostNode hNode = (HostNode)srcNode;
jobj.put("name", hNode.getName());
jobj.put("type", hNode.getType());
jobj.put("pes", hNode.getPes());
jobj.put("mips", hNode.getMips());
jobj.put("ram", hNode.getRam());
jobj.put("storage", hNode.getStorage());
jobj.put("bw", hNode.getBw());
break;
case "core":
case "edge":
SwitchNode sNode = (SwitchNode)srcNode;
jobj.put("name", sNode.getName());
jobj.put("type", sNode.getType());
jobj.put("iops", sNode.getIops());
jobj.put("upports", sNode.getDownports());
jobj.put("downports", sNode.getDownports());
jobj.put("bw", sNode.getBw());
break;
case "vm":
VmNode vNode = (VmNode)srcNode;
jobj.put("name", vNode.getName());
jobj.put("type", vNode.getType());
jobj.put("size", vNode.getSize());
jobj.put("pes", vNode.getPes());
jobj.put("mips", vNode.getMips());
jobj.put("ram", vNode.getRam());
break;
}
nodes.add(jobj);
// add edge
for (Edge edge : entry.getValue()) {
Node destNode = edge.getNode();
// check if edge exist (dest->src)
if (edgeList.containsKey(destNode) && edgeList.get(destNode).contains(srcNode)) {
continue;
}
JSONObject jobj2 = new JSONObject();
jobj2.put("source", srcNode.getName());
jobj2.put("destination", destNode.getName());
if("host"==destNode.getType() || "core"==destNode.getType() || "edge"==destNode.getType() ||
"FOG_DEVICE"==destNode.getType() || "SENSOR"==destNode.getType() || "ACTUATOR"==destNode.getType()){
jobj2.put("latency", edge.getLatency());
}else if("vm"==destNode.getName()){
if(edge.getBandwidth()>0){
jobj2.put("bandwidth", edge.getBandwidth());
}
}
links.add(jobj2);
// add exist edge to the edgeList
if (edgeList.containsKey(entry.getKey())) {
edgeList.get(entry.getKey()).add(edge.getNode());
} else {
List<Node> ns = new ArrayList<Node>();
ns.add(edge.getNode());
edgeList.put(entry.getKey(), ns);
}
}
}
topo.put("nodes", nodes);
topo.put("links", links);
StringWriter out = new StringWriter();
String jsonText = "";
try {
topo.writeJSONString(out);
jsonText = out.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(jsonText);
return jsonText;
}
}

View File

@@ -0,0 +1,36 @@
package org.fog.gui.core;
public class Coordinates {
private int x;
private int y;
public Coordinates() {
this.x = 0;
this.y = 0;
}
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Coordinates [abscissa=" + x + ", ordinate=" + y + "]";
}
}

View File

@@ -0,0 +1,93 @@
package org.fog.gui.core;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* The model that represents an edge with two vertexes, for physical link and virtual edge.
*
*/
public class Edge implements Serializable {
private static final long serialVersionUID = -356975278987708987L;
private Node dest = null;
private double latency = 0.0;
private String name = "";
private long bandwidth = 0;
/**
* Constructor.
*
* @param node the node that belongs to the edge.
*/
public Edge(Node to) {
this.dest = to;
}
/** physical topology link */
public Edge(Node to, double latency) {
this.dest = to;
this.latency = latency;
}
/** virtual virtual edge */
public Edge(Node to, String name, long bw) {
this.dest = to;
this.name = name;
this.bandwidth = bw;
}
/** copy edge */
public Edge(Node to, Map<String, Object> info){
this.dest = to;
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
public Node getNode() {
return dest;
}
public long getBandwidth() {
return bandwidth;
}
public double getLatency() {
return latency;
}
public Map<String, Object> getInfo() {
Map<String, Object> info = new HashMap<String, Object>();
info.put("name", this.name);
info.put("bandwidth",this.bandwidth);
info.put("latency", this.latency);
return info;
}
public void setInfo(Map<String, Object> info){
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
@Override
public String toString() {
return "Edge [dest=" + dest + "]";
}
}

View File

@@ -0,0 +1,94 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class FogDeviceGui extends Node {
private static final long serialVersionUID = -8635044061126993668L;
private int level;
private String name;
private long mips;
private int ram;
private long upBw;
private long downBw;
private double ratePerMips;
public FogDeviceGui() {
}
public FogDeviceGui(String name, long mips, int ram, long upBw, long downBw, int level, double rate) {
super(name, "FOG_DEVICE");
this.name = name;
this.mips = mips;
this.ram = ram;
this.upBw = upBw;
this.downBw = downBw;
this.level = level;
this.ratePerMips = rate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getMips() {
return mips;
}
public void setMips(long mips) {
this.mips = mips;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public long getUpBw() {
return upBw;
}
public void setUpBw(long upBw) {
this.upBw = upBw;
}
public long getDownBw() {
return downBw;
}
public void setDownBw(long downBw) {
this.downBw = downBw;
}
@Override
public String toString() {
return "FogDevice [mips=" + mips + " ram=" + ram + " upBw=" + upBw + " downBw=" + downBw + "]";
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public double getRatePerMips() {
return ratePerMips;
}
public void setRatePerMips(double ratePerMips) {
this.ratePerMips = ratePerMips;
}
}

View File

@@ -0,0 +1,153 @@
package org.fog.gui.core;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* A graph model. Normally a model should not have any logic, but in this case we implement logic to manipulate the
* adjacencyList like reorganizing, adding nodes, removing nodes, e.g
*
*/
public class Graph implements Serializable {
private static final long serialVersionUID = 745864022429447529L;
private Map<Node, List<Edge>> adjacencyList;
public Graph() {
// when creating a new graph ensure that a new adjacencyList is created
adjacencyList = new HashMap<Node, List<Edge>>();
}
public Graph(Map<Node, List<Edge>> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public void setAdjacencyList(Map<Node, List<Edge>> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public Map<Node, List<Edge>> getAdjacencyList() {
return adjacencyList;
}
/** Adds a given edge to the adjacency list. If the base node is not yet part of the adjacency list a new entry is added */
public void addEdge(Node key, Edge value) {
if (adjacencyList.containsKey(key)) {
if (adjacencyList.get(key) == null) {
adjacencyList.put(key, new ArrayList<Edge>());
}
// TODO: perhaps check if a value may not be added twice.
// add edge if not null
if (value != null) {
adjacencyList.get(key).add(value);
}
} else {
List<Edge> edges = new ArrayList<Edge>();
// add edge if not null
if (value != null) {
edges.add(value);
}
adjacencyList.put(key, edges);
}
// do bidirectional adding. Ugly duplicated code.
// only execute when there is an edge defined.
/*if (value != null) {
Edge reverseEdge = new Edge(key, value.getInfo());
if (adjacencyList.containsKey(value.getNode())) {
if (adjacencyList.get(value.getNode()) == null) {
adjacencyList.put(value.getNode(), new ArrayList<Edge>());
}
// TODO: perhaps check if a value may not be added twice.
// add edge if not null
if (reverseEdge != null) {
adjacencyList.get(value.getNode()).add(reverseEdge);
}
} else {
List<Edge> edges = new ArrayList<Edge>();
// add edge if not null
if (reverseEdge != null) {
edges.add(reverseEdge);
}
adjacencyList.put(value.getNode(), edges);
}
}*/
}
/** Simply adds a new node, without setting any edges */
public void addNode(Node node) {
addEdge(node, null);
}
public void removeEdge(Node key, Edge value) {
if (!adjacencyList.containsKey(key)) {
throw new IllegalArgumentException("The adjacency list does not contain a node for the given key: " + key);
}
List<Edge> edges = adjacencyList.get(key);
if (!edges.contains(value)) {
throw new IllegalArgumentException("The list of edges does not contain the given edge to remove: " + value);
}
edges.remove(value);
// remove bidirectional
List<Edge> reverseEdges = adjacencyList.get(value.getNode());
List<Edge> toRemove = new ArrayList<Edge>();
for (Edge edge : reverseEdges) {
if (edge.getNode().equals(key)) {
toRemove.add(edge);
}
}
//normally only one element
reverseEdges.removeAll(toRemove);
}
/** Deletes a node */
public void removeNode(Node key) {
if (!adjacencyList.containsKey(key)) {
throw new IllegalArgumentException("The adjacency list does not contain a node for the given key: " + key);
}
adjacencyList.remove(key);
// clean up all edges
for (Entry<Node, List<Edge>> entry : adjacencyList.entrySet()) {
List<Edge> toRemove = new ArrayList<Edge>();
for (Edge edge : entry.getValue()) {
if (edge.getNode().equals(key)) {
toRemove.add(edge);
}
}
entry.getValue().removeAll(toRemove);
}
}
public void clearGraph(){
adjacencyList.clear();
}
public String toJsonString(){
String jsonText = Bridge.graphToJson(this);
return jsonText;
}
@Override
public String toString() {
return "Graph [adjacencyList=" + adjacencyList + "]";
}
}

View File

@@ -0,0 +1,378 @@
package org.fog.gui.core;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.fog.utils.FogUtils;
/** Panel that displays a graph */
public class GraphView extends JPanel {
private static final long serialVersionUID = 1L;
private JPanel canvas;
private Graph graph;
private Image imgHost;
private Image imgSensor;
private Image imgSwitch;
private Image imgAppModule;
private Image imgActuator;
private Image imgSensorModule;
private Image imgActuatorModule;
public GraphView(final Graph graph) {
this.graph = graph;
imgHost = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/host.png"));
imgSwitch = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/disk.png"));
imgAppModule = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/module.png"));
imgSensor = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/sensor.png"));
imgActuator = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/actuator.png"));
imgSensorModule = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/sensorModule.png"));
imgActuatorModule = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/actuatorModule.png"));
initComponents();
}
private Map<Node, List<Node>> createChildrenMap(){
Map<Node, List<Node>> childrenMap = new HashMap<Node, List<Node>>();
for(Node node : graph.getAdjacencyList().keySet()){
if(node.getType().equals("FOG_DEVICE") && !childrenMap.containsKey(node))
childrenMap.put(node, new ArrayList<Node>());
List<Edge> edgeList = graph.getAdjacencyList().get(node);
for(Edge edge : edgeList){
Node neighbour = edge.getNode();
if(node.getType().equals("SENSOR") || node.getType().equals("ACTUATOR")){
if(!childrenMap.containsKey(neighbour)){
childrenMap.put(neighbour, new ArrayList<Node>());
}
childrenMap.get(neighbour).add(node);
} else if(neighbour.getType().equals("SENSOR") || neighbour.getType().equals("ACTUATOR")){
if(!childrenMap.containsKey(node)){
childrenMap.put(node, new ArrayList<Node>());
}
childrenMap.get(node).add(neighbour);
}else {
Node child = (((FogDeviceGui)node).getLevel() > ((FogDeviceGui)neighbour).getLevel())?node:neighbour;
Node parent = (((FogDeviceGui)node).getLevel() < ((FogDeviceGui)neighbour).getLevel())?node:neighbour;
if(!childrenMap.containsKey(parent)){
childrenMap.put(parent, new ArrayList<Node>());
}
childrenMap.get(parent).add(child);
}
}
}
return childrenMap;
}
@SuppressWarnings("serial")
private void initComponents() {
canvas = new JPanel() {
@Override
public void paint(Graphics g) {
if (graph.getAdjacencyList() == null) {
return;
}
Map<Node, Coordinates> coordForNodes = new HashMap<Node, Coordinates>();
/*int offsetX = canvas.getWidth() / 2;
int offsetY = canvas.getHeight() / 2;*/
System.out.println("sys:"+canvas.getWidth() + ":" + canvas.getHeight());
int height = 40;
/*double angle = 2 * Math.PI / graph.getAdjacencyList().keySet().size();
int radius = offsetY / 2 - 20;*/
FontMetrics f = g.getFontMetrics();
int nodeHeight = Math.max(height, f.getHeight());
int nodeWidth = nodeHeight;
int maxLevel=-1, minLevel=FogUtils.MAX;
Map<Integer, List<Node>> levelMap = new HashMap<Integer, List<Node>>();
List<Node> endpoints = new ArrayList<Node>();
for (Node node : graph.getAdjacencyList().keySet()) {
if(node.getType().equals("FOG_DEVICE")){
int level = ((FogDeviceGui)node).getLevel();
if(!levelMap.containsKey(level))
levelMap.put(level, new ArrayList<Node>());
levelMap.get(level).add(node);
if(level > maxLevel)
maxLevel = level;
if(level < minLevel)
minLevel = level;
} else if(node.getType().equals("SENSOR") || node.getType().equals("ACTUATOR")){
endpoints.add(node);
}
}
double yDist = canvas.getHeight()/(maxLevel-minLevel+3);
System.out.println("===================\n================\n=============");
Map<Integer, List<PlaceHolder>> levelToPlaceHolderMap = new HashMap<Integer, List<PlaceHolder>>();
int k=1;
for(int i=minLevel;i<=maxLevel;i++, k++){
double xDist = canvas.getWidth()/(levelMap.get(i).size()+1);
for(int j=1;j<=levelMap.get(i).size();j++){
int x = (int)xDist*j;
int y = (int)yDist*k;
if(!levelToPlaceHolderMap.containsKey(i))
levelToPlaceHolderMap.put(i, new ArrayList<PlaceHolder>());
levelToPlaceHolderMap.get(i).add(new PlaceHolder(x, y));
//coordForNodes.put(node, new Coordinates(x, y));
//node.setCoordinate(new Coordinates(x, y));
}
}
List<PlaceHolder> endpointPlaceHolders = new ArrayList<PlaceHolder>();
double xDist = canvas.getWidth()/(endpoints.size()+1);
for(int i=0;i<endpoints.size();i++){
Node node = endpoints.get(i);
int x = (int)xDist*(i+1);
int y = (int)yDist*k;
endpointPlaceHolders.add(new PlaceHolder(x, y));
coordForNodes.put(node, new Coordinates(x, y));
node.setCoordinate(new Coordinates(x, y));
}
for (Node node : graph.getAdjacencyList().keySet()) {
if(node.getType().equals("FOG_DEVICE")||node.getType().equals("SENSOR")||node.getType().equals("ACTUATOR"))
continue;
// calculate coordinates
/*int x = Double.valueOf(offsetX + Math.cos(i * angle) * radius).intValue();
int y = Double.valueOf(offsetY + Math.sin(i * angle) * radius).intValue();*/
//coordForNodes.put(node, new Coordinates(x, y));
//node.setCoordinate(new Coordinates(x, y));
}
coordForNodes = getCoordForNodes(levelToPlaceHolderMap, endpointPlaceHolders, levelMap, endpoints, minLevel, maxLevel);
System.out.println("COORD MAP"+coordForNodes);
Map<Node, List<Node>> drawnList = new HashMap<Node, List<Node>>();
for (Entry<Node, Coordinates> entry : coordForNodes.entrySet()) {
// first paint a single node for testing.
g.setColor(Color.black);
// int nodeWidth = Math.max(width, f.stringWidth(entry.getKey().getNodeText()) + width / 2);
Coordinates wrapper = entry.getValue();
String nodeName = entry.getKey().getName();
switch(entry.getKey().getType()){
case "host":
g.drawImage(imgHost, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
break;
case "APP_MODULE":
g.drawImage(imgAppModule, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "core":
case "edge":
g.drawImage(imgSwitch, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
break;
case "FOG_DEVICE":
g.drawImage(imgHost, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "SENSOR":
g.drawImage(imgSensor, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "ACTUATOR":
g.drawImage(imgActuator, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "SENSOR_MODULE":
g.drawImage(imgSensorModule, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
case "ACTUATOR_MODULE":
g.drawImage(imgActuatorModule, wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight, this);
g.drawString(nodeName, wrapper.getX() - f.stringWidth(nodeName) / 2, wrapper.getY() + nodeHeight);
break;
}
//g.setColor(Color.white);
//g.fillOval(wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight);
//g.setColor(Color.black);
//g.drawOval(wrapper.getX() - nodeWidth / 2, wrapper.getY() - nodeHeight / 2, nodeWidth, nodeHeight);
//System.out.println((wrapper.getX())+" "+(wrapper.getY()));
//g.drawString(entry.getKey().getName(), wrapper.getX() - f.stringWidth(entry.getKey().getName()) / 2, wrapper.getY() + f.getHeight() / 2);
}
// draw edges first
// TODO: we draw one edge two times at the moment because we have an undirected graph. But this
// shouldn`t matter because we have the same edge costs and no one will see in. Perhaps refactor later.
for (Entry<Node, List<Edge>> entry : graph.getAdjacencyList().entrySet()) {
Coordinates startNode = coordForNodes.get(entry.getKey());
System.out.println("Start Node : "+entry.getKey().getName());
for (Edge edge : entry.getValue()) {
/*
// if other direction was drawn already continue
if (drawnList.containsKey(edge.getNode()) && drawnList.get(edge.getNode()).contains(entry.getKey())) {
continue;
}
*/
Coordinates targetNode = coordForNodes.get(edge.getNode());
System.out.println("Target Node : "+edge.getNode().getName());
g.setColor(Color.RED);
g.drawLine(startNode.getX(), startNode.getY(), targetNode.getX(), targetNode.getY());
//drawArrow(g, startNode.getX(), startNode.getY(), targetNode.getX(), targetNode.getY());
// add drawn edges to the drawnList
if (drawnList.containsKey(entry.getKey())) {
drawnList.get(entry.getKey()).add(edge.getNode());
} else {
List<Node> nodes = new ArrayList<Node>();
nodes.add(edge.getNode());
drawnList.put(entry.getKey(), nodes);
}
/*int labelX = (startNode.getX() - targetNode.getX()) / 2;
int labelY = (startNode.getY() - targetNode.getY()) / 2;
labelX *= -1;
labelY *= -1;
labelX += startNode.getX();
labelY += startNode.getY();
*/
//g.setColor(Color.BLACK);
//g.drawString(String.valueOf(edge.getInfo()), labelX - f.stringWidth(String.valueOf(edge.getInfo())) / 2, labelY + f.getHeight() / 2);
}
}
}
};
JScrollPane scrollPane = new JScrollPane(canvas);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(scrollPane);
}
protected Map<Node, Coordinates> getCoordForNodes(
Map<Integer, List<PlaceHolder>> levelToPlaceHolderMap,
List<PlaceHolder> endpointPlaceHolders,
Map<Integer, List<Node>> levelMap, List<Node> endpoints, int minLevel, int maxLevel) {
// TODO Auto-generated method stub
Map<Node, Coordinates> coordForNodesMap = new HashMap<Node, Coordinates>();
Map<Node, List<Node>> childrenMap = createChildrenMap();
for(Node node : graph.getAdjacencyList().keySet())node.setPlaced(false);
for(Node node : endpoints)node.setPlaced(false);
if(maxLevel < 0)
return new HashMap<Node, Coordinates>();
int j=0;
for(PlaceHolder placeHolder : levelToPlaceHolderMap.get(minLevel)){
Node node = levelMap.get(minLevel).get(j);
placeHolder.setNode(node);
node.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(node, node.getCoordinate());
node.setPlaced(true);
j++;
}
for(int level = minLevel+1;level <= maxLevel; level++){
List<PlaceHolder> upperLevelNodes = levelToPlaceHolderMap.get(level-1);
List<Node> nodes = levelMap.get(level);
int i=0;
for(PlaceHolder parentPH : upperLevelNodes){
List<Node> children = childrenMap.get(parentPH.getNode());
for(Node child : children){
PlaceHolder childPlaceHolder = levelToPlaceHolderMap.get(level).get(i);
childPlaceHolder.setOccupied(true);
childPlaceHolder.setNode(child);
child.setCoordinate(childPlaceHolder.getCoordinates());
coordForNodesMap.put(child, child.getCoordinate());
child.setPlaced(true);
i++;
}
}
for(Node node : nodes){
if(!node.isPlaced()){
PlaceHolder placeHolder = levelToPlaceHolderMap.get(level).get(i);
placeHolder.setOccupied(true);
placeHolder.setNode(node);
node.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(node, node.getCoordinate());
node.setPlaced(true);
i++;
}
}
}
int i=0;
for(PlaceHolder parentPH : levelToPlaceHolderMap.get(maxLevel)){
List<Node>children = childrenMap.get(parentPH.getNode());
for(Node child : children){
PlaceHolder placeHolder = endpointPlaceHolders.get(i);
placeHolder.setOccupied(true);
placeHolder.setNode(child);
child.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(child, child.getCoordinate());
child.setPlaced(true);
i++;
}
}
for(Node node : endpoints){
if(!node.isPlaced()){
PlaceHolder placeHolder = endpointPlaceHolders.get(i);
placeHolder.setOccupied(true);
placeHolder.setNode(node);
node.setCoordinate(placeHolder.getCoordinates());
coordForNodesMap.put(node, node.getCoordinate());
node.setPlaced(true);
i++;
}
}
return coordForNodesMap;
}
/*private void drawArrow(Graphics g1, int x1, int y1, int x2, int y2) {
Graphics2D g = (Graphics2D) g1.create();
System.out.println("Drawing arrow");
double dx = x2 - x1, dy = y2 - y1;
double angle = Math.atan2(dy, dx);
int len = (int) Math.sqrt(dx * dx + dy * dy);
AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
at.concatenate(AffineTransform.getRotateInstance(angle));
g.transform(at);
// Draw horizontal arrow starting in (0, 0)
QuadCurve2D.Double curve = new QuadCurve2D.Double(0,0,50+0.5*len,50,len,0);
g.draw(curve);
g.fillPolygon(new int[] { len, len - ARR_SIZE, len - ARR_SIZE, len }, new int[] { 0, -ARR_SIZE, ARR_SIZE, 0 }, 4);
}*/
public void setGraph(Graph newGraph){
this.graph = newGraph;
}
}

View File

@@ -0,0 +1,74 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class HostNode extends Node {
private static final long serialVersionUID = -8635044061126993668L;
private long pes;
private long mips;
private int ram;
private long storage;
private long bw;
public HostNode() {
}
public HostNode(String name, String type, long pes, long mips, int ram, long storage, long bw) {
super(name, type);
this.pes = pes;
this.mips = mips;
this.ram = ram;
this.storage = storage;
this.bw = bw;
}
public void setPes(long pes) {
this.pes = pes;
}
public long getPes() {
return pes;
}
public void setMips(long mips) {
this.mips = mips;
}
public long getMips() {
return mips;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getRam() {
return ram;
}
public void setStorage(long storage) {
this.storage = storage;
}
public long getStorage() {
return storage;
}
public void setBw(long bw) {
this.bw = bw;
}
public long getBw() {
return bw;
}
@Override
public String toString() {
return "Node [pes=" + pes + " mips=" + mips + " ram=" + ram + " storage=" + storage + " bw=" + bw + "]";
}
}

View File

@@ -0,0 +1,97 @@
package org.fog.gui.core;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* The model that represents an edge with two vertexes, for physical link and virtual edge.
*
*/
public class Link extends Edge implements Serializable {
private static final long serialVersionUID = -356975278987708987L;
private Node dest = null;
private double latency = 0.0;
private String name = "";
private long bandwidth = 0;
/**
* Constructor.
*
* @param node the node that belongs to the edge.
*/
public Link(Node to) {
super(to);
this.dest = to;
}
/** physical topology link */
public Link(Node to, double latency) {
super(to, latency);
this.dest = to;
this.latency = latency;
}
/** virtual virtual edge */
public Link(Node to, String name, long bw) {
super(to, name, bw);
this.dest = to;
this.name = name;
this.bandwidth = bw;
}
/** copy edge */
public Link(Node to, Map<String, Object> info){
super(to, info);
this.dest = to;
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
public Node getNode() {
return dest;
}
public long getBandwidth() {
return bandwidth;
}
public double getLatency() {
return latency;
}
public Map<String, Object> getInfo() {
Map<String, Object> info = new HashMap<String, Object>();
info.put("name", this.name);
info.put("bandwidth",this.bandwidth);
info.put("latency", this.latency);
return info;
}
public void setInfo(Map<String, Object> info){
if(info.get("name")!=null){
this.name = (String) info.get("name");
}
if(info.get("bandwidth")!=null){
this.bandwidth = (long) info.get("bandwidth");
}
if(info.get("latency")!=null){
this.latency = (double) info.get("latency");
}
}
@Override
public String toString() {
return "Edge [dest=" + dest + "]";
}
}

View File

@@ -0,0 +1,92 @@
package org.fog.gui.core;
import java.io.Serializable;
/**
* The model that represents node (host or vm) for the graph.
*
*/
public class Node implements Serializable {
private static final long serialVersionUID = 823544330517091616L;
private Coordinates coord;
private String name;
private String type;
private boolean isPlaced;
public Node() {
setPlaced(false);
}
public Node(String name, String type) {
this.name = name;
this.type = type;
setPlaced(false);
coord = new Coordinates();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setCoordinate(Coordinates coord) {
this.coord.setX(coord.getX());
this.coord.setY(coord.getY());
}
public Coordinates getCoordinate() {
return coord;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Node [name=" + name + " type=" + type + "]";
}
public boolean isPlaced() {
return isPlaced;
}
public void setPlaced(boolean isPlaced) {
this.isPlaced = isPlaced;
}
}

View File

@@ -0,0 +1,27 @@
package org.fog.gui.core;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
/** A cell renderer for the JComboBox when displaying a node object */
@SuppressWarnings("rawtypes")
public class NodeCellRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = 6021697923766790099L;
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Node node = (Node) value;
JLabel label = new JLabel();
if (node != null && node.getName() != null) {
label.setText(node.getName());
}
return label;
}
}

View File

@@ -0,0 +1,47 @@
package org.fog.gui.core;
public class PlaceHolder {
protected Coordinates coordinates;
protected boolean isOccupied;
protected Node node;
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
public boolean isOccupied() {
return isOccupied;
}
public void setOccupied(boolean isOccupied) {
this.isOccupied = isOccupied;
}
public PlaceHolder(Coordinates coordinates){
setCoordinates(coordinates);
setOccupied(false);
}
public PlaceHolder(){
setCoordinates(new Coordinates());
setOccupied(false);
}
public PlaceHolder(int x, int y){
setCoordinates(new Coordinates(x, y));
setOccupied(false);
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
}

View File

@@ -0,0 +1,82 @@
package org.fog.gui.core;
import java.io.Serializable;
import org.fog.utils.distribution.DeterministicDistribution;
import org.fog.utils.distribution.Distribution;
import org.fog.utils.distribution.NormalDistribution;
import org.fog.utils.distribution.UniformDistribution;
public class SensorGui extends Node implements Serializable{
private static final long serialVersionUID = 4087896123649020073L;
private String name;
private String sensorType;
private Distribution distribution;
public SensorGui(String name, String type, Distribution distribution){
super(name, "SENSOR");
setName(name);
setSensorType(type);
setDistribution(distribution);
}
public SensorGui(String name, String sensorType, String selectedItem, double normalMean_,
double normalStdDev_, double uniformLow_, double uniformUp_,
double deterministicVal_) {
super(name, "SENSOR");
setName(name);
setSensorType(sensorType);
if(normalMean_ != -1){
setDistribution(new NormalDistribution(normalMean_, normalStdDev_));
}else if(uniformLow_ != -1){
setDistribution(new UniformDistribution(uniformLow_, uniformUp_));
}else if(deterministicVal_ != -1){
setDistribution(new DeterministicDistribution(deterministicVal_));
}
}
public int getDistributionType(){
return distribution.getDistributionType();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Distribution getDistribution() {
return distribution;
}
public void setDistribution(Distribution distribution) {
this.distribution = distribution;
}
@Override
public String toString() {
if(distribution instanceof NormalDistribution)
return "Sensor [dist=1 mean=" + ((NormalDistribution)distribution).getMean() + " stdDev=" + ((NormalDistribution)distribution).getStdDev() + "]";
else if(distribution instanceof UniformDistribution)
return "Sensor [dist=2 min=" + ((UniformDistribution)distribution).getMin() + " max=" + ((UniformDistribution)distribution).getMax() + "]";
else if(distribution instanceof DeterministicDistribution)
return "Sensor [dist=3 value=" + ((DeterministicDistribution)distribution).getValue() + "]";
else
return "";
}
public String getSensorType() {
return sensorType;
}
public void setSensorType(String sensorType) {
this.sensorType = sensorType;
}
}

View File

@@ -0,0 +1,34 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class SensorModule extends Node {
private static final long serialVersionUID = 804858850147477656L;
String sensorType;
public SensorModule() {
}
public SensorModule(String sensorType) {
super(sensorType, "SENSOR_MODULE");
setSensorType(sensorType);
}
public String getSensorType() {
return sensorType;
}
public void setSensorType(String sensorType) {
this.sensorType = sensorType;
}
@Override
public String toString() {
return "Node []";
}
}

View File

@@ -0,0 +1,194 @@
package org.fog.gui.core;
import javax.swing.*;
import javax.swing.SpringLayout;
import java.awt.*;
/**
* A 1.4 file that provides utility methods for
* creating form- or grid-style layouts with SpringLayout.
* These utilities are used by several programs, such as
* SpringBox and SpringCompactGrid.
*/
public class SpringUtilities {
/**
* A debugging utility that prints to stdout the component's
* minimum, preferred, and maximum sizes.
*/
public static void printSizes(Component c) {
System.out.println("minimumSize = " + c.getMinimumSize());
System.out.println("preferredSize = " + c.getPreferredSize());
System.out.println("maximumSize = " + c.getMaximumSize());
}
/**
* Aligns the first <code>rows</code> * <code>cols</code>
* components of <code>parent</code> in
* a grid. Each component is as big as the maximum
* preferred width and height of the components.
* The parent is made just big enough to fit them all.
*
* @param rows number of rows
* @param cols number of columns
* @param initialX x location to start the grid at
* @param initialY y location to start the grid at
* @param xPad x padding between cells
* @param yPad y padding between cells
*/
public static void makeGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeGrid must use SpringLayout.");
return;
}
Spring xPadSpring = Spring.constant(xPad);
Spring yPadSpring = Spring.constant(yPad);
Spring initialXSpring = Spring.constant(initialX);
Spring initialYSpring = Spring.constant(initialY);
int max = rows * cols;
//Calculate Springs that are the max of the width/height so that all
//cells have the same size.
Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)).
getWidth();
Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)).
getHeight();
for (int i = 1; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth());
maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight());
}
//Apply the new width/height Spring. This forces all the
//components to have the same size.
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
cons.setWidth(maxWidthSpring);
cons.setHeight(maxHeightSpring);
}
//Then adjust the x/y constraints of all the cells so that they
//are aligned in a grid.
SpringLayout.Constraints lastCons = null;
SpringLayout.Constraints lastRowCons = null;
for (int i = 0; i < max; i++) {
SpringLayout.Constraints cons = layout.getConstraints(
parent.getComponent(i));
if (i % cols == 0) { //start of new row
lastRowCons = lastCons;
cons.setX(initialXSpring);
} else { //x position depends on previous component
cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST),
xPadSpring));
}
if (i / cols == 0) { //first row
cons.setY(initialYSpring);
} else { //y position depends on previous row
cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH),
yPadSpring));
}
lastCons = cons;
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH,
Spring.sum(
Spring.constant(yPad),
lastCons.getConstraint(SpringLayout.SOUTH)));
pCons.setConstraint(SpringLayout.EAST,
Spring.sum(
Spring.constant(xPad),
lastCons.getConstraint(SpringLayout.EAST)));
}
/* Used by makeCompactGrid. */
private static SpringLayout.Constraints getConstraintsForCell(
int row, int col,
Container parent,
int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}
/**
* Aligns the first <code>rows</code> * <code>cols</code>
* components of <code>parent</code> in
* a grid. Each component in a column is as wide as the maximum
* preferred width of the components in that column;
* height is similarly determined for each row.
* The parent is made just big enough to fit them all.
*
* @param rows number of rows
* @param cols number of columns
* @param initialX x location to start the grid at
* @param initialY y location to start the grid at
* @param xPad x padding between cells
* @param yPad y padding between cells
*/
public static void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
}

View File

@@ -0,0 +1,62 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class SwitchNode extends Node {
private static final long serialVersionUID = 804858850147477656L;
private long iops;
private int upports;
private int downports;
private long bw;
public SwitchNode() {
}
public SwitchNode(String name, String type, long iops, int upports, int downports, long bw) {
super(name, type);
this.iops = iops;
this.upports = upports;
this.downports = downports;
this.bw = bw;
}
public void setIops(long iops) {
this.iops = iops;
}
public long getIops() {
return iops;
}
public void setUpports(int upports) {
this.upports = upports;
}
public int getUpports() {
return upports;
}
public void setDownports(int downports) {
this.downports = downports;
}
public int getDownports() {
return downports;
}
public void setBw(long bw) {
this.bw = bw;
}
public long getBw() {
return bw;
}
@Override
public String toString() {
return "Node [iops=" + iops + " upports=" + upports + " downports=" + downports + " bw=" + bw + "]";
}
}

View File

@@ -0,0 +1,62 @@
package org.fog.gui.core;
/**
* The model that represents virtual machine node for the graph.
*
*/
public class VmNode extends Node {
private static final long serialVersionUID = 804858850147477656L;
private long size;
private int pes;
private long mips;
private int ram;
public VmNode() {
}
public VmNode(String name, String type, long size, int pes, long mips, int ram) {
super(name, type);
this.size = size;
this.pes = pes;
this.mips = mips;
this.ram = ram;
}
public void setSize(int size) {
this.size = size;
}
public long getSize() {
return size;
}
public void setPes(int pes) {
this.pes = pes;
}
public int getPes() {
return pes;
}
public void setMips(long mips) {
this.mips = mips;
}
public long getMips() {
return mips;
}
public void setRam(int ram) {
this.ram = ram;
}
public int getRam() {
return ram;
}
@Override
public String toString() {
return "Node [size=" + size + " pes=" + pes + " mips=" + mips + " ram=" + ram + "]";
}
}

View File

@@ -0,0 +1,59 @@
package org.fog.gui.dialog;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
@SuppressWarnings("serial")
class About extends JDialog {
public About() {
initUI();
}
public final void initUI() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(0, 10)));
ImageIcon icon = new ImageIcon("src/logo.png");
JLabel label = new JLabel(icon);
label.setAlignmentX(0.5f);
add(label);
add(Box.createRigidArea(new Dimension(0, 10)));
JLabel name = new JLabel("CloudSim SDN, 1.00");
name.setFont(new Font("Serif", Font.BOLD, 15));
name.setAlignmentX(0.5f);
add(name);
add(Box.createRigidArea(new Dimension(0, 50)));
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
close.setAlignmentX(0.5f);
add(close);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle("About CloudSim");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(350, 300);
}
}

View File

@@ -0,0 +1,136 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.ActuatorGui;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddActuator extends JDialog {
private static final long serialVersionUID = -511667786177319577L;
private final Graph graph;
private JTextField actuatorName;
private JTextField actuatorType;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddActuator(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Actuator");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (actuatorName.getText() == null || actuatorName.getText().length() < 1) {
prompt("Please type Actuator name", "Error");
} else {
if(!catchedError){
ActuatorGui actuator = new ActuatorGui(actuatorName.getText(),
actuatorType.getText().toString());
graph.addNode(actuator);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
actuatorName = new JTextField();
lName.setLabelFor(actuatorName);
springPanel.add(actuatorName);
JLabel lType = new JLabel("Actuator Type : ");
springPanel.add(lType);
actuatorType = new JTextField();
lName.setLabelFor(actuatorType);
springPanel.add(actuatorType);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
2, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddActuator.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.ActuatorModule;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddActuatorModule extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField actuatorType;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddActuatorModule(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Sensor Module");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (actuatorType.getText() == null || actuatorType.getText().length() < 1) {
prompt("Please enter Actuator Type", "Error");
} else {
try {
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new ActuatorModule(actuatorType.getText().toString());
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Sensor Type: ");
springPanel.add(lName);
actuatorType = new JTextField();
lName.setLabelFor(actuatorType);
springPanel.add(actuatorType);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
1, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddActuatorModule.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,244 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
import org.fog.gui.core.SpringUtilities;
/** A dialog to add a new edge */
public class AddAppEdge extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tupleType;
private JTextField tupleCpuLen;
private JTextField tupleNwLen;
public AddAppEdge(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Application edge");
setModal(true);
setPreferredSize(new Dimension(400, 250));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel2 = new JPanel();
textAreaPanel2.setLayout(new BoxLayout(textAreaPanel2, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
for (Node node : allNodes) {
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
inputPanel.add(new Label("--->"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
JPanel springPanel = new JPanel(new SpringLayout());
//springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel tupleTypeLabel = new JLabel("Tuple Type : ");
springPanel.add(tupleTypeLabel);
tupleType = new JTextField();
tupleTypeLabel.setLabelFor(tupleType);
springPanel.add(tupleType);
JLabel tupleCpuLenLabel = new JLabel("Tuple CPU Len : ");
springPanel.add(tupleCpuLenLabel);
tupleCpuLen = new JTextField();
tupleCpuLenLabel.setLabelFor(tupleCpuLen);
springPanel.add(tupleCpuLen);
JLabel tupleNwLenLabel = new JLabel("Tuple NW Len : ");
springPanel.add(tupleNwLenLabel);
tupleNwLen = new JTextField();
tupleNwLenLabel.setLabelFor(tupleNwLen);
springPanel.add(tupleNwLen);
SpringUtilities.makeCompactGrid(springPanel,
3, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
inputPanelWrapper.add(springPanel);
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = "default";
long bandwidth = 0;
boolean catchedError = false;
if (tupleType.getText() == null || tupleType.getText().isEmpty()) {
catchedError = true;
prompt("Please enter Tuple Type", "Error");
} else if (tupleCpuLen.getText() == null || tupleCpuLen.getText().isEmpty()) {
catchedError = true;
prompt("Please enter Tuple CPU Length", "Error");
} else if (tupleNwLen.getText() == null || tupleNwLen.getText().isEmpty()) {
catchedError = true;
prompt("Please enter Tuple NW Length", "Error");
}
else {
name = ((Node)sourceNode.getSelectedItem()).getName()+"-"+((Node)sourceNode.getSelectedItem()).getName();
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Edge edge = new Edge(target, name, bandwidth);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddAppEdge.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.AppModule;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddApplicationModule extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField tfName;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddApplicationModule(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Application Module");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else {
try {
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new AppModule(tfName.getText().toString());
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
tfName = new JTextField();
lName.setLabelFor(tfName);
springPanel.add(tfName);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
1, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddApplicationModule.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,201 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.FogDeviceGui;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddFogDevice extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JLabel deviceNameLabel;
private JLabel upBwLabel;
private JLabel downBwLabel;
private JLabel mipsLabel;
private JLabel ramLabel;
private JLabel levelLabel;
private JLabel rateLabel;
private JTextField deviceName;
private JTextField upBw;
private JTextField downBw;
private JTextField mips;
private JTextField ram;
private JTextField level;
private JTextField rate;
public AddFogDevice(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Fog Device");
setModal(true);
setPreferredSize(new Dimension(350, 380));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (deviceName.getText() == null || deviceName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else if (upBw.getText() == null || upBw.getText().length() < 1) {
prompt("Please enter uplink BW", "Error");
} else if (downBw.getText() == null || downBw.getText().length() < 1) {
prompt("Please enter downlink BW", "Error");
} else if (mips.getText() == null || mips.getText().length() < 1) {
prompt("Please enter MIPS", "Error");
} else if (ram.getText() == null || ram.getText().length() < 1) {
prompt("Please enter RAM", "Error");
} else if (level.getText() == null || level.getText().length() < 1) {
prompt("Please enter Level", "Error");
} else if (rate.getText() == null || rate.getText().length() < 1) {
prompt("Please enter Rate", "Error");
}
long upBw_=-1, downBw_=-1, mips_=-1; int ram_=-1, level_=-1;double rate_ = -1;
try {
upBw_ = Long.parseLong(upBw.getText());
downBw_ = Long.parseLong(downBw.getText());
mips_ = Long.parseLong(mips.getText());
ram_ = Integer.parseInt(ram.getText());
level_ = Integer.parseInt(level.getText());
rate_ = Double.parseDouble(rate.getText());
catchedError = false;
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
FogDeviceGui fogDevice = new FogDeviceGui(deviceName.getText().toString(), mips_, ram_, upBw_, downBw_, level_, rate_);
graph.addNode(fogDevice);
setVisible(false);
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
//springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
deviceNameLabel = new JLabel("Name: ");
springPanel.add(deviceNameLabel);
deviceName = new JTextField();
deviceNameLabel.setLabelFor(deviceName);
springPanel.add(deviceName);
levelLabel = new JLabel("Level: ");
springPanel.add(levelLabel);
level = new JTextField();
levelLabel.setLabelFor(level);
springPanel.add(level);
upBwLabel = new JLabel("Uplink Bw: ");
springPanel.add(upBwLabel);
upBw = new JTextField();
upBwLabel.setLabelFor(upBw);
springPanel.add(upBw);
downBwLabel = new JLabel("Downlink Bw: ");
springPanel.add(downBwLabel);
downBw = new JTextField();
downBwLabel.setLabelFor(downBw);
springPanel.add(downBw);
/** switch and host */
mipsLabel = new JLabel("Mips: ");
springPanel.add(mipsLabel);
mips = new JTextField();
mipsLabel.setLabelFor(mips);
springPanel.add(mips);
ramLabel = new JLabel("Ram: ");
springPanel.add(ramLabel);
ram = new JTextField();
ramLabel.setLabelFor(ram);
springPanel.add(ram);
rateLabel = new JLabel("Rate/MIPS: ");
springPanel.add(rateLabel);
rate = new JTextField();
rateLabel.setLabelFor(rate);
springPanel.add(rate);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
7, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
//updatePanel("core");
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddFogDevice.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,222 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Link;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
/** A dialog to add a new edge */
public class AddLink extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tfLatency;
public AddLink(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Link");
setModal(true);
setPreferredSize(new Dimension(400, 200));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
if(!(selectedNode.getType().equals("SENSOR")||selectedNode.getType().equals("ACTUATOR")) || edgesForSelectedNode.size()==0){
for (Node node : allNodes) {
if((selectedNode.getType().equals("SENSOR")||selectedNode.getType().equals("ACTUATOR")) && !node.getType().equals("FOG_DEVICE"))
continue;
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
inputPanel.add(new Label("---->"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
textAreaPanel.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel.add(new JLabel("Latency: "));
tfLatency = new JTextField();
tfLatency.setMaximumSize(tfLatency.getPreferredSize());
tfLatency.setMinimumSize(new Dimension(150, tfLatency.getPreferredSize().height));
tfLatency.setPreferredSize(new Dimension(150, tfLatency.getPreferredSize().height));
textAreaPanel.add(tfLatency);
textAreaPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel);
inputPanelWrapper.add(Box.createVerticalGlue());
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double latency = 0;
boolean catchedError = false;
if (tfLatency.getText() == null || tfLatency.getText().isEmpty()) {
catchedError = true;
prompt("Please type latency", "Error");
}else {
try {
latency = Double.valueOf(tfLatency.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Latency should be double type", "Error");
}
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Link edge = new Link(target, latency);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddLink.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,217 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
/** A dialog to add a new edge */
public class AddPhysicalEdge extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tfLatency;
public AddPhysicalEdge(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Physical Topology edge");
setModal(true);
setPreferredSize(new Dimension(400, 200));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
for (Node node : allNodes) {
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
inputPanel.add(new Label(" <20><>"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
textAreaPanel.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel.add(new JLabel("Latency: "));
tfLatency = new JTextField();
tfLatency.setMaximumSize(tfLatency.getPreferredSize());
tfLatency.setMinimumSize(new Dimension(150, tfLatency.getPreferredSize().height));
tfLatency.setPreferredSize(new Dimension(150, tfLatency.getPreferredSize().height));
textAreaPanel.add(tfLatency);
textAreaPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel);
inputPanelWrapper.add(Box.createVerticalGlue());
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double latency = 0;
boolean catchedError = false;
if (tfLatency.getText() == null || tfLatency.getText().isEmpty()) {
catchedError = true;
prompt("Please type latency", "Error");
}else {
try {
latency = Double.valueOf(tfLatency.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Latency should be double type", "Error");
}
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Edge edge = new Edge(target, latency);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddPhysicalEdge.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,290 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SpringUtilities;
import org.fog.gui.core.SwitchNode;
import org.fog.gui.core.HostNode;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AddPhysicalNode extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JLabel lName;
private JLabel lType;
private JLabel lBw;
private JLabel lop1;
private JLabel lop2;
private JLabel lop3;
private JLabel lop4;
private JTextField tfName;
private JComboBox cType;
private JTextField tfBw;
private JTextField top1;
private JTextField top2;
private JTextField top3;
private JTextField top4;
public AddPhysicalNode(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Physical Node");
setModal(true);
setPreferredSize(new Dimension(350, 380));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else if (tfBw.getText() == null || tfBw.getText().length() < 1) {
prompt("Please type VM Bw", "Error");
} else if(cType.getSelectedIndex() < 0) {
prompt("Please type VM Type", "Error");
}else{
String type = (String)cType.getSelectedItem();
if("host"==getType(type)){
if (top1.getText() == null || top1.getText().length() < 1) {
prompt("Please type pes", "Error");
} else if (top2.getText() == null || top2.getText().length() < 1) {
prompt("Please type VM mips", "Error");
} else if (top3.getText() == null || top3.getText().length() < 1) {
prompt("Please type VM RAM", "Error");
} else if (top4.getText() == null || top4.getText().length() < 1) {
prompt("Please type VM Storage", "Error");
} else {
long t1 = 0;
long t2 = 0;
int t3 = 0;
long t4 = 0;
long t5 = 0;
try {
t1 = Long.parseLong(top1.getText());
t2 = Long.parseLong(top2.getText());
t3 = Integer.parseInt(top3.getText());
t4 = Long.parseLong(top4.getText());
t5 = Long.parseLong(tfBw.getText());
catchedError = false;
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new HostNode(tfName.getText().toString(), type, t1, t2, t3, t4, t5);
graph.addNode(node);
setVisible(false);
}
}
}else if("switch"==getType(type)){
if (top1.getText() == null || top1.getText().length() < 1) {
prompt("Please type Iops", "Error");
} else if (top2.getText() == null || top2.getText().length() < 1) {
prompt("Please type upports", "Error");
} else if (top3.getText() == null || top3.getText().length() < 1) {
prompt("Please type VM downports", "Error");
} else {
long t1 = 0;
int t2 = 0;
int t3 = 0;
long t4 = 0;
try {
t1 = Long.parseLong(top1.getText());
t2 = Integer.parseInt(top2.getText());
t3 = Integer.parseInt(top3.getText());
t4 = Long.parseLong(tfBw.getText());
catchedError = false;
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new SwitchNode(tfName.getText().toString(), type, t1, t2, t3, t4);
graph.addNode(node);
setVisible(false);
}
}
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private void updatePanel(String type){
switch(type){
case "core":
case "edge":
lop1.setText("Iops: ");
lop2.setText("Upports: ");
lop3.setText("Downports: ");
lop4.setVisible(false);
top1.setText("");
top2.setText("");
top3.setText("");
top4.setVisible(false);
break;
case "host":
lop1.setText("Pes: ");
lop2.setText("Mips: ");
lop3.setText("Ram: ");
lop4.setVisible(true);
lop4.setText("Storage: ");
top1.setText("");
top2.setText("");
top3.setText("");
top4.setVisible(true);
top4.setText("");
break;
}
}
private String getType(String type){
if("core"==type || "edge"==type){
return "switch";
} else if("host"==type){
return "host";
}
return "";
}
private JPanel createInputPanelArea() {
String[] vmType = {"core","edge","host"};
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
lName = new JLabel("Name: ");
springPanel.add(lName);
tfName = new JTextField();
lName.setLabelFor(tfName);
springPanel.add(tfName);
lType = new JLabel("Type: "); //, JLabel.TRAILING);
springPanel.add(lType);
cType = new JComboBox(vmType);
lType.setLabelFor(cType);
cType.setSelectedIndex(0);
cType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
JComboBox ctype = (JComboBox)e.getSource();
String item = (String)ctype.getSelectedItem();
updatePanel(item);
}
});
springPanel.add(cType);
lBw = new JLabel("Bw: ");
springPanel.add(lBw);
tfBw = new JTextField();
lBw.setLabelFor(tfBw);
springPanel.add(tfBw);
/** switch and host */
lop1 = new JLabel("Pes: ");
springPanel.add(lop1);
top1 = new JTextField();
lop1.setLabelFor(top1);
springPanel.add(top1);
lop2 = new JLabel("Mips: ");
springPanel.add(lop2);
top2 = new JTextField();
lop2.setLabelFor(top2);
springPanel.add(top2);
lop3 = new JLabel("Ram: ");
springPanel.add(lop3);
top3 = new JTextField();
lop3.setLabelFor(top3);
springPanel.add(top3);
lop4 = new JLabel("Storage: ");
springPanel.add(lop4);
top4 = new JTextField();
lop4.setLabelFor(top4);
springPanel.add(top4);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
7, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
updatePanel("core");
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddPhysicalNode.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,270 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.entities.Sensor;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SensorGui;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AddSensor extends JDialog {
private static final long serialVersionUID = -511667786177319577L;
private final Graph graph;
private JTextField sensorName;
private JTextField sensorType;
private JComboBox distribution;
private JTextField uniformLowerBound;
private JTextField uniformUpperBound;
private JTextField deterministicValue;
private JTextField normalMean;
private JTextField normalStdDev;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddSensor(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Sensor");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (sensorName.getText() == null || sensorName.getText().length() < 1) {
prompt("Please type Sensor name", "Error");
} else if (sensorType.getText() == null || sensorType.getText().length() < 1) {
prompt("Please type Sensor Type", "Error");
} else if (distribution.getSelectedIndex() < 0) {
prompt("Please select Emission time distribution", "Error");
} else {
double normalMean_ = -1;
double normalStdDev_ = -1;
double uniformLow_ = -1;
double uniformUp_ = -1;
double deterministicVal_ = -1;
String _sensorType = sensorType.getText();
String dist = (String)distribution.getSelectedItem();
if(dist.equals("Normal")){
try {
normalMean_ = Double.parseDouble(normalMean.getText());
normalStdDev_ = Double.parseDouble(normalStdDev.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
SensorGui sensor = new SensorGui(sensorName.getText().toString(), _sensorType, (String)distribution.getSelectedItem(),
normalMean_, normalStdDev_, uniformLow_, uniformUp_, deterministicVal_);
graph.addNode(sensor);
setVisible(false);
}
} else if(dist.equals("Uniform")){
try {
uniformLow_ = Double.parseDouble(uniformLowerBound.getText());
uniformUp_ = Double.parseDouble(uniformUpperBound.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
SensorGui sensor = new SensorGui(sensorName.getText().toString(), _sensorType, (String)distribution.getSelectedItem(),
normalMean_, normalStdDev_, uniformLow_, uniformUp_, deterministicVal_);
graph.addNode(sensor);
setVisible(false);
}
} else if(dist.equals("Deterministic")){
try {
deterministicVal_ = Double.parseDouble(deterministicValue.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
SensorGui sensor = new SensorGui(sensorName.getText().toString(), _sensorType, (String)distribution.getSelectedItem(),
normalMean_, normalStdDev_, uniformLow_, uniformUp_, deterministicVal_);
graph.addNode(sensor);
setVisible(false);
}
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
String[] distributionType = {"Normal", "Uniform", "Deterministic"};
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
sensorName = new JTextField();
lName.setLabelFor(sensorName);
springPanel.add(sensorName);
JLabel lType = new JLabel("Type: ");
springPanel.add(lType);
sensorType = new JTextField();
lType.setLabelFor(sensorType);
springPanel.add(sensorType);
JLabel distLabel = new JLabel("Distribution Type: ", JLabel.TRAILING);
springPanel.add(distLabel);
distribution = new JComboBox(distributionType);
distLabel.setLabelFor(distribution);
distribution.setSelectedIndex(-1);
distribution.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
JComboBox ctype = (JComboBox)e.getSource();
String item = (String)ctype.getSelectedItem();
updatePanel(item);
}
});
springPanel.add(distribution);
JLabel normalMeanLabel = new JLabel("Mean: ");
springPanel.add(normalMeanLabel);
normalMean = new JTextField();
normalMeanLabel.setLabelFor(normalMean);
springPanel.add(normalMean);
JLabel normalStdDevLabel = new JLabel("StdDev: ");
springPanel.add(normalStdDevLabel);
normalStdDev = new JTextField();
normalStdDevLabel.setLabelFor(normalStdDev);
springPanel.add(normalStdDev);
JLabel uniformLowLabel = new JLabel("Min: ");
springPanel.add(uniformLowLabel);
uniformLowerBound = new JTextField();
uniformLowLabel.setLabelFor(uniformLowerBound);
springPanel.add(uniformLowerBound);
JLabel uniformUpLabel = new JLabel("Max: ");
springPanel.add(uniformUpLabel);
uniformUpperBound = new JTextField();
uniformUpLabel.setLabelFor(uniformUpperBound);
springPanel.add(uniformUpperBound);
JLabel deterministicValueLabel = new JLabel("Value: ");
springPanel.add(deterministicValueLabel);
deterministicValue = new JTextField();
uniformLowLabel.setLabelFor(deterministicValue);
springPanel.add(deterministicValue);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
8, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
protected void updatePanel(String item) {
switch(item){
case "Normal":
normalMean.setVisible(true);
normalStdDev.setVisible(true);
uniformLowerBound.setVisible(false);
uniformUpperBound.setVisible(false);
deterministicValue.setVisible(false);
break;
case "Uniform":
normalMean.setVisible(false);
normalStdDev.setVisible(false);
uniformLowerBound.setVisible(true);
uniformUpperBound.setVisible(true);
deterministicValue.setVisible(false);
break;
case "Deterministic":
normalMean.setVisible(false);
normalStdDev.setVisible(false);
uniformLowerBound.setVisible(false);
uniformUpperBound.setVisible(false);
deterministicValue.setVisible(true);
break;
default:
break;
}
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddSensor.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,134 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.SensorModule;
import org.fog.gui.core.SpringUtilities;
@SuppressWarnings({ "rawtypes" })
public class AddSensorModule extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField sensorType;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddSensorModule(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Sensor Module");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (sensorType.getText() == null || sensorType.getText().length() < 1) {
prompt("Please entyer Sensor Type", "Error");
} else {
try {
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new SensorModule(sensorType.getText().toString());
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Sensor Type: ");
springPanel.add(lName);
sensorType = new JTextField();
lName.setLabelFor(sensorType);
springPanel.add(sensorType);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
1, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddSensorModule.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,241 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.fog.gui.core.Edge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.Node;
import org.fog.gui.core.NodeCellRenderer;
/** A dialog to add a new edge */
public class AddVirtualEdge extends JDialog {
private static final long serialVersionUID = 4794808969864918000L;
private final Graph graph;
private JComboBox sourceNode;
private JComboBox targetNode;
private JTextField tfName;
private JTextField tfBandwidth;
public AddVirtualEdge(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanel(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Virtual Topology edge");
setModal(true);
setPreferredSize(new Dimension(400, 250));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
@SuppressWarnings("unchecked")
private JPanel createInputPanel() {
Component rigid = Box.createRigidArea(new Dimension(10, 0));
JPanel inputPanelWrapper = new JPanel();
inputPanelWrapper.setLayout(new BoxLayout(inputPanelWrapper, BoxLayout.PAGE_AXIS));
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BoxLayout(textAreaPanel, BoxLayout.LINE_AXIS));
JPanel textAreaPanel2 = new JPanel();
textAreaPanel2.setLayout(new BoxLayout(textAreaPanel2, BoxLayout.LINE_AXIS));
ComboBoxModel sourceNodeModel = new DefaultComboBoxModel(graph.getAdjacencyList().keySet().toArray());
sourceNodeModel.setSelectedItem(null);
sourceNode = new JComboBox(sourceNodeModel);
targetNode = new JComboBox();
sourceNode.setMaximumSize(sourceNode.getPreferredSize());
sourceNode.setMinimumSize(new Dimension(150, sourceNode.getPreferredSize().height));
sourceNode.setPreferredSize(new Dimension(150, sourceNode.getPreferredSize().height));
targetNode.setMaximumSize(targetNode.getPreferredSize());
targetNode.setMinimumSize(new Dimension(150, targetNode.getPreferredSize().height));
targetNode.setPreferredSize(new Dimension(150, targetNode.getPreferredSize().height));
NodeCellRenderer renderer = new NodeCellRenderer();
sourceNode.setRenderer(renderer);
targetNode.setRenderer(renderer);
sourceNode.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// only display nodes which do not have already an edge
targetNode.removeAllItems();
Node selectedNode = (Node) sourceNode.getSelectedItem();
if (selectedNode != null) {
List<Node> nodesToDisplay = new ArrayList<Node>();
Set<Node> allNodes = graph.getAdjacencyList().keySet();
// get edged for selected node and throw out all target nodes where already an edge exists
List<Edge> edgesForSelectedNode = graph.getAdjacencyList().get(selectedNode);
Set<Node> nodesInEdges = new HashSet<Node>();
for (Edge edge : edgesForSelectedNode) {
nodesInEdges.add(edge.getNode());
}
for (Node node : allNodes) {
if (!node.equals(selectedNode) && !nodesInEdges.contains(node)) {
nodesToDisplay.add(node);
}
}
ComboBoxModel targetNodeModel = new DefaultComboBoxModel(nodesToDisplay.toArray());
targetNode.setModel(targetNodeModel);
}
}
});
inputPanel.add(sourceNode);
// inputPanel.add(Box.createRigidArea(new Dimension(10, 0)));
inputPanel.add(new Label(" <20><>"));
inputPanel.add(targetNode);
inputPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(inputPanel);
textAreaPanel.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel.add(new JLabel("Edge Name: "));
tfName = new JTextField();
tfName.setMaximumSize(tfName.getPreferredSize());
tfName.setMinimumSize(new Dimension(180, tfName.getPreferredSize().height));
tfName.setPreferredSize(new Dimension(180, tfName.getPreferredSize().height));
textAreaPanel.add(tfName);
textAreaPanel.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel);
inputPanelWrapper.add(Box.createVerticalGlue());
textAreaPanel2.add(Box.createRigidArea(new Dimension(10, 0)));
textAreaPanel2.add(new JLabel("Bandwidth: "));
tfBandwidth = new JTextField();
tfBandwidth.setMaximumSize(tfBandwidth.getPreferredSize());
tfBandwidth.setMinimumSize(new Dimension(180, tfBandwidth.getPreferredSize().height));
tfBandwidth.setPreferredSize(new Dimension(180, tfBandwidth.getPreferredSize().height));
textAreaPanel2.add(tfBandwidth);
textAreaPanel2.add(Box.createHorizontalGlue());
inputPanelWrapper.add(textAreaPanel2);
inputPanelWrapper.add(Box.createVerticalGlue());
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return inputPanelWrapper;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = "default";
long bandwidth = 0;
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().isEmpty()) {
catchedError = true;
prompt("Please type Edge Name", "Error");
}else {
name = (String)tfName.getText();
}
if (tfBandwidth.getText() == null || tfBandwidth.getText().isEmpty()) {
catchedError = true;
prompt("Please type Bandwidth", "Error");
}else {
try {
bandwidth = Long.valueOf(tfBandwidth.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Bandwidth should be long type", "Error");
}
}
if (!catchedError) {
if (sourceNode.getSelectedItem() == null || targetNode.getSelectedItem() == null) {
prompt("Please select node", "Error");
} else {
Node source = (Node) sourceNode.getSelectedItem();
Node target = (Node) targetNode.getSelectedItem();
Edge edge = new Edge(target, name, bandwidth);
graph.addEdge(source, edge);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return buttonPanel;
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddVirtualEdge.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,198 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import org.fog.gui.core.Graph;
import org.fog.gui.core.SpringUtilities;
import org.fog.gui.core.VmNode;
import org.fog.gui.core.Node;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AddVirtualNode extends JDialog {
private static final long serialVersionUID = -5116677861770319577L;
private final Graph graph;
private JTextField tfName;
private JComboBox cType;
private JTextField tfSize;
private JTextField tfPes;
private JTextField tfMips;
private JTextField tfRam;
/**
* Constructor.
*
* @param frame the parent frame
*/
public AddVirtualNode(final Graph graph, final JFrame frame) {
this.graph = graph;
setLayout(new BorderLayout());
add(createInputPanelArea(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.PAGE_END);
// show dialog
setTitle("Add Virtual Node");
setModal(true);
setPreferredSize(new Dimension(350, 400));
setResizable(false);
pack();
setLocationRelativeTo(frame);
setVisible(true);
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
JButton okBtn = new JButton("Ok");
JButton cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean catchedError = false;
if (tfName.getText() == null || tfName.getText().length() < 1) {
prompt("Please type VM name", "Error");
} else if (cType.getSelectedIndex() < 0) {
prompt("Please select VM type", "Error");
} else if (tfSize.getText() == null || tfSize.getText().length() < 1) {
prompt("Please type VM size", "Error");
} else if (tfPes.getText() == null || tfPes.getText().length() < 1) {
prompt("Please type pes", "Error");
} else if (tfMips.getText() == null || tfMips.getText().length() < 1) {
prompt("Please type VM mips", "Error");
} else if (tfRam.getText() == null || tfRam.getText().length() < 1) {
prompt("Please type VM RAM", "Error");
} else {
long t1 = 0;
int t2 = 0;
long t3 = 0;
int t4 = 0;
try {
t1 = Long.parseLong(tfSize.getText());
t2 = Integer.parseInt(tfPes.getText());
t3 = Long.parseLong(tfMips.getText());
t4 = Integer.parseInt(tfRam.getText());
} catch (NumberFormatException e1) {
catchedError = true;
prompt("Input should be numerical character", "Error");
}
if(!catchedError){
Node node = new VmNode(tfName.getText().toString(), (String)cType.getSelectedItem(),
t1, t2, t3, t4);
graph.addNode(node);
setVisible(false);
}
}
}
});
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(okBtn);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancelBtn);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
return buttonPanel;
}
private JPanel createInputPanelArea() {
String[] vmType = {"vm"};
//Create and populate the panel.
JPanel springPanel = new JPanel(new SpringLayout());
springPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
JLabel lName = new JLabel("Name: ");
springPanel.add(lName);
tfName = new JTextField();
lName.setLabelFor(tfName);
springPanel.add(tfName);
JLabel lType = new JLabel("Type: ", JLabel.TRAILING);
springPanel.add(lType);
cType = new JComboBox(vmType);
lType.setLabelFor(cType);
cType.setSelectedIndex(-1);
cType.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
}
});
springPanel.add(cType);
JLabel lSize = new JLabel("Size: ");
springPanel.add(lSize);
tfSize = new JTextField();
lSize.setLabelFor(tfSize);
springPanel.add(tfSize);
JLabel lPes = new JLabel("Pes: ");
springPanel.add(lPes);
tfPes = new JTextField();
lPes.setLabelFor(tfPes);
springPanel.add(tfPes);
JLabel lMips = new JLabel("Mips: ");
springPanel.add(lMips);
tfMips = new JTextField();
lMips.setLabelFor(tfMips);
springPanel.add(tfMips);
JLabel lRam = new JLabel("Ram: ");
springPanel.add(lRam);
tfRam = new JTextField();
lRam.setLabelFor(tfRam);
springPanel.add(tfRam);
//Lay out the panel.
SpringUtilities.makeCompactGrid(springPanel,
6, 2, //rows, columns
6, 6, //initX, initY
6, 6); //xPad, yPad
return springPanel;
}
public static void setUIFont (javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void prompt(String msg, String type){
JOptionPane.showMessageDialog(AddVirtualNode.this, msg, type, JOptionPane.ERROR_MESSAGE);
}
}

View File

@@ -0,0 +1,174 @@
package org.fog.gui.dialog;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import org.cloudbus.cloudsim.sdn.graph.example.GraphicSDNExample;
public class SDNRun extends JDialog {
private static final long serialVersionUID = -8313194085507492462L;
private String physicalTopologyFile = ""; //physical
private String deploymentFile = ""; //virtual
private String workloads_background = ""; //workload
private String workloads = ""; //workload
private JPanel panel;
private JScrollPane pane;
private JTextArea outputArea;
private JLabel imageLabel;
private JLabel msgLabel;
private JComponent space;
private int counter = 0;
private Timer timer;
private GraphicSDNExample sdn;
public SDNRun(final String phy, final String vir, final String wlbk, final String wl, final JFrame frame){
physicalTopologyFile = phy;
deploymentFile = vir;
workloads_background = wlbk;
workloads = wl;
setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
initUI();
run();
add(panel, BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE );
setTitle("Run Simulation");
setModal(true);
setPreferredSize(new Dimension(900, 600));
setResizable(false);
pack();
setLocationRelativeTo(frame); // must be called between pack and setVisible to work properly
setVisible(true);
}
private void initUI(){
ImageIcon ii = new ImageIcon(this.getClass().getResource("/src/1.gif"));
imageLabel = new JLabel(ii);
imageLabel.setAlignmentX(CENTER_ALIGNMENT);
msgLabel = new JLabel("Simulation is executing");
msgLabel.setAlignmentX(CENTER_ALIGNMENT);
space = (JComponent)Box.createRigidArea(new Dimension(0, 200));
panel.add(space);
panel.add(msgLabel);
panel.add(imageLabel);
pane = new JScrollPane();
outputArea = new JTextArea();
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
outputArea.setEditable(false);
//outputArea.setText("wo ai bei jin tian an men");
//readFile(physicalTopologyFile, outputArea);
pane.getViewport().add(outputArea);
panel.add(pane);
pane.setVisible(false);
}
private void run(){
sdn = new GraphicSDNExample(physicalTopologyFile, deploymentFile, workloads_background, workloads, outputArea);
SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {
protected Boolean doInBackground() throws Exception {
boolean success = false;
success = sdn.simulate();
if(success){
sdn.output();
append("<<<<<<<<<< Simulation completed >>>>>>>>>");
}else{
append("<<<<<<<<<< Running Error >>>>>>>>>>");
}
return success;
}
protected void done() {
boolean status;
try {
status = get();
panel.remove(space);
panel.remove(imageLabel);
panel.remove(msgLabel);
pane.setVisible(true);
panel.revalidate();
panel.repaint();
} catch (InterruptedException e) {
} catch (ExecutionException e) {
}
}
};
worker.execute();
}
private void append(String content){
outputArea.append(content+"\n");
}
/** below only used for testing reading file to textarea */
private void startTest(){
ActionListener updateProBar = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if(counter>=100){
timer.stop();
panel.remove(space);
panel.remove(imageLabel);
panel.remove(msgLabel);
pane.setVisible(true);
panel.revalidate();
panel.repaint();
}else{
counter +=2;
}
}
};
timer = new Timer(50, updateProBar);
timer.start();
}
private void readFile(String path, JTextArea area) {
try{
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
area.read( br, null );
br.close();
area.requestFocus();
}catch(Exception e2) {
System.out.println(e2);
}
}
}

View File

@@ -0,0 +1,585 @@
package org.fog.gui.example;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.fog.gui.core.Bridge;
import org.fog.gui.core.Graph;
import org.fog.gui.core.GraphView;
import org.fog.gui.dialog.AddActuator;
import org.fog.gui.dialog.AddFogDevice;
import org.fog.gui.dialog.AddLink;
import org.fog.gui.dialog.AddPhysicalEdge;
import org.fog.gui.dialog.AddPhysicalNode;
import org.fog.gui.dialog.AddSensor;
import org.fog.gui.dialog.SDNRun;
public class FogGui extends JFrame {
private static final long serialVersionUID = -2238414769964738933L;
private JPanel contentPane;
/** Import file names */
private String physicalTopologyFile = ""; //physical
private String deploymentFile = ""; //virtual
private String workloads_background = ""; //workload
private String workloads = ""; //workload
private JPanel panel;
private JPanel graph;
private Graph physicalGraph;
//private Graph virtualGraph;
private GraphView physicalCanvas;
//private GraphView virtualCanvas;
private JButton btnRun;
private String mode; //'m':manual; 'i':import
public FogGui() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1280, 800));
setLocationRelativeTo(null);
//setResizable(false);
setTitle("Fog Topology Creator");
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
initUI();
initGraph();
pack();
setVisible(true);
}
public final void initUI() {
setUIFont (new javax.swing.plaf.FontUIResource("Serif",Font.BOLD,18));
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
graph = new JPanel(new java.awt.GridLayout(1, 2));
initBar();
doPosition();
}
/** position window */
private void doPosition() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
int x = (width / 2 - 1280 / 2);
int y = (height / 2 - 800 / 2);
// One could use the dimension of the frame. But when doing so, one have to call this method !BETWEEN! pack and
// setVisible. Otherwise the calculation will go wrong.
this.setLocation(x, y);
}
/** Initialize project menu and tool bar */
private final void initBar() {
//---------- Start ActionListener ----------
ActionListener readPhyTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
physicalTopologyFile = importFile("josn");
checkImportStatus();
}
};
ActionListener readVirTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
deploymentFile = importFile("json");
checkImportStatus();
}
};
ActionListener readWorkloadBkListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
workloads_background = importFile("cvs");
checkImportStatus();
}
};
ActionListener readWorkloadListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
workloads = importFile("cvs");
checkImportStatus();
}
};
ActionListener addFogDeviceListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddFogDeviceDialog();
}
};
ActionListener addPhysicalNodeListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddPhysicalNodeDialog();
}
};
ActionListener addPhysicalEdgeListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddPhysicalEdgeDialog();
}
};
ActionListener addLinkListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddLinkDialog();
}
};
ActionListener addActuatorListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddActuatorDialog();
}
};
ActionListener addSensorListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
openAddSensorDialog();
}
};
ActionListener importPhyTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String fileName = importFile("josn");
Graph phyGraph= Bridge.jsonToGraph(fileName, 0);
physicalGraph = phyGraph;
physicalCanvas.setGraph(physicalGraph);
physicalCanvas.repaint();
}
};
ActionListener savePhyTopoListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
saveFile("json", physicalGraph);
} catch (IOException e1) {
e1.printStackTrace();
}
}
};
//---------- End ActionListener ----------
//---------- Start Creating project tool bar ----------
JToolBar toolbar = new JToolBar();
ImageIcon iSensor = new ImageIcon(
getClass().getResource("/images/sensor.png"));
ImageIcon iActuator = new ImageIcon(
getClass().getResource("/images/actuator.png"));
ImageIcon iFogDevice = new ImageIcon(
getClass().getResource("/images/dc.png"));
ImageIcon iLink = new ImageIcon(
getClass().getResource("/images/hline2.png"));
ImageIcon iHOpen = new ImageIcon(
getClass().getResource("/images/openPhyTop.png"));
ImageIcon iHSave = new ImageIcon(
getClass().getResource("/images/savePhyTop.png"));
ImageIcon run = new ImageIcon(
getClass().getResource("/images/play.png"));
ImageIcon exit = new ImageIcon(
getClass().getResource("/images/exit.png"));
final JButton btnSensor = new JButton(iSensor);
btnSensor.setToolTipText("Add Sensor");
final JButton btnActuator = new JButton(iActuator);
btnActuator.setToolTipText("Add Actuator");
final JButton btnFogDevice = new JButton(iFogDevice);
btnFogDevice.setToolTipText("Add Fog Device");
final JButton btnLink = new JButton(iLink);
btnLink.setToolTipText("Add Link");
final JButton btnHopen = new JButton(iHOpen);
btnHopen.setToolTipText("Open Physical Topology");
final JButton btnHsave = new JButton(iHSave);
btnHsave.setToolTipText("Save Physical Topology");
btnRun = new JButton(run);
btnRun.setToolTipText("Start simulation");
JButton btnExit = new JButton(exit);
btnExit.setToolTipText("Exit CloudSim");
toolbar.setAlignmentX(0);
btnSensor.addActionListener(addSensorListener);
btnActuator.addActionListener(addActuatorListener);
btnFogDevice.addActionListener(addFogDeviceListener);
btnLink.addActionListener(addLinkListener);
btnHopen.addActionListener(importPhyTopoListener);
btnHsave.addActionListener(savePhyTopoListener);
btnRun.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if("i"==mode){
if(physicalTopologyFile==null || physicalTopologyFile.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select physicalTopologyFile", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(deploymentFile==null || deploymentFile.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select deploymentFile", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(workloads_background==null || workloads_background.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select workloads_background", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
if(workloads==null || workloads.isEmpty()){
JOptionPane.showMessageDialog(panel, "Please select workloads", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// run simulation
SDNRun run = new SDNRun(physicalTopologyFile, deploymentFile,
workloads_background, workloads, FogGui.this);
}else if("m"==mode){
}
}
});
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
toolbar.add(btnSensor);
toolbar.add(btnActuator);
toolbar.add(btnFogDevice);
toolbar.add(btnLink);
toolbar.add(btnHopen);
toolbar.add(btnHsave);
toolbar.addSeparator();
/*toolbar.add(btnSensorModule);
toolbar.add(btnActuatorModule);
toolbar.add(btnModule);
toolbar.add(btnAppEdge);*/
toolbar.addSeparator();
toolbar.add(btnRun);
toolbar.add(btnExit);
panel.add(toolbar);
contentPane.add(panel, BorderLayout.NORTH);
//---------- End Creating project tool bar ----------
//---------- Start Creating project menu bar ----------
//1-1
JMenuBar menubar = new JMenuBar();
//ImageIcon iconNew = new ImageIcon(getClass().getResource("/src/new.png"));
//2-1
JMenu graph = new JMenu("Graph");
graph.setMnemonic(KeyEvent.VK_G);
//Graph by importing json and cvs files
final JMenuItem MiPhy = new JMenuItem("Physical Topology");
final JMenuItem MiVir = new JMenuItem("Virtual Topology");
final JMenuItem MiWl1 = new JMenuItem("Workload Background");
final JMenuItem MiWl2 = new JMenuItem("Workload");
//Graph drawing elements
final JMenu MuPhy = new JMenu("Physical");
JMenuItem MiFogDevice = new JMenuItem("Add Fog Device");
JMenuItem MiPhyEdge = new JMenuItem("Add Edge");
JMenuItem MiPhyOpen = new JMenuItem("Import Physical Topology");
JMenuItem MiPhySave = new JMenuItem("Save Physical Topology");
MuPhy.add(MiFogDevice);
MuPhy.add(MiPhyEdge);
MuPhy.add(MiPhyOpen);
MuPhy.add(MiPhySave);
MiPhy.addActionListener(readPhyTopoListener);
MiVir.addActionListener(readVirTopoListener);
MiWl1.addActionListener(readWorkloadBkListener);
MiWl2.addActionListener(readWorkloadListener);
MiFogDevice.addActionListener(addFogDeviceListener);
MiPhyEdge.addActionListener(addPhysicalEdgeListener);
MiPhyOpen.addActionListener(importPhyTopoListener);
MiPhySave.addActionListener(savePhyTopoListener);
graph.add(MuPhy);
//graph.add(MuVir);
graph.add(MiPhy);
//graph.add(MiVir);
graph.add(MiWl1);
graph.add(MiWl2);
//2-2
JMenu view = new JMenu("View");
view.setMnemonic(KeyEvent.VK_F);
//switch mode between manual mode (to create graph by hand) and import mode (to create graph from file)
ActionListener actionSwitcher = new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String cmd = e.getActionCommand();
if("Canvas" == cmd){
btnSensor.setVisible(true);
btnActuator.setVisible(true);
btnFogDevice.setVisible(true);
btnLink.setVisible(true);
btnHopen.setVisible(true);
btnHsave.setVisible(true);
MiPhy.setVisible(false);
MiVir.setVisible(false);
MiWl1.setVisible(false);
MiWl2.setVisible(false);
MuPhy.setVisible(true);
//MuVir.setVisible(true);
btnRun.setVisible(false);
btnRun.setEnabled(false);
mode = "m";
}else if("Execution" == cmd){
btnSensor.setVisible(false);
btnActuator.setVisible(false);
btnFogDevice.setVisible(false);
btnLink.setVisible(false);
btnHopen.setVisible(false);
btnHsave.setVisible(false);
MiPhy.setVisible(true);
MiVir.setVisible(true);
MiWl1.setVisible(true);
MiWl2.setVisible(true);
MuPhy.setVisible(false);
//MuVir.setVisible(false);
btnRun.setVisible(true);
btnRun.setEnabled(false);
mode = "i";
}
//System.out.println(e.getActionCommand());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
JRadioButtonMenuItem manualMode = new JRadioButtonMenuItem("Canvas");
manualMode.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK));
manualMode.addActionListener(actionSwitcher);
JRadioButtonMenuItem importMode = new JRadioButtonMenuItem("Execution");
importMode.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
importMode.addActionListener(actionSwitcher);
ButtonGroup group = new ButtonGroup();
group.add(manualMode);
group.add(importMode);
JMenuItem fileExit = new JMenuItem("Exit");
fileExit.setMnemonic(KeyEvent.VK_C);
fileExit.setToolTipText("Exit CloudSim");
fileExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
ActionEvent.CTRL_MASK));
fileExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
view.add(manualMode);
view.add(importMode);
view.addSeparator();
view.add(fileExit);
//3-1
menubar.add(view);
menubar.add(graph);
//4-1
setJMenuBar(menubar);
//----- End Creating project menu bar -----
//----- Start Initialize menu and tool bar -----
manualMode.setSelected(true);
mode = "m";
//btnHost.setVisible(true);
btnSensor.setVisible(true);
btnActuator.setVisible(true);
btnFogDevice.setVisible(true);
btnLink.setVisible(true);
btnHopen.setVisible(true);
btnHsave.setVisible(true);
MiPhy.setVisible(false);
MiVir.setVisible(false);
MiWl1.setVisible(false);
MiWl2.setVisible(false);
MuPhy.setVisible(true);
//MuVir.setVisible(true);
btnRun.setVisible(false);
btnRun.setEnabled(false);
//----- End Initialize menu and tool bar -----
}
protected void openAddActuatorDialog() {
AddActuator actuator = new AddActuator(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
protected void openAddLinkDialog() {
AddLink phyEdge = new AddLink(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
protected void openAddFogDeviceDialog() {
AddFogDevice fogDevice = new AddFogDevice(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
/** initialize Canvas */
private void initGraph(){
physicalGraph = new Graph();
//virtualGraph = new Graph();
physicalCanvas = new GraphView(physicalGraph);
//virtualCanvas = new GraphView(virtualGraph);
graph.add(physicalCanvas);
//graph.add(virtualCanvas);
contentPane.add(graph, BorderLayout.CENTER);
}
/** dialog opening */
private void openAddPhysicalNodeDialog(){
AddPhysicalNode phyNode = new AddPhysicalNode(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
private void openAddPhysicalEdgeDialog(){
AddPhysicalEdge phyEdge = new AddPhysicalEdge(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
protected void openAddSensorDialog() {
AddSensor sensor = new AddSensor(physicalGraph, FogGui.this);
physicalCanvas.repaint();
}
/** common utility */
private String importFile(String type){
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(type.toUpperCase()+" Files", type);
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(panel, "Import file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
return file.getPath();
}
return "";
}
/** save network topology */
private void saveFile(String type, Graph graph) throws IOException{
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter(type.toUpperCase()+" Files", type);
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showSaveDialog(panel);
if (ret == JFileChooser.APPROVE_OPTION) {
String jsonText = graph.toJsonString();
System.out.println(jsonText);
String path = fileopen.getSelectedFile().toString();
File file = new File(path);
FileOutputStream out = new FileOutputStream(file);
out.write(jsonText.getBytes());
out.close();
}
}
private static void setUIFont(javax.swing.plaf.FontUIResource f){
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
}
private void checkImportStatus(){
if((physicalTopologyFile!=null && !physicalTopologyFile.isEmpty()) &&
(deploymentFile!=null && !deploymentFile.isEmpty()) &&
(workloads_background!=null && !workloads_background.isEmpty()) &&
(workloads!=null && !workloads.isEmpty())){
btnRun.setEnabled(true);
}else{
btnRun.setEnabled(false);
}
}
/** Application entry point */
public static void main(String args[]) throws InterruptedException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FogGui sdn = new FogGui();
sdn.setVisible(true);
}
});
}
}

View File

@@ -0,0 +1,288 @@
package org.fog.placement;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.AppModule;
import org.fog.application.Application;
import org.fog.entities.Actuator;
import org.fog.entities.FogDevice;
import org.fog.entities.Sensor;
import org.fog.utils.Config;
import org.fog.utils.FogEvents;
import org.fog.utils.FogUtils;
import org.fog.utils.NetworkUsageMonitor;
import org.fog.utils.TimeKeeper;
public class Controller extends SimEntity{
public static boolean ONLY_CLOUD = false;
private List<FogDevice> fogDevices;
private List<Sensor> sensors;
private List<Actuator> actuators;
private Map<String, Application> applications;
private Map<String, Integer> appLaunchDelays;
private Map<String, ModulePlacement> appModulePlacementPolicy;
public Controller(String name, List<FogDevice> fogDevices, List<Sensor> sensors, List<Actuator> actuators) {
super(name);
this.applications = new HashMap<String, Application>();
setAppLaunchDelays(new HashMap<String, Integer>());
setAppModulePlacementPolicy(new HashMap<String, ModulePlacement>());
for(FogDevice fogDevice : fogDevices){
fogDevice.setControllerId(getId());
}
setFogDevices(fogDevices);
setActuators(actuators);
setSensors(sensors);
connectWithLatencies();
}
private FogDevice getFogDeviceById(int id){
for(FogDevice fogDevice : getFogDevices()){
if(id==fogDevice.getId())
return fogDevice;
}
return null;
}
private void connectWithLatencies(){
for(FogDevice fogDevice : getFogDevices()){
FogDevice parent = getFogDeviceById(fogDevice.getParentId());
if(parent == null)
continue;
double latency = fogDevice.getUplinkLatency();
parent.getChildToLatencyMap().put(fogDevice.getId(), latency);
parent.getChildrenIds().add(fogDevice.getId());
}
}
@Override
public void startEntity() {
for(String appId : applications.keySet()){
if(getAppLaunchDelays().get(appId)==0)
processAppSubmit(applications.get(appId));
else
send(getId(), getAppLaunchDelays().get(appId), FogEvents.APP_SUBMIT, applications.get(appId));
}
send(getId(), Config.RESOURCE_MANAGE_INTERVAL, FogEvents.CONTROLLER_RESOURCE_MANAGE);
send(getId(), Config.MAX_SIMULATION_TIME, FogEvents.STOP_SIMULATION);
for(FogDevice dev : getFogDevices())
sendNow(dev.getId(), FogEvents.RESOURCE_MGMT);
}
@Override
public void processEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.APP_SUBMIT:
processAppSubmit(ev);
break;
case FogEvents.TUPLE_FINISHED:
processTupleFinished(ev);
break;
case FogEvents.CONTROLLER_RESOURCE_MANAGE:
manageResources();
break;
case FogEvents.STOP_SIMULATION:
CloudSim.stopSimulation();
printTimeDetails();
printPowerDetails();
printCostDetails();
printNetworkUsageDetails();
System.exit(0);
break;
}
}
private void printNetworkUsageDetails() {
System.out.println("Total network usage = "+NetworkUsageMonitor.getNetworkUsage()/Config.MAX_SIMULATION_TIME);
}
private FogDevice getCloud(){
for(FogDevice dev : getFogDevices())
if(dev.getName().equals("cloud"))
return dev;
return null;
}
private void printCostDetails(){
System.out.println("Cost of execution in cloud = "+getCloud().getTotalCost());
}
private void printPowerDetails() {
for(FogDevice fogDevice : getFogDevices()){
System.out.println(fogDevice.getName() + " : Energy Consumed = "+fogDevice.getEnergyConsumption());
}
}
private String getStringForLoopId(int loopId){
for(String appId : getApplications().keySet()){
Application app = getApplications().get(appId);
for(AppLoop loop : app.getLoops()){
if(loop.getLoopId() == loopId)
return loop.getModules().toString();
}
}
return null;
}
private void printTimeDetails() {
System.out.println("=========================================");
System.out.println("============== RESULTS ==================");
System.out.println("=========================================");
System.out.println("EXECUTION TIME : "+ (Calendar.getInstance().getTimeInMillis() - TimeKeeper.getInstance().getSimulationStartTime()));
System.out.println("=========================================");
System.out.println("APPLICATION LOOP DELAYS");
System.out.println("=========================================");
for(Integer loopId : TimeKeeper.getInstance().getLoopIdToTupleIds().keySet()){
/*double average = 0, count = 0;
for(int tupleId : TimeKeeper.getInstance().getLoopIdToTupleIds().get(loopId)){
Double startTime = TimeKeeper.getInstance().getEmitTimes().get(tupleId);
Double endTime = TimeKeeper.getInstance().getEndTimes().get(tupleId);
if(startTime == null || endTime == null)
break;
average += endTime-startTime;
count += 1;
}
System.out.println(getStringForLoopId(loopId) + " ---> "+(average/count));*/
System.out.println(getStringForLoopId(loopId) + " ---> "+TimeKeeper.getInstance().getLoopIdToCurrentAverage().get(loopId));
}
System.out.println("=========================================");
System.out.println("TUPLE CPU EXECUTION DELAY");
System.out.println("=========================================");
for(String tupleType : TimeKeeper.getInstance().getTupleTypeToAverageCpuTime().keySet()){
System.out.println(tupleType + " ---> "+TimeKeeper.getInstance().getTupleTypeToAverageCpuTime().get(tupleType));
}
System.out.println("=========================================");
}
protected void manageResources(){
send(getId(), Config.RESOURCE_MANAGE_INTERVAL, FogEvents.CONTROLLER_RESOURCE_MANAGE);
}
private void processTupleFinished(SimEvent ev) {
}
@Override
public void shutdownEntity() {
}
public void submitApplication(Application application, int delay, ModulePlacement modulePlacement){
FogUtils.appIdToGeoCoverageMap.put(application.getAppId(), application.getGeoCoverage());
getApplications().put(application.getAppId(), application);
getAppLaunchDelays().put(application.getAppId(), delay);
getAppModulePlacementPolicy().put(application.getAppId(), modulePlacement);
for(Sensor sensor : sensors){
sensor.setApp(getApplications().get(sensor.getAppId()));
}
for(Actuator ac : actuators){
ac.setApp(getApplications().get(ac.getAppId()));
}
for(AppEdge edge : application.getEdges()){
if(edge.getEdgeType() == AppEdge.ACTUATOR){
String moduleName = edge.getSource();
for(Actuator actuator : getActuators()){
if(actuator.getActuatorType().equalsIgnoreCase(edge.getDestination()))
application.getModuleByName(moduleName).subscribeActuator(actuator.getId(), edge.getTupleType());
}
}
}
}
public void submitApplication(Application application, ModulePlacement modulePlacement){
submitApplication(application, 0, modulePlacement);
}
private void processAppSubmit(SimEvent ev){
Application app = (Application) ev.getData();
processAppSubmit(app);
}
private void processAppSubmit(Application application){
System.out.println(CloudSim.clock()+" Submitted application "+ application.getAppId());
FogUtils.appIdToGeoCoverageMap.put(application.getAppId(), application.getGeoCoverage());
getApplications().put(application.getAppId(), application);
ModulePlacement modulePlacement = getAppModulePlacementPolicy().get(application.getAppId());
for(FogDevice fogDevice : fogDevices){
sendNow(fogDevice.getId(), FogEvents.ACTIVE_APP_UPDATE, application);
}
Map<Integer, List<AppModule>> deviceToModuleMap = modulePlacement.getDeviceToModuleMap();
for(Integer deviceId : deviceToModuleMap.keySet()){
for(AppModule module : deviceToModuleMap.get(deviceId)){
sendNow(deviceId, FogEvents.APP_SUBMIT, application);
sendNow(deviceId, FogEvents.LAUNCH_MODULE, module);
}
}
}
public List<FogDevice> getFogDevices() {
return fogDevices;
}
public void setFogDevices(List<FogDevice> fogDevices) {
this.fogDevices = fogDevices;
}
public Map<String, Integer> getAppLaunchDelays() {
return appLaunchDelays;
}
public void setAppLaunchDelays(Map<String, Integer> appLaunchDelays) {
this.appLaunchDelays = appLaunchDelays;
}
public Map<String, Application> getApplications() {
return applications;
}
public void setApplications(Map<String, Application> applications) {
this.applications = applications;
}
public List<Sensor> getSensors() {
return sensors;
}
public void setSensors(List<Sensor> sensors) {
for(Sensor sensor : sensors)
sensor.setControllerId(getId());
this.sensors = sensors;
}
public List<Actuator> getActuators() {
return actuators;
}
public void setActuators(List<Actuator> actuators) {
this.actuators = actuators;
}
public Map<String, ModulePlacement> getAppModulePlacementPolicy() {
return appModulePlacementPolicy;
}
public void setAppModulePlacementPolicy(Map<String, ModulePlacement> appModulePlacementPolicy) {
this.appModulePlacementPolicy = appModulePlacementPolicy;
}
}

View File

@@ -0,0 +1,43 @@
package org.fog.placement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ModuleMapping {
/**
* Mapping from node name to list of <moduleName, numInstances> of instances to be launched on node
*/
protected Map<String, List<String>> moduleMapping;
public static ModuleMapping createModuleMapping(){
return new ModuleMapping();
}
public Map<String, List<String>> getModuleMapping() {
return moduleMapping;
}
public void setModuleMapping(Map<String, List<String>> moduleMapping) {
this.moduleMapping = moduleMapping;
}
protected ModuleMapping(){
setModuleMapping(new HashMap<String, List<String>>());
}
/**
* Add <b>instanceCount</b> number of instances of module <b>moduleName</b> to <b>device deviceName</b>
* @param moduleName
* @param deviceName
* @param instanceCount
*/
public void addModuleToDevice(String moduleName, String deviceName){
if(!getModuleMapping().containsKey(deviceName))
getModuleMapping().put(deviceName, new ArrayList<String>());
if(!getModuleMapping().get(deviceName).contains(moduleName))
getModuleMapping().get(deviceName).add(moduleName);
}
}

View File

@@ -0,0 +1,124 @@
package org.fog.placement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.application.AppModule;
import org.fog.application.Application;
import org.fog.entities.FogDevice;
public abstract class ModulePlacement {
public static int ONLY_CLOUD = 1;
public static int EDGEWARDS = 2;
public static int USER_MAPPING = 3;
private List<FogDevice> fogDevices;
private Application application;
private Map<String, List<Integer>> moduleToDeviceMap;
private Map<Integer, List<AppModule>> deviceToModuleMap;
private Map<Integer, Map<String, Integer>> moduleInstanceCountMap;
protected abstract void mapModules();
protected boolean canBeCreated(FogDevice fogDevice, AppModule module){
return fogDevice.getVmAllocationPolicy().allocateHostForVm(module);
}
protected int getParentDevice(int fogDeviceId){
return ((FogDevice)CloudSim.getEntity(fogDeviceId)).getParentId();
}
protected FogDevice getFogDeviceById(int fogDeviceId){
return (FogDevice)CloudSim.getEntity(fogDeviceId);
}
protected boolean createModuleInstanceOnDevice(AppModule _module, final FogDevice device, int instanceCount){
return false;
}
protected boolean createModuleInstanceOnDevice(AppModule _module, final FogDevice device){
AppModule module = null;
if(getModuleToDeviceMap().containsKey(_module.getName()))
module = new AppModule(_module);
else
module = _module;
if(canBeCreated(device, module)){
System.out.println("Creating "+module.getName()+" on device "+device.getName());
if(!getDeviceToModuleMap().containsKey(device.getId()))
getDeviceToModuleMap().put(device.getId(), new ArrayList<AppModule>());
getDeviceToModuleMap().get(device.getId()).add(module);
if(!getModuleToDeviceMap().containsKey(module.getName()))
getModuleToDeviceMap().put(module.getName(), new ArrayList<Integer>());
getModuleToDeviceMap().get(module.getName()).add(device.getId());
return true;
} else {
System.err.println("Module "+module.getName()+" cannot be created on device "+device.getName());
System.err.println("Terminating");
return false;
}
}
protected FogDevice getDeviceByName(String deviceName) {
for(FogDevice dev : getFogDevices()){
if(dev.getName().equals(deviceName))
return dev;
}
return null;
}
protected FogDevice getDeviceById(int id){
for(FogDevice dev : getFogDevices()){
if(dev.getId() == id)
return dev;
}
return null;
}
public List<FogDevice> getFogDevices() {
return fogDevices;
}
public void setFogDevices(List<FogDevice> fogDevices) {
this.fogDevices = fogDevices;
}
public Application getApplication() {
return application;
}
public void setApplication(Application application) {
this.application = application;
}
public Map<String, List<Integer>> getModuleToDeviceMap() {
return moduleToDeviceMap;
}
public void setModuleToDeviceMap(Map<String, List<Integer>> moduleToDeviceMap) {
this.moduleToDeviceMap = moduleToDeviceMap;
}
public Map<Integer, List<AppModule>> getDeviceToModuleMap() {
return deviceToModuleMap;
}
public void setDeviceToModuleMap(Map<Integer, List<AppModule>> deviceToModuleMap) {
this.deviceToModuleMap = deviceToModuleMap;
}
public Map<Integer, Map<String, Integer>> getModuleInstanceCountMap() {
return moduleInstanceCountMap;
}
public void setModuleInstanceCountMap(Map<Integer, Map<String, Integer>> moduleInstanceCountMap) {
this.moduleInstanceCountMap = moduleInstanceCountMap;
}
}

View File

@@ -0,0 +1,525 @@
package org.fog.placement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.util.Pair;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.application.AppEdge;
import org.fog.application.AppModule;
import org.fog.application.Application;
import org.fog.application.selectivity.SelectivityModel;
import org.fog.entities.Actuator;
import org.fog.entities.FogDevice;
import org.fog.entities.Sensor;
import org.fog.entities.Tuple;
import org.fog.utils.Logger;
public class ModulePlacementEdgewards extends ModulePlacement{
protected ModuleMapping moduleMapping;
protected List<Sensor> sensors;
protected List<Actuator> actuators;
protected Map<Integer, Double> currentCpuLoad;
/**
* Stores the current mapping of application modules to fog devices
*/
protected Map<Integer, List<String>> currentModuleMap;
protected Map<Integer, Map<String, Double>> currentModuleLoadMap;
protected Map<Integer, Map<String, Integer>> currentModuleInstanceNum;
public ModulePlacementEdgewards(List<FogDevice> fogDevices, List<Sensor> sensors, List<Actuator> actuators,
Application application, ModuleMapping moduleMapping){
this.setFogDevices(fogDevices);
this.setApplication(application);
this.setModuleMapping(moduleMapping);
this.setModuleToDeviceMap(new HashMap<String, List<Integer>>());
this.setDeviceToModuleMap(new HashMap<Integer, List<AppModule>>());
setSensors(sensors);
setActuators(actuators);
setCurrentCpuLoad(new HashMap<Integer, Double>());
setCurrentModuleMap(new HashMap<Integer, List<String>>());
setCurrentModuleLoadMap(new HashMap<Integer, Map<String, Double>>());
setCurrentModuleInstanceNum(new HashMap<Integer, Map<String, Integer>>());
for(FogDevice dev : getFogDevices()){
getCurrentCpuLoad().put(dev.getId(), 0.0);
getCurrentModuleLoadMap().put(dev.getId(), new HashMap<String, Double>());
getCurrentModuleMap().put(dev.getId(), new ArrayList<String>());
getCurrentModuleInstanceNum().put(dev.getId(), new HashMap<String, Integer>());
}
mapModules();
setModuleInstanceCountMap(getCurrentModuleInstanceNum());
}
@Override
protected void mapModules() {
for(String deviceName : getModuleMapping().getModuleMapping().keySet()){
for(String moduleName : getModuleMapping().getModuleMapping().get(deviceName)){
int deviceId = CloudSim.getEntityId(deviceName);
getCurrentModuleMap().get(deviceId).add(moduleName);
getCurrentModuleLoadMap().get(deviceId).put(moduleName, 0.0);
getCurrentModuleInstanceNum().get(deviceId).put(moduleName, 0);
}
}
List<List<Integer>> leafToRootPaths = getLeafToRootPaths();
for(List<Integer> path : leafToRootPaths){
placeModulesInPath(path);
}
for(int deviceId : getCurrentModuleMap().keySet()){
for(String module : getCurrentModuleMap().get(deviceId)){
createModuleInstanceOnDevice(getApplication().getModuleByName(module), getFogDeviceById(deviceId));
}
}
}
/**
* Get the list of modules that are ready to be placed
* @param placedModules Modules that have already been placed in current path
* @return list of modules ready to be placed
*/
private List<String> getModulesToPlace(List<String> placedModules){
Application app = getApplication();
List<String> modulesToPlace_1 = new ArrayList<String>();
List<String> modulesToPlace = new ArrayList<String>();
for(AppModule module : app.getModules()){
if(!placedModules.contains(module.getName()))
modulesToPlace_1.add(module.getName());
}
/*
* Filtering based on whether modules (to be placed) lower in physical topology are already placed
*/
for(String moduleName : modulesToPlace_1){
boolean toBePlaced = true;
for(AppEdge edge : app.getEdges()){
//CHECK IF OUTGOING DOWN EDGES ARE PLACED
if(edge.getSource().equals(moduleName) && edge.getDirection()==Tuple.DOWN && !placedModules.contains(edge.getDestination()))
toBePlaced = false;
//CHECK IF INCOMING UP EDGES ARE PLACED
if(edge.getDestination().equals(moduleName) && edge.getDirection()==Tuple.UP && !placedModules.contains(edge.getSource()))
toBePlaced = false;
}
if(toBePlaced)
modulesToPlace.add(moduleName);
}
return modulesToPlace;
}
protected double getRateOfSensor(String sensorType){
for(Sensor sensor : getSensors()){
if(sensor.getTupleType().equals(sensorType))
return 1/sensor.getTransmitDistribution().getMeanInterTransmitTime();
}
return 0;
}
private void placeModulesInPath(List<Integer> path) {
if(path.size()==0)return;
List<String> placedModules = new ArrayList<String>();
Map<AppEdge, Double> appEdgeToRate = new HashMap<AppEdge, Double>();
/**
* Periodic edges have a fixed periodicity of tuples, so setting the tuple rate beforehand
*/
for(AppEdge edge : getApplication().getEdges()){
if(edge.isPeriodic()){
appEdgeToRate.put(edge, 1/edge.getPeriodicity());
}
}
for(Integer deviceId : path){
FogDevice device = getFogDeviceById(deviceId);
Map<String, Integer> sensorsAssociated = getAssociatedSensors(device);
Map<String, Integer> actuatorsAssociated = getAssociatedActuators(device);
placedModules.addAll(sensorsAssociated.keySet()); // ADDING ALL SENSORS TO PLACED LIST
placedModules.addAll(actuatorsAssociated.keySet()); // ADDING ALL ACTUATORS TO PLACED LIST
/*
* Setting the rates of application edges emanating from sensors
*/
for(String sensor : sensorsAssociated.keySet()){
for(AppEdge edge : getApplication().getEdges()){
if(edge.getSource().equals(sensor)){
appEdgeToRate.put(edge, sensorsAssociated.get(sensor)*getRateOfSensor(sensor));
}
}
}
/*
* Updating the AppEdge rates for the entire application based on knowledge so far
*/
boolean changed = true;
while(changed){ //Loop runs as long as some new information is added
changed=false;
Map<AppEdge, Double> rateMap = new HashMap<AppEdge, Double>(appEdgeToRate);
for(AppEdge edge : rateMap.keySet()){
AppModule destModule = getApplication().getModuleByName(edge.getDestination());
if(destModule == null)continue;
Map<Pair<String, String>, SelectivityModel> map = destModule.getSelectivityMap();
for(Pair<String, String> pair : map.keySet()){
if(pair.getFirst().equals(edge.getTupleType())){
double outputRate = appEdgeToRate.get(edge)*map.get(pair).getMeanRate(); // getting mean rate from SelectivityModel
AppEdge outputEdge = getApplication().getEdgeMap().get(pair.getSecond());
if(!appEdgeToRate.containsKey(outputEdge) || appEdgeToRate.get(outputEdge)!=outputRate){
// if some new information is available
changed = true;
}
appEdgeToRate.put(outputEdge, outputRate);
}
}
}
}
/*
* Getting the list of modules ready to be placed on current device on path
*/
List<String> modulesToPlace = getModulesToPlace(placedModules);
while(modulesToPlace.size() > 0){ // Loop runs until all modules in modulesToPlace are deployed in the path
String moduleName = modulesToPlace.get(0);
double totalCpuLoad = 0;
//IF MODULE IS ALREADY PLACED UPSTREAM, THEN UPDATE THE EXISTING MODULE
int upsteamDeviceId = isPlacedUpstream(moduleName, path);
if(upsteamDeviceId > 0){
if(upsteamDeviceId==deviceId){
placedModules.add(moduleName);
modulesToPlace = getModulesToPlace(placedModules);
// NOW THE MODULE TO PLACE IS IN THE CURRENT DEVICE. CHECK IF THE NODE CAN SUSTAIN THE MODULE
for(AppEdge edge : getApplication().getEdges()){ // take all incoming edges
if(edge.getDestination().equals(moduleName)){
double rate = appEdgeToRate.get(edge);
totalCpuLoad += rate*edge.getTupleCpuLength();
}
}
if(totalCpuLoad + getCurrentCpuLoad().get(deviceId) > device.getHost().getTotalMips()){
Logger.debug("ModulePlacementEdgeward", "Need to shift module "+moduleName+" upstream from device " + device.getName());
List<String> _placedOperators = shiftModuleNorth(moduleName, totalCpuLoad, deviceId, modulesToPlace);
for(String placedOperator : _placedOperators){
if(!placedModules.contains(placedOperator))
placedModules.add(placedOperator);
}
} else{
placedModules.add(moduleName);
getCurrentCpuLoad().put(deviceId, getCurrentCpuLoad().get(deviceId)+totalCpuLoad);
getCurrentModuleInstanceNum().get(deviceId).put(moduleName, getCurrentModuleInstanceNum().get(deviceId).get(moduleName)+1);
Logger.debug("ModulePlacementEdgeward", "AppModule "+moduleName+" can be created on device "+device.getName());
}
}
}else{
// FINDING OUT WHETHER PLACEMENT OF OPERATOR ON DEVICE IS POSSIBLE
for(AppEdge edge : getApplication().getEdges()){ // take all incoming edges
if(edge.getDestination().equals(moduleName)){
double rate = appEdgeToRate.get(edge);
totalCpuLoad += rate*edge.getTupleCpuLength();
}
}
if(totalCpuLoad + getCurrentCpuLoad().get(deviceId) > device.getHost().getTotalMips()){
Logger.debug("ModulePlacementEdgeward", "Placement of operator "+moduleName+ "NOT POSSIBLE on device "+device.getName());
}
else{
Logger.debug("ModulePlacementEdgeward", "Placement of operator "+moduleName+ " on device "+device.getName() + " successful.");
getCurrentCpuLoad().put(deviceId, totalCpuLoad + getCurrentCpuLoad().get(deviceId));
System.out.println("Placement of operator "+moduleName+ " on device "+device.getName() + " successful.");
if(!currentModuleMap.containsKey(deviceId))
currentModuleMap.put(deviceId, new ArrayList<String>());
currentModuleMap.get(deviceId).add(moduleName);
placedModules.add(moduleName);
modulesToPlace = getModulesToPlace(placedModules);
getCurrentModuleLoadMap().get(device.getId()).put(moduleName, totalCpuLoad);
int max = 1;
for(AppEdge edge : getApplication().getEdges()){
if(edge.getSource().equals(moduleName) && actuatorsAssociated.containsKey(edge.getDestination()))
max = Math.max(actuatorsAssociated.get(edge.getDestination()), max);
if(edge.getDestination().equals(moduleName) && sensorsAssociated.containsKey(edge.getSource()))
max = Math.max(sensorsAssociated.get(edge.getSource()), max);
}
getCurrentModuleInstanceNum().get(deviceId).put(moduleName, max);
}
}
modulesToPlace.remove(moduleName);
}
}
}
/**
* Shifts a module moduleName from device deviceId northwards. This involves other modules that depend on it to be shifted north as well.
* @param moduleName
* @param cpuLoad cpuLoad of the module
* @param deviceId
*/
private List<String> shiftModuleNorth(String moduleName, double cpuLoad, Integer deviceId, List<String> operatorsToPlace) {
System.out.println(CloudSim.getEntityName(deviceId)+" is shifting "+moduleName+" north.");
List<String> modulesToShift = findModulesToShift(moduleName, deviceId);
Map<String, Integer> moduleToNumInstances = new HashMap<String, Integer>(); // Map of number of instances of modules that need to be shifted
double totalCpuLoad = 0;
Map<String, Double> loadMap = new HashMap<String, Double>();
for(String module : modulesToShift){
loadMap.put(module, getCurrentModuleLoadMap().get(deviceId).get(module));
moduleToNumInstances.put(module, getCurrentModuleInstanceNum().get(deviceId).get(module)+1);
totalCpuLoad += getCurrentModuleLoadMap().get(deviceId).get(module);
getCurrentModuleLoadMap().get(deviceId).remove(module);
getCurrentModuleMap().get(deviceId).remove(module);
getCurrentModuleInstanceNum().get(deviceId).remove(module);
}
getCurrentCpuLoad().put(deviceId, getCurrentCpuLoad().get(deviceId)-totalCpuLoad); // change info of current CPU load on device
loadMap.put(moduleName, loadMap.get(moduleName)+cpuLoad);
totalCpuLoad += cpuLoad;
int id = getParentDevice(deviceId);
while(true){ // Loop iterates over all devices in path upstream from current device. Tries to place modules (to be shifted northwards) on each of them.
if(id==-1){
// Loop has reached the apex fog device in hierarchy, and still could not place modules.
Logger.debug("ModulePlacementEdgeward", "Could not place modules "+modulesToShift+" northwards.");
break;
}
FogDevice fogDevice = getFogDeviceById(id);
if(getCurrentCpuLoad().get(id) + totalCpuLoad > fogDevice.getHost().getTotalMips()){
// Device cannot take up CPU load of incoming modules. Keep searching for device further north.
List<String> _modulesToShift = findModulesToShift(modulesToShift, id); // All modules in _modulesToShift are currently placed on device id
double cpuLoadShifted = 0; // the total CPU load shifted from device id to its parent
for(String module : _modulesToShift){
if(!modulesToShift.contains(module)){
// Add information of all newly added modules (to be shifted)
moduleToNumInstances.put(module, getCurrentModuleInstanceNum().get(id).get(module)+moduleToNumInstances.get(module));
loadMap.put(module, getCurrentModuleLoadMap().get(id).get(module));
cpuLoadShifted += getCurrentModuleLoadMap().get(id).get(module);
totalCpuLoad += getCurrentModuleLoadMap().get(id).get(module);
// Removing information of all modules (to be shifted north) in device with ID id
getCurrentModuleLoadMap().get(id).remove(module);
getCurrentModuleMap().get(id).remove(module);
getCurrentModuleInstanceNum().get(id).remove(module);
}
}
getCurrentCpuLoad().put(id, getCurrentCpuLoad().get(id)-cpuLoadShifted); // CPU load on device id gets reduced due to modules shifting northwards
modulesToShift = _modulesToShift;
id = getParentDevice(id); // iterating to parent device
} else{
// Device (@ id) can accommodate modules. Placing them here.
double totalLoad = 0;
for(String module : loadMap.keySet()){
totalLoad += loadMap.get(module);
getCurrentModuleLoadMap().get(id).put(module, loadMap.get(module));
getCurrentModuleMap().get(id).add(module);
String module_ = module;
int initialNumInstances = 0;
if(getCurrentModuleInstanceNum().get(id).containsKey(module_))
initialNumInstances = getCurrentModuleInstanceNum().get(id).get(module_);
int finalNumInstances = initialNumInstances + moduleToNumInstances.get(module_);
getCurrentModuleInstanceNum().get(id).put(module_, finalNumInstances);
}
getCurrentCpuLoad().put(id, totalLoad);
operatorsToPlace.removeAll(loadMap.keySet());
List<String> placedOperators = new ArrayList<String>();
for(String op : loadMap.keySet())placedOperators.add(op);
return placedOperators;
}
}
return new ArrayList<String>();
}
/**
* Get all modules that need to be shifted northwards along with <b>module</b>.
* Typically, these other modules are those that are hosted on device with ID <b>deviceId</b> and lie upstream of <b>module</b> in application model.
* @param module the module that needs to be shifted northwards
* @param deviceId the fog device ID that it is currently on
* @return list of all modules that need to be shifted north along with <b>module</b>
*/
private List<String> findModulesToShift(String module, Integer deviceId) {
List<String> modules = new ArrayList<String>();
modules.add(module);
return findModulesToShift(modules, deviceId);
/*List<String> upstreamModules = new ArrayList<String>();
upstreamModules.add(module);
boolean changed = true;
while(changed){ // Keep loop running as long as new information is added.
changed = false;
for(AppEdge edge : getApplication().getEdges()){
* If there is an application edge UP from the module to be shifted to another module in the same device
if(upstreamModules.contains(edge.getSource()) && edge.getDirection()==Tuple.UP &&
getCurrentModuleMap().get(deviceId).contains(edge.getDestination())
&& !upstreamModules.contains(edge.getDestination())){
upstreamModules.add(edge.getDestination());
changed = true;
}
}
}
return upstreamModules; */
}
/**
* Get all modules that need to be shifted northwards along with <b>modules</b>.
* Typically, these other modules are those that are hosted on device with ID <b>deviceId</b> and lie upstream of modules in <b>modules</b> in application model.
* @param module the module that needs to be shifted northwards
* @param deviceId the fog device ID that it is currently on
* @return list of all modules that need to be shifted north along with <b>modules</b>
*/
private List<String> findModulesToShift(List<String> modules, Integer deviceId) {
List<String> upstreamModules = new ArrayList<String>();
upstreamModules.addAll(modules);
boolean changed = true;
while(changed){ // Keep loop running as long as new information is added.
changed = false;
/*
* If there is an application edge UP from the module to be shifted to another module in the same device
*/
for(AppEdge edge : getApplication().getEdges()){
if(upstreamModules.contains(edge.getSource()) && edge.getDirection()==Tuple.UP &&
getCurrentModuleMap().get(deviceId).contains(edge.getDestination())
&& !upstreamModules.contains(edge.getDestination())){
upstreamModules.add(edge.getDestination());
changed = true;
}
}
}
return upstreamModules;
}
private int isPlacedUpstream(String operatorName, List<Integer> path) {
for(int deviceId : path){
if(currentModuleMap.containsKey(deviceId) && currentModuleMap.get(deviceId).contains(operatorName))
return deviceId;
}
return -1;
}
/**
* Gets all sensors associated with fog-device <b>device</b>
* @param device
* @return map from sensor type to number of such sensors
*/
private Map<String, Integer> getAssociatedSensors(FogDevice device) {
Map<String, Integer> endpoints = new HashMap<String, Integer>();
for(Sensor sensor : getSensors()){
if(sensor.getGatewayDeviceId()==device.getId()){
if(!endpoints.containsKey(sensor.getTupleType()))
endpoints.put(sensor.getTupleType(), 0);
endpoints.put(sensor.getTupleType(), endpoints.get(sensor.getTupleType())+1);
}
}
return endpoints;
}
/**
* Gets all actuators associated with fog-device <b>device</b>
* @param device
* @return map from actuator type to number of such sensors
*/
private Map<String, Integer> getAssociatedActuators(FogDevice device) {
Map<String, Integer> endpoints = new HashMap<String, Integer>();
for(Actuator actuator : getActuators()){
if(actuator.getGatewayDeviceId()==device.getId()){
if(!endpoints.containsKey(actuator.getActuatorType()))
endpoints.put(actuator.getActuatorType(), 0);
endpoints.put(actuator.getActuatorType(), endpoints.get(actuator.getActuatorType())+1);
}
}
return endpoints;
}
@SuppressWarnings("serial")
protected List<List<Integer>> getPaths(final int fogDeviceId){
FogDevice device = (FogDevice)CloudSim.getEntity(fogDeviceId);
if(device.getChildrenIds().size() == 0){
final List<Integer> path = (new ArrayList<Integer>(){{add(fogDeviceId);}});
List<List<Integer>> paths = (new ArrayList<List<Integer>>(){{add(path);}});
return paths;
}
List<List<Integer>> paths = new ArrayList<List<Integer>>();
for(int childId : device.getChildrenIds()){
List<List<Integer>> childPaths = getPaths(childId);
for(List<Integer> childPath : childPaths)
childPath.add(fogDeviceId);
paths.addAll(childPaths);
}
return paths;
}
protected List<List<Integer>> getLeafToRootPaths(){
FogDevice cloud=null;
for(FogDevice device : getFogDevices()){
if(device.getName().equals("cloud"))
cloud = device;
}
return getPaths(cloud.getId());
}
public ModuleMapping getModuleMapping() {
return moduleMapping;
}
public void setModuleMapping(ModuleMapping moduleMapping) {
this.moduleMapping = moduleMapping;
}
public Map<Integer, List<String>> getCurrentModuleMap() {
return currentModuleMap;
}
public void setCurrentModuleMap(Map<Integer, List<String>> currentModuleMap) {
this.currentModuleMap = currentModuleMap;
}
public List<Sensor> getSensors() {
return sensors;
}
public void setSensors(List<Sensor> sensors) {
this.sensors = sensors;
}
public List<Actuator> getActuators() {
return actuators;
}
public void setActuators(List<Actuator> actuators) {
this.actuators = actuators;
}
public Map<Integer, Double> getCurrentCpuLoad() {
return currentCpuLoad;
}
public void setCurrentCpuLoad(Map<Integer, Double> currentCpuLoad) {
this.currentCpuLoad= currentCpuLoad;
}
public Map<Integer, Map<String, Double>> getCurrentModuleLoadMap() {
return currentModuleLoadMap;
}
public void setCurrentModuleLoadMap(
Map<Integer, Map<String, Double>> currentModuleLoadMap) {
this.currentModuleLoadMap = currentModuleLoadMap;
}
public Map<Integer, Map<String, Integer>> getCurrentModuleInstanceNum() {
return currentModuleInstanceNum;
}
public void setCurrentModuleInstanceNum(
Map<Integer, Map<String, Integer>> currentModuleInstanceNum) {
this.currentModuleInstanceNum = currentModuleInstanceNum;
}
}

View File

@@ -0,0 +1,53 @@
package org.fog.placement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fog.application.AppModule;
import org.fog.application.Application;
import org.fog.entities.FogDevice;
public class ModulePlacementMapping extends ModulePlacement{
private ModuleMapping moduleMapping;
@Override
protected void mapModules() {
Map<String, List<String>> mapping = moduleMapping.getModuleMapping();
for(String deviceName : mapping.keySet()){
FogDevice device = getDeviceByName(deviceName);
for(String moduleName : mapping.get(deviceName)){
AppModule module = getApplication().getModuleByName(moduleName);
if(module == null)
continue;
createModuleInstanceOnDevice(module, device);
//getModuleInstanceCountMap().get(device.getId()).put(moduleName, mapping.get(deviceName).get(moduleName));
}
}
}
public ModulePlacementMapping(List<FogDevice> fogDevices, Application application,
ModuleMapping moduleMapping){
this.setFogDevices(fogDevices);
this.setApplication(application);
this.setModuleMapping(moduleMapping);
this.setModuleToDeviceMap(new HashMap<String, List<Integer>>());
this.setDeviceToModuleMap(new HashMap<Integer, List<AppModule>>());
this.setModuleInstanceCountMap(new HashMap<Integer, Map<String, Integer>>());
for(FogDevice device : getFogDevices())
getModuleInstanceCountMap().put(device.getId(), new HashMap<String, Integer>());
mapModules();
}
public ModuleMapping getModuleMapping() {
return moduleMapping;
}
public void setModuleMapping(ModuleMapping moduleMapping) {
this.moduleMapping = moduleMapping;
}
}

View File

@@ -0,0 +1,101 @@
package org.fog.placement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.application.AppEdge;
import org.fog.application.AppModule;
import org.fog.application.Application;
import org.fog.entities.Actuator;
import org.fog.entities.FogDevice;
import org.fog.entities.Sensor;
import org.fog.entities.Tuple;
public class ModulePlacementOnlyCloud extends ModulePlacement{
private List<Sensor> sensors;
private List<Actuator> actuators;
private int cloudId;
public ModulePlacementOnlyCloud(List<FogDevice> fogDevices, List<Sensor> sensors, List<Actuator> actuators, Application application){
this.setFogDevices(fogDevices);
this.setApplication(application);
this.setSensors(sensors);
this.setActuators(actuators);
this.setModuleToDeviceMap(new HashMap<String, List<Integer>>());
this.setDeviceToModuleMap(new HashMap<Integer, List<AppModule>>());
this.setModuleInstanceCountMap(new HashMap<Integer, Map<String, Integer>>());
this.cloudId = CloudSim.getEntityId("cloud");
mapModules();
computeModuleInstanceCounts();
}
private void computeModuleInstanceCounts(){
FogDevice cloud = getDeviceById(CloudSim.getEntityId("cloud"));
getModuleInstanceCountMap().put(cloud.getId(), new HashMap<String, Integer>());
for(Sensor sensor : getSensors()){
String sensorType = sensor.getSensorName();
if(!getModuleInstanceCountMap().get(cloud.getId()).containsKey(sensorType))
getModuleInstanceCountMap().get(cloud.getId()).put(sensorType, 0);
getModuleInstanceCountMap().get(cloud.getId()).put(sensorType, getModuleInstanceCountMap().get(cloud.getId()).get(sensorType)+1);
}
for(Actuator actuator : getActuators()){
String actuatorType = actuator.getActuatorType();
if(!getModuleInstanceCountMap().get(cloud.getId()).containsKey(actuatorType))
getModuleInstanceCountMap().get(cloud.getId()).put(actuatorType, 0);
getModuleInstanceCountMap().get(cloud.getId()).put(actuatorType, getModuleInstanceCountMap().get(cloud.getId()).get(actuatorType)+1);
}
while(!isModuleInstanceCalculationComplete()){
for(AppModule module : getApplication().getModules()){
int maxInstances = 0;
for(AppEdge edge : getApplication().getEdges()){
if(!getModuleInstanceCountMap().get(cloudId).containsKey(edge.getSource()))
continue;
if(edge.getDestination().equals(module.getName()) && edge.getDirection()==Tuple.UP){
maxInstances = Math.max(maxInstances, getModuleInstanceCountMap().get(cloudId).get(edge.getSource()));
}
}
getModuleInstanceCountMap().get(cloudId).put(module.getName(), maxInstances);
}
}
System.out.println(getModuleInstanceCountMap());
}
private boolean isModuleInstanceCalculationComplete() {
for(AppModule module : getApplication().getModules()){
if(!getModuleInstanceCountMap().get(cloudId).containsKey(module.getName()))
return false;
}
return true;
}
@Override
protected void mapModules() {
List<AppModule> modules = getApplication().getModules();
for(AppModule module : modules){
FogDevice cloud = getDeviceById(cloudId);
createModuleInstanceOnDevice(module, cloud);
}
}
public List<Actuator> getActuators() {
return actuators;
}
public void setActuators(List<Actuator> actuators) {
this.actuators = actuators;
}
public List<Sensor> getSensors() {
return sensors;
}
public void setSensors(List<Sensor> sensors) {
this.sensors = sensors;
}
}

View File

@@ -0,0 +1,284 @@
package org.fog.placement;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEntity;
import org.cloudbus.cloudsim.core.SimEvent;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.AppModule;
import org.fog.application.MyApplication;
import org.fog.entities.MyActuator;
import org.fog.entities.MyFogDevice;
import org.fog.entities.MySensor;
import org.fog.utils.Config;
import org.fog.utils.FogEvents;
import org.fog.utils.FogUtils;
import org.fog.utils.NetworkUsageMonitor;
import org.fog.utils.TimeKeeper;
public class MyController extends SimEntity{
public static boolean ONLY_CLOUD = false;
private List<MyFogDevice> fogDevices;
private List<MySensor> sensors;
private List<MyActuator> actuators;
private Map<String, MyApplication> applications;
private Map<String, Integer> appLaunchDelays;
private Map<String, MyModulePlacement> appModulePlacementPolicy;
public MyController(String name, List<MyFogDevice> fogDevices, List<MySensor> sensors, List<MyActuator> actuators) {
super(name);
this.applications = new HashMap<String, MyApplication>();
setAppLaunchDelays(new HashMap<String, Integer>());
setAppModulePlacementPolicy(new HashMap<String, MyModulePlacement>());
for(MyFogDevice fogDevice : fogDevices){
fogDevice.setControllerId(getId());
}
setMyFogDevices(fogDevices);
setMyActuators(actuators);
setMySensors(sensors);
connectWithLatencies();
}
private MyFogDevice getMyFogDeviceById(int id){
for(MyFogDevice fogDevice : getMyFogDevices()){
if(id==fogDevice.getId())
return fogDevice;
}
return null;
}
private void connectWithLatencies(){
for(MyFogDevice fogDevice : getMyFogDevices()){
MyFogDevice parent = getMyFogDeviceById(fogDevice.getParentId());
if(parent == null)
continue;
double latency = fogDevice.getUplinkLatency();
parent.getChildToLatencyMap().put(fogDevice.getId(), latency);
parent.getChildrenIds().add(fogDevice.getId());
}
}
@Override
public void startEntity() {
for(String appId : applications.keySet()){
if(getAppLaunchDelays().get(appId)==0)
processAppSubmit(applications.get(appId));
else
send(getId(), getAppLaunchDelays().get(appId), FogEvents.APP_SUBMIT, applications.get(appId));
}
send(getId(), Config.RESOURCE_MANAGE_INTERVAL, FogEvents.CONTROLLER_RESOURCE_MANAGE);
send(getId(), Config.MAX_SIMULATION_TIME, FogEvents.STOP_SIMULATION);
for(MyFogDevice dev : getMyFogDevices())
sendNow(dev.getId(), FogEvents.RESOURCE_MGMT);
}
@Override
public void processEvent(SimEvent ev) {
switch(ev.getTag()){
case FogEvents.APP_SUBMIT:
processAppSubmit(ev);
break;
case FogEvents.TUPLE_FINISHED:
processTupleFinished(ev);
break;
case FogEvents.CONTROLLER_RESOURCE_MANAGE:
manageResources();
break;
case FogEvents.STOP_SIMULATION:
CloudSim.stopSimulation();
printTimeDetails();
printPowerDetails();
printCostDetails();
printNetworkUsageDetails();
System.exit(0);
break;
}
}
private void printNetworkUsageDetails() {
System.out.println("Total network usage = "+NetworkUsageMonitor.getNetworkUsage()/Config.MAX_SIMULATION_TIME);
}
private MyFogDevice getCloud(){
for(MyFogDevice dev : getMyFogDevices())
if(dev.getName().equals("cloud"))
return dev;
return null;
}
private void printCostDetails(){
System.out.println("Cost of execution in cloud = "+getCloud().getTotalCost());
}
private void printPowerDetails() {
for(MyFogDevice fogDevice : getMyFogDevices()){
System.out.println(fogDevice.getName() + " : Energy Consumed = "+fogDevice.getEnergyConsumption());
}
}
private String getStringForLoopId(int loopId){
for(String appId : getMyApplications().keySet()){
MyApplication app = getMyApplications().get(appId);
for(AppLoop loop : app.getLoops()){
if(loop.getLoopId() == loopId)
return loop.getModules().toString();
}
}
return null;
}
private void printTimeDetails() {
System.out.println("=========================================");
System.out.println("============== RESULTS ==================");
System.out.println("=========================================");
System.out.println("EXECUTION TIME : "+ (Calendar.getInstance().getTimeInMillis() - TimeKeeper.getInstance().getSimulationStartTime()));
System.out.println("=========================================");
System.out.println("APPLICATION LOOP DELAYS");
System.out.println("=========================================");
for(Integer loopId : TimeKeeper.getInstance().getLoopIdToTupleIds().keySet()){
System.out.println(getStringForLoopId(loopId) + " ---> "+TimeKeeper.getInstance().getLoopIdToCurrentAverage().get(loopId));
}
System.out.println("=========================================");
System.out.println("TUPLE CPU EXECUTION DELAY");
System.out.println("=========================================");
for(String tupleType : TimeKeeper.getInstance().getTupleTypeToAverageCpuTime().keySet()){
System.out.println(tupleType + " ---> "+TimeKeeper.getInstance().getTupleTypeToAverageCpuTime().get(tupleType));
}
System.out.println("=========================================");
}
protected void manageResources(){
send(getId(), Config.RESOURCE_MANAGE_INTERVAL, FogEvents.CONTROLLER_RESOURCE_MANAGE);
}
private void processTupleFinished(SimEvent ev) {
}
@Override
public void shutdownEntity() {
}
public void submitApplication(MyApplication application, int delay, MyModulePlacement modulePlacement){
FogUtils.appIdToGeoCoverageMap.put(application.getAppId(), application.getGeoCoverage());
getMyApplications().put(application.getAppId(), application);
getAppLaunchDelays().put(application.getAppId(), delay);
getAppModulePlacementPolicy().put(application.getAppId(), modulePlacement);
for(MySensor sensor : sensors){
sensor.setApp(getMyApplications().get(sensor.getAppId()));
}
for(MyActuator ac : actuators){
ac.setApp(getMyApplications().get(ac.getAppId()));
}
for(AppEdge edge : application.getEdges()){
if(edge.getEdgeType() == AppEdge.ACTUATOR){
String moduleName = edge.getSource();
for(MyActuator actuator : getMyActuators()){
if(actuator.getMyActuatorType().equalsIgnoreCase(edge.getDestination()))
application.getModuleByName(moduleName).subscribeActuator(actuator.getId(), edge.getTupleType());
}
}
}
}
public void submitApplication(MyApplication application, MyModulePlacement modulePlacement){
submitApplication(application, 0, modulePlacement);
}
private void processAppSubmit(SimEvent ev){
MyApplication app = (MyApplication) ev.getData();
processAppSubmit(app);
}
private void processAppSubmit(MyApplication application){
System.out.println(CloudSim.clock()+" Submitted application "+ application.getAppId());
FogUtils.appIdToGeoCoverageMap.put(application.getAppId(), application.getGeoCoverage());
getMyApplications().put(application.getAppId(), application);
MyModulePlacement modulePlacement = getAppModulePlacementPolicy().get(application.getAppId());
for(MyFogDevice fogDevice : fogDevices){
sendNow(fogDevice.getId(), FogEvents.ACTIVE_APP_UPDATE, application);
}
Map<Integer, List<AppModule>> deviceToModuleMap = modulePlacement.getDeviceToModuleMap();
for(Integer deviceId : deviceToModuleMap.keySet()){
for(AppModule module : deviceToModuleMap.get(deviceId)){
sendNow(deviceId, FogEvents.APP_SUBMIT, application);
System.out.println(CloudSim.clock()+" Trying to Launch "+ module.getName() + " in "+getMyFogDeviceById(deviceId).getName());
sendNow(deviceId, FogEvents.LAUNCH_MODULE, module);
}
}
}
public List<MyFogDevice> getMyFogDevices() {
return fogDevices;
}
public void setMyFogDevices(List<MyFogDevice> fogDevices) {
this.fogDevices = fogDevices;
}
public Map<String, Integer> getAppLaunchDelays() {
return appLaunchDelays;
}
public void setAppLaunchDelays(Map<String, Integer> appLaunchDelays) {
this.appLaunchDelays = appLaunchDelays;
}
public Map<String, MyApplication> getMyApplications() {
return applications;
}
public void setMyApplications(Map<String, MyApplication> applications) {
this.applications = applications;
}
public List<MySensor> getMySensors() {
return sensors;
}
public void setMySensors(List<MySensor> sensors) {
for(MySensor sensor : sensors)
sensor.setControllerId(getId());
this.sensors = sensors;
}
public List<MyActuator> getMyActuators() {
return actuators;
}
public void setMyActuators(List<MyActuator> actuators) {
this.actuators = actuators;
}
public Map<String, MyModulePlacement> getAppModulePlacementPolicy() {
return appModulePlacementPolicy;
}
public void setAppModulePlacementPolicy(Map<String, MyModulePlacement> appModulePlacementPolicy) {
this.appModulePlacementPolicy = appModulePlacementPolicy;
}
}

View File

@@ -0,0 +1,168 @@
package org.fog.placement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.application.AppModule;
import org.fog.application.MyApplication;
import org.fog.entities.MyActuator;
import org.fog.entities.MyFogDevice;
import org.fog.entities.MySensor;
public class MyModulePlacement extends MyPlacement{
protected ModuleMapping moduleMapping;
protected List<MySensor> sensors;
protected List<MyActuator> actuators;
protected String moduleToPlace;
protected Map<Integer, Integer> deviceMipsInfo;
public MyModulePlacement(List<MyFogDevice> fogDevices, List<MySensor> sensors, List<MyActuator> actuators,
MyApplication application, ModuleMapping moduleMapping, String moduleToPlace){
this.setMyFogDevices(fogDevices);
this.setMyApplication(application);
this.setModuleMapping(moduleMapping);
this.setModuleToDeviceMap(new HashMap<String, List<Integer>>());
this.setDeviceToModuleMap(new HashMap<Integer, List<AppModule>>());
setMySensors(sensors);
setMyActuators(actuators);
this.moduleToPlace = moduleToPlace;
this.deviceMipsInfo = new HashMap<Integer, Integer>();
mapModules();
}
@Override
protected void mapModules() {
for(String deviceName : getModuleMapping().getModuleMapping().keySet()){
for(String moduleName : getModuleMapping().getModuleMapping().get(deviceName)){
int deviceId = CloudSim.getEntityId(deviceName);
AppModule appModule = getMyApplication().getModuleByName(moduleName);
if(!getDeviceToModuleMap().containsKey(deviceId))
{
List<AppModule>placedModules = new ArrayList<AppModule>();
placedModules.add(appModule);
getDeviceToModuleMap().put(deviceId, placedModules);
}
else
{
List<AppModule>placedModules = getDeviceToModuleMap().get(deviceId);
placedModules.add(appModule);
getDeviceToModuleMap().put(deviceId, placedModules);
}
}
}
for(MyFogDevice device:getMyFogDevices())
{
int deviceParent = -1;
List<Integer>children = new ArrayList<Integer>();
if(device.getLevel()==1)
{
if(!deviceMipsInfo.containsKey(device.getId()))
deviceMipsInfo.put(device.getId(), 0);
deviceParent = device.getParentId();
for(MyFogDevice deviceChild:getMyFogDevices())
{
if(deviceChild.getParentId()==device.getId())
{
children.add(deviceChild.getId());
}
}
Map<Integer, Double>childDeadline = new HashMap<Integer, Double>();
for(int childId:children)
childDeadline.put(childId,getMyApplication().getDeadlineInfo().get(childId).get(moduleToPlace));
List<Integer> keys = new ArrayList<Integer>(childDeadline.keySet());
for(int i = 0; i<keys.size()-1; i++)
{
for(int j=0;j<keys.size()-i-1;j++)
{
if(childDeadline.get(keys.get(j))>childDeadline.get(keys.get(j+1)))
{
int tempJ = keys.get(j);
int tempJn = keys.get(j+1);
keys.set(j, tempJn);
keys.set(j+1, tempJ);
}
}
}
int baseMipsOfPlacingModule = (int)getMyApplication().getModuleByName(moduleToPlace).getMips();
for(int key:keys)
{
int currentMips = deviceMipsInfo.get(device.getId());
AppModule appModule = getMyApplication().getModuleByName(moduleToPlace);
int additionalMips = getMyApplication().getAdditionalMipsInfo().get(key).get(moduleToPlace);
if(currentMips+baseMipsOfPlacingModule+additionalMips<device.getMips())
{
currentMips = currentMips+baseMipsOfPlacingModule+additionalMips;
deviceMipsInfo.put(device.getId(), currentMips);
if(!getDeviceToModuleMap().containsKey(device.getId()))
{
List<AppModule>placedModules = new ArrayList<AppModule>();
placedModules.add(appModule);
getDeviceToModuleMap().put(device.getId(), placedModules);
}
else
{
List<AppModule>placedModules = getDeviceToModuleMap().get(device.getId());
placedModules.add(appModule);
getDeviceToModuleMap().put(device.getId(), placedModules);
}
}
else
{
List<AppModule>placedModules = getDeviceToModuleMap().get(deviceParent);
placedModules.add(appModule);
getDeviceToModuleMap().put(deviceParent, placedModules);
}
}
}
}
}
public ModuleMapping getModuleMapping() {
return moduleMapping;
}
public void setModuleMapping(ModuleMapping moduleMapping) {
this.moduleMapping = moduleMapping;
}
public List<MySensor> getMySensors() {
return sensors;
}
public void setMySensors(List<MySensor> sensors) {
this.sensors = sensors;
}
public List<MyActuator> getMyActuators() {
return actuators;
}
public void setMyActuators(List<MyActuator> actuators) {
this.actuators = actuators;
}
}

View File

@@ -0,0 +1,124 @@
package org.fog.placement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.application.AppModule;
import org.fog.application.MyApplication;
import org.fog.entities.MyFogDevice;
public abstract class MyPlacement {
public static int ONLY_CLOUD = 1;
public static int EDGEWARDS = 2;
public static int USER_MAPPING = 3;
private List<MyFogDevice> fogDevices;
private MyApplication application;
private Map<String, List<Integer>> moduleToDeviceMap;
private Map<Integer, List<AppModule>> deviceToModuleMap;
private Map<Integer, Map<String, Integer>> moduleInstanceCountMap;
protected abstract void mapModules();
protected boolean canBeCreated(MyFogDevice fogDevice, AppModule module){
return fogDevice.getVmAllocationPolicy().allocateHostForVm(module);
}
protected int getParentDevice(int fogDeviceId){
return ((MyFogDevice)CloudSim.getEntity(fogDeviceId)).getParentId();
}
protected MyFogDevice getMyFogDeviceById(int fogDeviceId){
return (MyFogDevice)CloudSim.getEntity(fogDeviceId);
}
protected boolean createModuleInstanceOnDevice(AppModule _module, final MyFogDevice device, int instanceCount){
return false;
}
protected boolean createModuleInstanceOnDevice(AppModule _module, final MyFogDevice device){
AppModule module = null;
if(getModuleToDeviceMap().containsKey(_module.getName()))
module = new AppModule(_module);
else
module = _module;
if(canBeCreated(device, module)){
System.out.println("Creating "+module.getName()+" on device "+device.getName());
if(!getDeviceToModuleMap().containsKey(device.getId()))
getDeviceToModuleMap().put(device.getId(), new ArrayList<AppModule>());
getDeviceToModuleMap().get(device.getId()).add(module);
if(!getModuleToDeviceMap().containsKey(module.getName()))
getModuleToDeviceMap().put(module.getName(), new ArrayList<Integer>());
getModuleToDeviceMap().get(module.getName()).add(device.getId());
return true;
} else {
System.err.println("Module "+module.getName()+" cannot be created on device "+device.getName());
System.err.println("Terminating");
return false;
}
}
protected MyFogDevice getDeviceByName(String deviceName) {
for(MyFogDevice dev : getMyFogDevices()){
if(dev.getName().equals(deviceName))
return dev;
}
return null;
}
protected MyFogDevice getDeviceById(int id){
for(MyFogDevice dev : getMyFogDevices()){
if(dev.getId() == id)
return dev;
}
return null;
}
public List<MyFogDevice> getMyFogDevices() {
return fogDevices;
}
public void setMyFogDevices(List<MyFogDevice> fogDevices) {
this.fogDevices = fogDevices;
}
public MyApplication getMyApplication() {
return application;
}
public void setMyApplication(MyApplication application) {
this.application = application;
}
public Map<String, List<Integer>> getModuleToDeviceMap() {
return moduleToDeviceMap;
}
public void setModuleToDeviceMap(Map<String, List<Integer>> moduleToDeviceMap) {
this.moduleToDeviceMap = moduleToDeviceMap;
}
public Map<Integer, List<AppModule>> getDeviceToModuleMap() {
return deviceToModuleMap;
}
public void setDeviceToModuleMap(Map<Integer, List<AppModule>> deviceToModuleMap) {
this.deviceToModuleMap = deviceToModuleMap;
}
public Map<Integer, Map<String, Integer>> getModuleInstanceCountMap() {
return moduleInstanceCountMap;
}
public void setModuleInstanceCountMap(Map<Integer, Map<String, Integer>> moduleInstanceCountMap) {
this.moduleInstanceCountMap = moduleInstanceCountMap;
}
}

View File

@@ -0,0 +1,86 @@
package org.fog.policy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.fog.application.AppModule;
public class AppModuleAllocationPolicy extends VmAllocationPolicy{
private Host fogHost;
private List<Integer> appModuleIds;
public AppModuleAllocationPolicy(List<? extends Host> list) {
super(list);
if(list.size()==1)
fogHost = list.get(0);
appModuleIds = new ArrayList<Integer>();
}
@Override
public boolean allocateHostForVm(Vm vm) {
Host host = fogHost;
boolean result = host.vmCreate(vm);
if (result) { // if vm were succesfully created in the host
getAppModuleIdsIds().add(vm.getId());
}
return result;
}
@Override
public boolean allocateHostForVm(Vm vm, Host host) {
boolean result = host.vmCreate(vm);
if (result) { // if vm were succesfully created in the host
getAppModuleIdsIds().add(vm.getId());
}
return result;
}
@Override
public List<Map<String, Object>> optimizeAllocation(
List<? extends Vm> vmList) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deallocateHostForVm(Vm vm) {
if (fogHost != null) {
fogHost.vmDestroy(vm);
}
}
@Override
public Host getHost(Vm vm) {
return fogHost;
}
@Override
public Host getHost(int vmId, int userId) {
return fogHost;
}
public Host getFogHost() {
return fogHost;
}
public void setFogHost(Host fogHost) {
this.fogHost = fogHost;
}
public List<Integer> getAppModuleIdsIds() {
return appModuleIds;
}
public void setAppModuleIds(List<Integer> appModuleIds) {
this.appModuleIds = appModuleIds;
}
}

View File

@@ -0,0 +1,16 @@
package org.fog.scheduler;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.VmSchedulerTimeShared;
import org.cloudbus.cloudsim.VmSchedulerTimeSharedOverSubscription;
import org.cloudbus.cloudsim.sdn.overbooking.VmSchedulerTimeSharedOverbookingEnergy;
public class StreamOperatorScheduler extends VmSchedulerTimeSharedOverbookingEnergy{
public StreamOperatorScheduler(List<? extends Pe> pelist) {
super(pelist);
}
}

View File

@@ -0,0 +1,44 @@
package org.fog.scheduler;
import org.cloudbus.cloudsim.CloudletSchedulerTimeShared;
import org.cloudbus.cloudsim.ResCloudlet;
public class TupleScheduler extends CloudletSchedulerTimeShared{
public TupleScheduler(double mips, int numberOfPes) {
//super(mips, numberOfPes);
super();
}
/**
* Get estimated cloudlet completion time.
*
* @param rcl the rcl
* @param time the time
* @return the estimated finish time
*/
public double getEstimatedFinishTime(ResCloudlet rcl, double time) {
//System.out.println("REMAINING CLOUDLET LENGTH : "+rcl.getRemainingCloudletLength()+"\tCLOUDLET LENGTH"+rcl.getCloudletLength());
//System.out.println("CURRENT ALLOC MIPS FOR CLOUDLET : "+getTotalCurrentAllocatedMipsForCloudlet(rcl, time));
/*>>>>>>>>>>>>>>>>>>>>*/
/* edit made by HARSHIT GUPTA */
System.out.println("ALLOCATED MIPS FOR CLOUDLET = "+getTotalCurrentAllocatedMipsForCloudlet(rcl, time));
return time
+ ((rcl.getRemainingCloudletLength()) / getTotalCurrentAllocatedMipsForCloudlet(rcl, time));
//return ((rcl.getRemainingCloudletLength()) / getTotalCurrentAllocatedMipsForCloudlet(rcl, time));
/*end of edit*/
/*<<<<<<<<<<<<<<<<<<<<<*/
}
// public void cloudletFinish(ResCloudlet rcl) {
// rcl.setCloudletStatus(Cloudlet.SUCCESS);
// rcl.finalizeCloudlet();
// getCloudletFinishedList().add(rcl);
// }
}

View File

@@ -0,0 +1,102 @@
package org.fog.test;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.application.selectivity.FractionalSelectivity;
import org.fog.entities.FogBroker;
import org.fog.entities.PhysicalTopology;
import org.fog.entities.Tuple;
import org.fog.placement.Controller;
import org.fog.placement.ModuleMapping;
import org.fog.placement.ModulePlacementEdgewards;
import org.fog.utils.JsonToTopology;
/**
* Simulation setup for EEG Beam Tractor Game extracting physical topology
* @author Harshit Gupta
*
*/
public class CleanFromJson {
public static void main(String[] args) {
Log.printLine("Starting VRGame...");
try {
Log.disable();
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
CloudSim.init(num_user, calendar, trace_flag);
String appId = "vr_game";
FogBroker broker = new FogBroker("broker");
Application application = createApplication(appId, broker.getId());
application.setUserId(broker.getId());
/*
* Creating the physical topology from specified JSON file
*/
PhysicalTopology physicalTopology = JsonToTopology.getPhysicalTopology(broker.getId(), appId, "topologies/routerTopology");
Controller controller = new Controller("master-controller", physicalTopology.getFogDevices(), physicalTopology.getSensors(),
physicalTopology.getActuators());
controller.submitApplication(application, 0, new ModulePlacementEdgewards(physicalTopology.getFogDevices(),
physicalTopology.getSensors(), physicalTopology.getActuators(),
application, ModuleMapping.createModuleMapping()));
CloudSim.startSimulation();
CloudSim.stopSimulation();
Log.printLine("VRGame finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
@SuppressWarnings({ "serial" })
private static Application createApplication(String appId, int userId){
Application application = Application.createApplication(appId, userId);
application.addAppModule("client", 10);
application.addAppModule("classifier", 10);
application.addAppModule("tuner", 10);
application.addTupleMapping("client", "TEMP", "_SENSOR", new FractionalSelectivity(1.0));
application.addTupleMapping("client", "CLASSIFICATION", "ACTUATOR", new FractionalSelectivity(1.0));
application.addTupleMapping("classifier", "_SENSOR", "CLASSIFICATION", new FractionalSelectivity(1.0));
application.addTupleMapping("classifier", "_SENSOR", "HISTORY", new FractionalSelectivity(0.1));
application.addTupleMapping("tuner", "HISTORY", "TUNING_PARAMS", new FractionalSelectivity(1.0));
application.addAppEdge("TEMP", "client", 1000, 100, "TEMP", Tuple.UP, AppEdge.SENSOR);
application.addAppEdge("client", "classifier", 8000, 100, "_SENSOR", Tuple.UP, AppEdge.MODULE);
application.addAppEdge("classifier", "tuner", 1000000, 100, "HISTORY", Tuple.UP, AppEdge.MODULE);
application.addAppEdge("classifier", "client", 1000, 100, "CLASSIFICATION", Tuple.DOWN, AppEdge.MODULE);
application.addAppEdge("tuner", "classifier", 1000, 100, "TUNING_PARAMS", Tuple.DOWN, AppEdge.MODULE);
application.addAppEdge("client", "MOTOR", 1000, 100, "ACTUATOR", Tuple.DOWN, AppEdge.ACTUATOR);
final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("TEMP");add("client");add("classifier");add("client");add("MOTOR");}});
final AppLoop loop2 = new AppLoop(new ArrayList<String>(){{add("classifier");add("tuner");add("classifier");}});
List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);add(loop2);}};
application.setLoops(loops);
//GeoCoverage geoCoverage = new GeoCoverage(-100, 100, -100, 100);
return application;
}
}

View File

@@ -0,0 +1,203 @@
package org.fog.test.perfeval;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.application.selectivity.FractionalSelectivity;
import org.fog.entities.*;
import org.fog.placement.Controller;
import org.fog.placement.ModuleMapping;
import org.fog.placement.ModulePlacementEdgewards;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.FogLinearPowerModel;
import org.fog.utils.FogUtils;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.DeterministicDistribution;
import java.util.*;
public class Birbnetes {
static int numOfFogDevices = 2;
static int numOfClientsPerFogDevice = 10;
static List<FogDevice> fogDevices = new ArrayList<>();
static Map<String, Integer> getIdByName = new HashMap<>();
static List<Sensor> sensors = new ArrayList<>();
static List<Actuator> actuators = new ArrayList<>();
private static FogDevice createAFogDevice(String nodeName, long mips,
int ram, long upBw, long downBw, int level, double ratePerMips, double busyPower, double idlePower) {
List<Pe> peList = new ArrayList<>();
peList.add(new Pe(0, new PeProvisionerOverbooking(mips)));
int hostId = FogUtils.generateEntityId();
long storage = 1000000;
int bw = 10000;
PowerHost host = new PowerHost(hostId, new RamProvisionerSimple(ram), new BwProvisionerOverbooking(bw), storage, peList, new StreamOperatorScheduler(peList), new FogLinearPowerModel(busyPower,
idlePower));
List<Host> hostList = new ArrayList<>();
hostList.add(host);
String arch = "x86";
String os = "Linux";
String vmm = "Xen";
double time_zone = 10.0;
double cost = 3.0;
double costPerMem = 0.05;
double costPerStorage = 0.001;
double costPerBw = 0.0;
LinkedList<Storage> storageList = new LinkedList<>();
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(arch, os, vmm, host, time_zone, cost,
costPerMem, costPerStorage, costPerBw);
FogDevice fogdevice = null;
try {
fogdevice = new FogDevice(nodeName, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
assert fogdevice != null;
fogdevice.setLevel(level);
return fogdevice;
}
private static Application createApplication(String appId, int brokerId) {
Application application = Application.createApplication(appId, brokerId);
application.addAppModule("ClientModule", 10);
application.addAppModule("MainModule", 120);
application.addAppModule("StorageModule", 120);
application.addAppEdge("Sensor", "ClientModule", 50, 8800,
"Sensor", Tuple.UP, AppEdge.SENSOR);
application.addAppEdge("ClientModule", "MainModule", 100,
1000, "PreProcessedData", Tuple.UP, AppEdge.MODULE);
application.addAppEdge("ClientModule", "StorageModule", 10,
8800, "StoreData", Tuple.UP, AppEdge.MODULE);
application.addAppEdge("MainModule", "ClientModule", 200,
1000, "ProcessedData", Tuple.DOWN, AppEdge.MODULE);
application.addAppEdge("ClientModule", "Actuators", 50, 1000,
"OutputData", Tuple.DOWN, AppEdge.ACTUATOR);
application.addTupleMapping("ClientModule", "Sensor", "PreProcessedData", new FractionalSelectivity(1.0));
application.addTupleMapping("ClientModule", "Sensor", "StoreData", new FractionalSelectivity(1.0));
application.addTupleMapping("MainModule", "PreProcessedData",
"ProcessedData", new FractionalSelectivity(1.0));
application.addTupleMapping("ClientModule", "ProcessedData",
"OutputData", new FractionalSelectivity(1.0));
final AppLoop loop1 = new AppLoop(new ArrayList<>() {{
add("Sensor");
add("ClientModule");
add("StorageModule");
add("MainModule");
add("ClientModule");
add("Actuator");
}});
List<AppLoop> loops = new ArrayList<>() {{
add(loop1);
}};
application.setLoops(loops);
return application;
}
private static FogDevice addLowLevelFogDevice(String id, int brokerId, String appId, int parentId) {
FogDevice lowLevelFogDevice = createAFogDevice("LowLevelFogDevice-" + id, 1000, 1000, 10000, 270, 2, 0, 87.53, 82.44);
lowLevelFogDevice.setParentId(parentId);
getIdByName.put(lowLevelFogDevice.getName(), lowLevelFogDevice.getId());
Sensor sensor = new Sensor("s-" + id, "Sensor", brokerId, appId, new DeterministicDistribution(getValue(5.00)));
sensors.add(sensor);
Actuator actuator = new Actuator("a-" + id, brokerId, appId,
"OutputData");
actuators.add(actuator);
sensor.setGatewayDeviceId(lowLevelFogDevice.getId());
sensor.setLatency(6.0);
actuator.setGatewayDeviceId(lowLevelFogDevice.getId());
actuator.setLatency(1.0);
return lowLevelFogDevice;
}
private static double getValue(double min) {
Random rn = new Random();
return rn.nextDouble() * 10 + min;
}
private static void createFogDevices(int brokerId, String appId) {
FogDevice cloud = createAFogDevice("cloud", 44800, 64000, 10000,
10000, 0, 0.01, 16 * 103, 16 * 83.25);
cloud.setParentId(-1);
fogDevices.add(cloud);
getIdByName.put(cloud.getName(), cloud.getId());
for (int i = 0; i < numOfFogDevices; i++) {
FogDevice device = createAFogDevice("FogDevice-" + i, 4000, 4000,
1000, 1000, 1, 0.01,
100, 70);
device.setParentId(cloud.getId());
device.setUplinkLatency(20);
for (int j = 0; j < numOfClientsPerFogDevice; j++) {
String clientId = i + "-" + j;
FogDevice client = addLowLevelFogDevice(clientId, brokerId, appId, device.getId());
client.setUplinkLatency(3);
fogDevices.add(client);
}
fogDevices.add(device);
getIdByName.put(device.getName(), device.getId());
}
}
public static void main(String[] args) {
Log.printLine("Starting Birbnetes...");
try {
Log.disable();
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
CloudSim.init(num_user, calendar, false);
String appId = "birbnetes"; // identifier of the application
FogBroker broker = new FogBroker("broker");
Application application = createApplication(appId, broker.getId());
application.setUserId(broker.getId());
createFogDevices(broker.getId(), appId);
ModuleMapping moduleMapping = ModuleMapping.createModuleMapping(); // initializing a module mapping
moduleMapping.addModuleToDevice("MainModule", "cloud");
moduleMapping.addModuleToDevice("StorageModule", "cloud");
for (FogDevice device : fogDevices) {
if (device.getName().startsWith("FogDevice")) {
moduleMapping.addModuleToDevice("ClientModule", device.getName());
}
}
Controller controller = new Controller("master-controller", fogDevices, sensors,
actuators);
controller.submitApplication(application, 0,
new ModulePlacementEdgewards(fogDevices, sensors, actuators, application, moduleMapping));
TimeKeeper.getInstance().setSimulationStartTime(Calendar.getInstance().getTimeInMillis());
CloudSim.startSimulation();
CloudSim.stopSimulation();
Log.printLine("Birbnetes finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
}

View File

@@ -0,0 +1,265 @@
package org.fog.test.perfeval;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.application.selectivity.FractionalSelectivity;
import org.fog.entities.Actuator;
import org.fog.entities.FogBroker;
import org.fog.entities.FogDevice;
import org.fog.entities.FogDeviceCharacteristics;
import org.fog.entities.Sensor;
import org.fog.entities.Tuple;
import org.fog.placement.Controller;
import org.fog.placement.ModuleMapping;
import org.fog.placement.ModulePlacementEdgewards;
import org.fog.placement.ModulePlacementMapping;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.FogLinearPowerModel;
import org.fog.utils.FogUtils;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.DeterministicDistribution;
/**
* Simulation setup for case study 2 - Intelligent Surveillance
* @author Harshit Gupta
*
*/
public class DCNSFog {
static List<FogDevice> fogDevices = new ArrayList<FogDevice>();
static List<Sensor> sensors = new ArrayList<Sensor>();
static List<Actuator> actuators = new ArrayList<Actuator>();
static int numOfAreas = 1;
static int numOfCamerasPerArea = 4;
private static boolean CLOUD = false;
public static void main(String[] args) {
Log.printLine("Starting DCNS...");
try {
Log.disable();
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
CloudSim.init(num_user, calendar, trace_flag);
String appId = "dcns"; // identifier of the application
FogBroker broker = new FogBroker("broker");
Application application = createApplication(appId, broker.getId());
application.setUserId(broker.getId());
createFogDevices(broker.getId(), appId);
Controller controller = null;
ModuleMapping moduleMapping = ModuleMapping.createModuleMapping(); // initializing a module mapping
for(FogDevice device : fogDevices){
if(device.getName().startsWith("m")){ // names of all Smart Cameras start with 'm'
moduleMapping.addModuleToDevice("motion_detector", device.getName()); // fixing 1 instance of the Motion Detector module to each Smart Camera
}
}
moduleMapping.addModuleToDevice("user_interface", "cloud"); // fixing instances of User Interface module in the Cloud
if(CLOUD){
// if the mode of deployment is cloud-based
moduleMapping.addModuleToDevice("object_detector", "cloud"); // placing all instances of Object Detector module in the Cloud
moduleMapping.addModuleToDevice("object_tracker", "cloud"); // placing all instances of Object Tracker module in the Cloud
}
controller = new Controller("master-controller", fogDevices, sensors,
actuators);
controller.submitApplication(application,
(CLOUD)?(new ModulePlacementMapping(fogDevices, application, moduleMapping))
:(new ModulePlacementEdgewards(fogDevices, sensors, actuators, application, moduleMapping)));
TimeKeeper.getInstance().setSimulationStartTime(Calendar.getInstance().getTimeInMillis());
CloudSim.startSimulation();
CloudSim.stopSimulation();
Log.printLine("VRGame finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
/**
* Creates the fog devices in the physical topology of the simulation.
* @param userId
* @param appId
*/
private static void createFogDevices(int userId, String appId) {
FogDevice cloud = createFogDevice("cloud", 44800, 40000, 100, 10000, 0, 0.01, 16*103, 16*83.25);
cloud.setParentId(-1);
fogDevices.add(cloud);
FogDevice proxy = createFogDevice("proxy-server", 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333);
proxy.setParentId(cloud.getId());
proxy.setUplinkLatency(100); // latency of connection between proxy server and cloud is 100 ms
fogDevices.add(proxy);
for(int i=0;i<numOfAreas;i++){
addArea(i+"", userId, appId, proxy.getId());
}
}
private static FogDevice addArea(String id, int userId, String appId, int parentId){
FogDevice router = createFogDevice("d-"+id, 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333);
fogDevices.add(router);
router.setUplinkLatency(2); // latency of connection between router and proxy server is 2 ms
for(int i=0;i<numOfCamerasPerArea;i++){
String mobileId = id+"-"+i;
FogDevice camera = addCamera(mobileId, userId, appId, router.getId()); // adding a smart camera to the physical topology. Smart cameras have been modeled as fog devices as well.
camera.setUplinkLatency(2); // latency of connection between camera and router is 2 ms
fogDevices.add(camera);
}
router.setParentId(parentId);
return router;
}
private static FogDevice addCamera(String id, int userId, String appId, int parentId){
FogDevice camera = createFogDevice("m-"+id, 500, 1000, 10000, 10000, 3, 0, 87.53, 82.44);
camera.setParentId(parentId);
Sensor sensor = new Sensor("s-"+id, "CAMERA", userId, appId, new DeterministicDistribution(5)); // inter-transmission time of camera (sensor) follows a deterministic distribution
sensors.add(sensor);
Actuator ptz = new Actuator("ptz-"+id, userId, appId, "PTZ_CONTROL");
actuators.add(ptz);
sensor.setGatewayDeviceId(camera.getId());
sensor.setLatency(1.0); // latency of connection between camera (sensor) and the parent Smart Camera is 1 ms
ptz.setGatewayDeviceId(camera.getId());
ptz.setLatency(1.0); // latency of connection between PTZ Control and the parent Smart Camera is 1 ms
return camera;
}
/**
* Creates a vanilla fog device
* @param nodeName name of the device to be used in simulation
* @param mips MIPS
* @param ram RAM
* @param upBw uplink bandwidth
* @param downBw downlink bandwidth
* @param level hierarchy level of the device
* @param ratePerMips cost rate per MIPS used
* @param busyPower
* @param idlePower
* @return
*/
private static FogDevice createFogDevice(String nodeName, long mips,
int ram, long upBw, long downBw, int level, double ratePerMips, double busyPower, double idlePower) {
List<Pe> peList = new ArrayList<Pe>();
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); // need to store Pe id and MIPS Rating
int hostId = FogUtils.generateEntityId();
long storage = 1000000; // host storage
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
new FogLinearPowerModel(busyPower, idlePower)
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this
// resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are not adding SAN
// devices by now
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
FogDevice fogdevice = null;
try {
fogdevice = new FogDevice(nodeName, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
fogdevice.setLevel(level);
return fogdevice;
}
/**
* Function to create the Intelligent Surveillance application in the DDF model.
* @param appId unique identifier of the application
* @param userId identifier of the user of the application
* @return
*/
@SuppressWarnings({"serial" })
private static Application createApplication(String appId, int userId){
Application application = Application.createApplication(appId, userId);
/*
* Adding modules (vertices) to the application model (directed graph)
*/
application.addAppModule("object_detector", 10);
application.addAppModule("motion_detector", 10);
application.addAppModule("object_tracker", 10);
application.addAppModule("user_interface", 10);
/*
* Connecting the application modules (vertices) in the application model (directed graph) with edges
*/
application.addAppEdge("CAMERA", "motion_detector", 1000, 20000, "CAMERA", Tuple.UP, AppEdge.SENSOR); // adding edge from CAMERA (sensor) to Motion Detector module carrying tuples of type CAMERA
application.addAppEdge("motion_detector", "object_detector", 2000, 2000, "MOTION_VIDEO_STREAM", Tuple.UP, AppEdge.MODULE); // adding edge from Motion Detector to Object Detector module carrying tuples of type MOTION_VIDEO_STREAM
application.addAppEdge("object_detector", "user_interface", 500, 2000, "DETECTED_OBJECT", Tuple.UP, AppEdge.MODULE); // adding edge from Object Detector to User Interface module carrying tuples of type DETECTED_OBJECT
application.addAppEdge("object_detector", "object_tracker", 1000, 100, "OBJECT_LOCATION", Tuple.UP, AppEdge.MODULE); // adding edge from Object Detector to Object Tracker module carrying tuples of type OBJECT_LOCATION
application.addAppEdge("object_tracker", "PTZ_CONTROL", 100, 28, 100, "PTZ_PARAMS", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Object Tracker to PTZ CONTROL (actuator) carrying tuples of type PTZ_PARAMS
/*
* Defining the input-output relationships (represented by selectivity) of the application modules.
*/
application.addTupleMapping("motion_detector", "CAMERA", "MOTION_VIDEO_STREAM", new FractionalSelectivity(1.0)); // 1.0 tuples of type MOTION_VIDEO_STREAM are emitted by Motion Detector module per incoming tuple of type CAMERA
application.addTupleMapping("object_detector", "MOTION_VIDEO_STREAM", "OBJECT_LOCATION", new FractionalSelectivity(1.0)); // 1.0 tuples of type OBJECT_LOCATION are emitted by Object Detector module per incoming tuple of type MOTION_VIDEO_STREAM
application.addTupleMapping("object_detector", "MOTION_VIDEO_STREAM", "DETECTED_OBJECT", new FractionalSelectivity(0.05)); // 0.05 tuples of type MOTION_VIDEO_STREAM are emitted by Object Detector module per incoming tuple of type MOTION_VIDEO_STREAM
/*
* Defining application loops (maybe incomplete loops) to monitor the latency of.
* Here, we add two loops for monitoring : Motion Detector -> Object Detector -> Object Tracker and Object Tracker -> PTZ Control
*/
final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("motion_detector");add("object_detector");add("object_tracker");}});
final AppLoop loop2 = new AppLoop(new ArrayList<String>(){{add("object_tracker");add("PTZ_CONTROL");}});
List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);add(loop2);}};
application.setLoops(loops);
return application;
}
}

View File

@@ -0,0 +1,241 @@
package org.fog.test.perfeval;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.MyApplication;
import org.fog.application.selectivity.FractionalSelectivity;
import org.fog.entities.FogBroker;
import org.fog.entities.FogDeviceCharacteristics;
import org.fog.entities.MyActuator;
import org.fog.entities.MyFogDevice;
import org.fog.entities.MySensor;
import org.fog.entities.Tuple;
import org.fog.placement.ModuleMapping;
import org.fog.placement.MyController;
import org.fog.placement.MyModulePlacement;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.FogLinearPowerModel;
import org.fog.utils.FogUtils;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.DeterministicDistribution;
public class TestApplication {
static List<MyFogDevice> fogDevices = new ArrayList<MyFogDevice>();
static Map<Integer,MyFogDevice> deviceById = new HashMap<Integer,MyFogDevice>();
static List<MySensor> sensors = new ArrayList<MySensor>();
static List<MyActuator> actuators = new ArrayList<MyActuator>();
static List<Integer> idOfEndDevices = new ArrayList<Integer>();
static Map<Integer, Map<String, Double>> deadlineInfo = new HashMap<Integer, Map<String, Double>>();
static Map<Integer, Map<String, Integer>> additionalMipsInfo = new HashMap<Integer, Map<String, Integer>>();
static boolean CLOUD = false;
static int numOfGateways = 2;
static int numOfEndDevPerGateway = 3;
static double sensingInterval = 5;
public static void main(String[] args) {
Log.printLine("Starting TestApplication...");
try {
Log.disable();
int num_user = 1;
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false;
CloudSim.init(num_user, calendar, trace_flag);
String appId = "test_app";
FogBroker broker = new FogBroker("broker");
createFogDevices(broker.getId(), appId);
MyApplication application = createApplication(appId, broker.getId());
application.setUserId(broker.getId());
ModuleMapping moduleMapping = ModuleMapping.createModuleMapping();
moduleMapping.addModuleToDevice("storageModule", "cloud");
for(int i=0;i<idOfEndDevices.size();i++)
{
MyFogDevice fogDevice = deviceById.get(idOfEndDevices.get(i));
moduleMapping.addModuleToDevice("clientModule", fogDevice.getName());
}
MyController controller = new MyController("master-controller", fogDevices, sensors, actuators);
controller.submitApplication(application, 0, new MyModulePlacement(fogDevices, sensors, actuators, application, moduleMapping,"mainModule"));
TimeKeeper.getInstance().setSimulationStartTime(Calendar.getInstance().getTimeInMillis());
CloudSim.startSimulation();
CloudSim.stopSimulation();
Log.printLine("TestApplication finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
private static double getvalue(double min, double max)
{
Random r = new Random();
double randomValue = min + (max - min) * r.nextDouble();
return randomValue;
}
private static int getvalue(int min, int max)
{
Random r = new Random();
int randomValue = min + r.nextInt()%(max - min);
return randomValue;
}
private static void createFogDevices(int userId, String appId) {
MyFogDevice cloud = createFogDevice("cloud", 44800, 40000, 100, 10000, 0, 0.01, 16*103, 16*83.25);
cloud.setParentId(-1);
fogDevices.add(cloud);
deviceById.put(cloud.getId(), cloud);
for(int i=0;i<numOfGateways;i++){
addGw(i+"", userId, appId, cloud.getId());
}
}
private static void addGw(String gwPartialName, int userId, String appId, int parentId){
MyFogDevice gw = createFogDevice("g-"+gwPartialName, 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333);
fogDevices.add(gw);
deviceById.put(gw.getId(), gw);
gw.setParentId(parentId);
gw.setUplinkLatency(4);
for(int i=0;i<numOfEndDevPerGateway;i++){
String endPartialName = gwPartialName+"-"+i;
MyFogDevice end = addEnd(endPartialName, userId, appId, gw.getId());
end.setUplinkLatency(2);
fogDevices.add(end);
deviceById.put(end.getId(), end);
}
}
private static MyFogDevice addEnd(String endPartialName, int userId, String appId, int parentId){
MyFogDevice end = createFogDevice("e-"+endPartialName, 3200, 1000, 10000, 270, 2, 0, 87.53, 82.44);
end.setParentId(parentId);
idOfEndDevices.add(end.getId());
MySensor sensor = new MySensor("s-"+endPartialName, "IoTSensor", userId, appId, new DeterministicDistribution(sensingInterval)); // inter-transmission time of EEG sensor follows a deterministic distribution
sensors.add(sensor);
MyActuator actuator = new MyActuator("a-"+endPartialName, userId, appId, "IoTActuator");
actuators.add(actuator);
sensor.setGatewayDeviceId(end.getId());
sensor.setLatency(6.0); // latency of connection between EEG sensors and the parent Smartphone is 6 ms
actuator.setGatewayDeviceId(end.getId());
actuator.setLatency(1.0); // latency of connection between Display actuator and the parent Smartphone is 1 ms
return end;
}
private static MyFogDevice createFogDevice(String nodeName, long mips,
int ram, long upBw, long downBw, int level, double ratePerMips, double busyPower, double idlePower) {
List<Pe> peList = new ArrayList<Pe>();
peList.add(new Pe(0, new PeProvisionerOverbooking(mips)));
int hostId = FogUtils.generateEntityId();
long storage = 1000000;
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
new FogLinearPowerModel(busyPower, idlePower)
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
String arch = "x86";
String os = "Linux";
String vmm = "Xen";
double time_zone = 10.0;
double cost = 3.0;
double costPerMem = 0.05;
double costPerStorage = 0.001;
double costPerBw = 0.0;
LinkedList<Storage> storageList = new LinkedList<Storage>();
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
MyFogDevice fogdevice = null;
try {
fogdevice = new MyFogDevice(nodeName, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
fogdevice.setLevel(level);
fogdevice.setMips((int) mips);
return fogdevice;
}
@SuppressWarnings({"serial" })
private static MyApplication createApplication(String appId, int userId){
MyApplication application = MyApplication.createApplication(appId, userId);
application.addAppModule("clientModule",10, 1000, 1000, 100);
application.addAppModule("mainModule", 50, 1500, 4000, 800);
application.addAppModule("storageModule", 10, 50, 12000, 100);
application.addAppEdge("IoTSensor", "clientModule", 100, 200, "IoTSensor", Tuple.UP, AppEdge.SENSOR);
application.addAppEdge("clientModule", "mainModule", 6000, 600 , "RawData", Tuple.UP, AppEdge.MODULE);
application.addAppEdge("mainModule", "storageModule", 1000, 300, "StoreData", Tuple.UP, AppEdge.MODULE);
application.addAppEdge("mainModule", "clientModule", 100, 50, "ResultData", Tuple.DOWN, AppEdge.MODULE);
application.addAppEdge("clientModule", "IoTActuator", 100, 50, "Response", Tuple.DOWN, AppEdge.ACTUATOR);
application.addTupleMapping("clientModule", "IoTSensor", "RawData", new FractionalSelectivity(1.0));
application.addTupleMapping("mainModule", "RawData", "ResultData", new FractionalSelectivity(1.0));
application.addTupleMapping("mainModule", "RawData", "StoreData", new FractionalSelectivity(1.0));
application.addTupleMapping("clientModule", "ResultData", "Response", new FractionalSelectivity(1.0));
for(int id:idOfEndDevices)
{
Map<String,Double>moduleDeadline = new HashMap<String,Double>();
moduleDeadline.put("mainModule", getvalue(3.00, 5.00));
Map<String,Integer>moduleAddMips = new HashMap<String,Integer>();
moduleAddMips.put("mainModule", getvalue(0, 500));
deadlineInfo.put(id, moduleDeadline);
additionalMipsInfo.put(id,moduleAddMips);
}
final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("IoTSensor");add("clientModule");add("mainModule");add("clientModule");add("IoTActuator");}});
List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);}};
application.setLoops(loops);
application.setDeadlineInfo(deadlineInfo);
application.setAdditionalMipsInfo(additionalMipsInfo);
return application;
}
}

View File

@@ -0,0 +1,355 @@
package org.fog.test.perfeval;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.application.selectivity.FractionalSelectivity;
import org.fog.entities.Actuator;
import org.fog.entities.FogBroker;
import org.fog.entities.FogDevice;
import org.fog.entities.FogDeviceCharacteristics;
import org.fog.entities.Sensor;
import org.fog.entities.Tuple;
import org.fog.placement.Controller;
import org.fog.placement.ModuleMapping;
import org.fog.placement.ModulePlacementMapping;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.FogLinearPowerModel;
import org.fog.utils.FogUtils;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.DeterministicDistribution;
/**
* Simulation setup for case study 1 - EEG Beam Tractor Game
* @author Harshit Gupta
*
*/
public class TwoApps {
static List<FogDevice> fogDevices = new ArrayList<FogDevice>();
static List<FogDevice> mobiles = new ArrayList<FogDevice>();
static List<Sensor> sensors = new ArrayList<Sensor>();
static List<Actuator> actuators = new ArrayList<Actuator>();
static int numOfDepts = 1;
static int numOfMobilesPerDept = 4;
static double EEG_TRANSMISSION_TIME = 5.1;
//static double EEG_TRANSMISSION_TIME = 10;
public static void main(String[] args) {
Log.printLine("Starting TwoApps...");
try {
Log.disable();
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
CloudSim.init(num_user, calendar, trace_flag);
String appId0 = "vr_game_0";
String appId1 = "vr_game_1";
FogBroker broker0 = new FogBroker("broker_0");
FogBroker broker1 = new FogBroker("broker_1");
Application application0 = createApplication0(appId0, broker0.getId());
Application application1 = createApplication1(appId1, broker1.getId());
application0.setUserId(broker0.getId());
application1.setUserId(broker1.getId());
createFogDevices();
createEdgeDevices0(broker0.getId(), appId0);
createEdgeDevices1(broker1.getId(), appId1);
ModuleMapping moduleMapping_0 = ModuleMapping.createModuleMapping(); // initializing a module mapping
ModuleMapping moduleMapping_1 = ModuleMapping.createModuleMapping(); // initializing a module mapping
moduleMapping_0.addModuleToDevice("connector", "cloud"); // fixing all instances of the Connector module to the Cloud
moduleMapping_0.addModuleToDevice("concentration_calculator", "cloud"); // fixing all instances of the Concentration Calculator module to the Cloud
moduleMapping_1.addModuleToDevice("connector_1", "cloud"); // fixing all instances of the Connector module to the Cloud
moduleMapping_1.addModuleToDevice("concentration_calculator_1", "cloud"); // fixing all instances of the Concentration Calculator module to the Cloud
for(FogDevice device : fogDevices){
if(device.getName().startsWith("m")){
moduleMapping_0.addModuleToDevice("client", device.getName()); // fixing all instances of the Client module to the Smartphones
moduleMapping_1.addModuleToDevice("client_1", device.getName()); // fixing all instances of the Client module to the Smartphones
}
}
Controller controller = new Controller("master-controller", fogDevices, sensors,
actuators);
controller.submitApplication(application0, new ModulePlacementMapping(fogDevices, application0, moduleMapping_0));
controller.submitApplication(application1, 1000, new ModulePlacementMapping(fogDevices, application1, moduleMapping_1));
TimeKeeper.getInstance().setSimulationStartTime(Calendar.getInstance().getTimeInMillis());
CloudSim.startSimulation();
CloudSim.stopSimulation();
Log.printLine("VRGame finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
private static void createEdgeDevices0(int userId, String appId) {
for(FogDevice mobile : mobiles){
String id = mobile.getName();
Sensor eegSensor = new Sensor("s-"+appId+"-"+id, "EEG", userId, appId, new DeterministicDistribution(EEG_TRANSMISSION_TIME)); // inter-transmission time of EEG sensor follows a deterministic distribution
sensors.add(eegSensor);
Actuator display = new Actuator("a-"+appId+"-"+id, userId, appId, "DISPLAY");
actuators.add(display);
eegSensor.setGatewayDeviceId(mobile.getId());
eegSensor.setLatency(6.0); // latency of connection between EEG sensors and the parent Smartphone is 6 ms
display.setGatewayDeviceId(mobile.getId());
display.setLatency(1.0); // latency of connection between Display actuator and the parent Smartphone is 1 ms
}
}
private static void createEdgeDevices1(int userId, String appId) {
for(FogDevice mobile : mobiles){
String id = mobile.getName();
Sensor eegSensor = new Sensor("s-"+appId+"-"+id, "EEG_1", userId, appId, new DeterministicDistribution(EEG_TRANSMISSION_TIME)); // inter-transmission time of EEG sensor follows a deterministic distribution
sensors.add(eegSensor);
Actuator display = new Actuator("a-"+appId+"-"+id, userId, appId, "DISPLAY_1");
actuators.add(display);
eegSensor.setGatewayDeviceId(mobile.getId());
eegSensor.setLatency(6.0); // latency of connection between EEG sensors and the parent Smartphone is 6 ms
display.setGatewayDeviceId(mobile.getId());
display.setLatency(1.0); // latency of connection between Display actuator and the parent Smartphone is 1 ms
}
}
/**
* Creates the fog devices in the physical topology of the simulation.
* @param userId
* @param appId
*/
private static void createFogDevices() {
FogDevice cloud = createFogDevice("cloud", 44800, 40000, 100, 10000, 0, 0.01, 16*103, 16*83.25); // creates the fog device Cloud at the apex of the hierarchy with level=0
cloud.setParentId(-1);
FogDevice proxy = createFogDevice("proxy-server", 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333); // creates the fog device Proxy Server (level=1)
proxy.setParentId(cloud.getId()); // setting Cloud as parent of the Proxy Server
proxy.setUplinkLatency(100); // latency of connection from Proxy Server to the Cloud is 100 ms
fogDevices.add(cloud);
fogDevices.add(proxy);
for(int i=0;i<numOfDepts;i++){
addGw(i+"", proxy.getId()); // adding a fog device for every Gateway in physical topology. The parent of each gateway is the Proxy Server
}
}
private static FogDevice addGw(String id, int parentId){
FogDevice dept = createFogDevice("d-"+id, 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333);
fogDevices.add(dept);
dept.setParentId(parentId);
dept.setUplinkLatency(4); // latency of connection between gateways and proxy server is 4 ms
for(int i=0;i<numOfMobilesPerDept;i++){
String mobileId = id+"-"+i;
FogDevice mobile = addMobile(mobileId, dept.getId()); // adding mobiles to the physical topology. Smartphones have been modeled as fog devices as well.
mobile.setUplinkLatency(2); // latency of connection between the smartphone and proxy server is 4 ms
fogDevices.add(mobile);
}
return dept;
}
private static FogDevice addMobile(String id, int parentId){
FogDevice mobile = createFogDevice("m-"+id, 1000, 1000, 10000, 270, 3, 0, 87.53, 82.44);
mobile.setParentId(parentId);
mobiles.add(mobile);
/*Sensor eegSensor = new Sensor("s-"+id, "EEG", userId, appId, new DeterministicDistribution(EEG_TRANSMISSION_TIME)); // inter-transmission time of EEG sensor follows a deterministic distribution
sensors.add(eegSensor);
Actuator display = new Actuator("a-"+id, userId, appId, "DISPLAY");
actuators.add(display);
eegSensor.setGatewayDeviceId(mobile.getId());
eegSensor.setLatency(6.0); // latency of connection between EEG sensors and the parent Smartphone is 6 ms
display.setGatewayDeviceId(mobile.getId());
display.setLatency(1.0); // latency of connection between Display actuator and the parent Smartphone is 1 ms
*/ return mobile;
}
/**
* Creates a vanilla fog device
* @param nodeName name of the device to be used in simulation
* @param mips MIPS
* @param ram RAM
* @param upBw uplink bandwidth
* @param downBw downlink bandwidth
* @param level hierarchy level of the device
* @param ratePerMips cost rate per MIPS used
* @param busyPower
* @param idlePower
* @return
*/
private static FogDevice createFogDevice(String nodeName, long mips,
int ram, long upBw, long downBw, int level, double ratePerMips, double busyPower, double idlePower) {
List<Pe> peList = new ArrayList<Pe>();
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); // need to store Pe id and MIPS Rating
int hostId = FogUtils.generateEntityId();
long storage = 1000000; // host storage
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
new FogLinearPowerModel(busyPower, idlePower)
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this
// resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are not adding SAN
// devices by now
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
FogDevice fogdevice = null;
try {
fogdevice = new FogDevice(nodeName, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
fogdevice.setLevel(level);
return fogdevice;
}
/**
* Function to create the EEG Tractor Beam game application in the DDF model.
* @param appId unique identifier of the application
* @param userId identifier of the user of the application
* @return
*/
@SuppressWarnings({"serial" })
private static Application createApplication0(String appId, int userId){
Application application = Application.createApplication(appId, userId); // creates an empty application model (empty directed graph)
/*
* Adding modules (vertices) to the application model (directed graph)
*/
application.addAppModule("client", 10); // adding module Client to the application model
application.addAppModule("concentration_calculator", 10); // adding module Concentration Calculator to the application model
application.addAppModule("connector", 10); // adding module Connector to the application model
/*
* Connecting the application modules (vertices) in the application model (directed graph) with edges
*/
if(EEG_TRANSMISSION_TIME==10)
application.addAppEdge("EEG", "client", 2000, 500, "EEG", Tuple.UP, AppEdge.SENSOR); // adding edge from EEG (sensor) to Client module carrying tuples of type EEG
else
application.addAppEdge("EEG", "client", 3000, 500, "EEG", Tuple.UP, AppEdge.SENSOR);
application.addAppEdge("client", "concentration_calculator", 3500, 500, "_SENSOR", Tuple.UP, AppEdge.MODULE); // adding edge from Client to Concentration Calculator module carrying tuples of type _SENSOR
application.addAppEdge("concentration_calculator", "connector", 100, 1000, 1000, "PLAYER_GAME_STATE", Tuple.UP, AppEdge.MODULE); // adding periodic edge (period=1000ms) from Concentration Calculator to Connector module carrying tuples of type PLAYER_GAME_STATE
application.addAppEdge("concentration_calculator", "client", 14, 500, "CONCENTRATION", Tuple.DOWN, AppEdge.MODULE); // adding edge from Concentration Calculator to Client module carrying tuples of type CONCENTRATION
application.addAppEdge("connector", "client", 100, 28, 1000, "GLOBAL_GAME_STATE", Tuple.DOWN, AppEdge.MODULE); // adding periodic edge (period=1000ms) from Connector to Client module carrying tuples of type GLOBAL_GAME_STATE
application.addAppEdge("client", "DISPLAY", 1000, 500, "SELF_STATE_UPDATE", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Client module to Display (actuator) carrying tuples of type SELF_STATE_UPDATE
application.addAppEdge("client", "DISPLAY", 1000, 500, "GLOBAL_STATE_UPDATE", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Client module to Display (actuator) carrying tuples of type GLOBAL_STATE_UPDATE
/*
* Defining the input-output relationships (represented by selectivity) of the application modules.
*/
application.addTupleMapping("client", "EEG", "_SENSOR", new FractionalSelectivity(0.9)); // 0.9 tuples of type _SENSOR are emitted by Client module per incoming tuple of type EEG
application.addTupleMapping("client", "CONCENTRATION", "SELF_STATE_UPDATE", new FractionalSelectivity(1.0)); // 1.0 tuples of type SELF_STATE_UPDATE are emitted by Client module per incoming tuple of type CONCENTRATION
application.addTupleMapping("concentration_calculator", "_SENSOR", "CONCENTRATION", new FractionalSelectivity(1.0)); // 1.0 tuples of type CONCENTRATION are emitted by Concentration Calculator module per incoming tuple of type _SENSOR
application.addTupleMapping("client", "GLOBAL_GAME_STATE", "GLOBAL_STATE_UPDATE", new FractionalSelectivity(1.0)); // 1.0 tuples of type GLOBAL_STATE_UPDATE are emitted by Client module per incoming tuple of type GLOBAL_GAME_STATE
/*
* Defining application loops to monitor the latency of.
* Here, we add only one loop for monitoring : EEG(sensor) -> Client -> Concentration Calculator -> Client -> DISPLAY (actuator)
*/
final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("EEG");add("client");add("concentration_calculator");add("client");add("DISPLAY");}});
List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);}};
application.setLoops(loops);
return application;
}
@SuppressWarnings({"serial" })
private static Application createApplication1(String appId, int userId){
Application application = Application.createApplication(appId, userId); // creates an empty application model (empty directed graph)
/*
* Adding modules (vertices) to the application model (directed graph)
*/
application.addAppModule("client_1", 10); // adding module Client to the application model
application.addAppModule("concentration_calculator_1", 10); // adding module Concentration Calculator to the application model
application.addAppModule("connector_1", 10); // adding module Connector to the application model
/*
* Connecting the application modules (vertices) in the application model (directed graph) with edges
*/
if(EEG_TRANSMISSION_TIME==10)
application.addAppEdge("EEG_1", "client_1", 2000, 500, "EEG_1", Tuple.UP, AppEdge.SENSOR); // adding edge from EEG (sensor) to Client module carrying tuples of type EEG
else
application.addAppEdge("EEG_1", "client_1", 3000, 500, "EEG_1", Tuple.UP, AppEdge.SENSOR);
application.addAppEdge("client_1", "concentration_calculator_1", 3500, 500, "_SENSOR_1", Tuple.UP, AppEdge.MODULE); // adding edge from Client to Concentration Calculator module carrying tuples of type _SENSOR
application.addAppEdge("concentration_calculator_1", "connector_1", 100, 1000, 1000, "PLAYER_GAME_STATE_1", Tuple.UP, AppEdge.MODULE); // adding periodic edge (period=1000ms) from Concentration Calculator to Connector module carrying tuples of type PLAYER_GAME_STATE
application.addAppEdge("concentration_calculator_1", "client_1", 14, 500, "CONCENTRATION_1", Tuple.DOWN, AppEdge.MODULE); // adding edge from Concentration Calculator to Client module carrying tuples of type CONCENTRATION
application.addAppEdge("connector_1", "client_1", 100, 28, 1000, "GLOBAL_GAME_STATE_1", Tuple.DOWN, AppEdge.MODULE); // adding periodic edge (period=1000ms) from Connector to Client module carrying tuples of type GLOBAL_GAME_STATE
application.addAppEdge("client_1", "DISPLAY_1", 1000, 500, "SELF_STATE_UPDATE_1", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Client module to Display (actuator) carrying tuples of type SELF_STATE_UPDATE
application.addAppEdge("client_1", "DISPLAY_1", 1000, 500, "GLOBAL_STATE_UPDATE_1", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Client module to Display (actuator) carrying tuples of type GLOBAL_STATE_UPDATE
/*
* Defining the input-output relationships (represented by selectivity) of the application modules.
*/
application.addTupleMapping("client_1", "EEG_1", "_SENSOR_1", new FractionalSelectivity(0.9)); // 0.9 tuples of type _SENSOR are emitted by Client module per incoming tuple of type EEG
application.addTupleMapping("client_1", "CONCENTRATION_1", "SELF_STATE_UPDATE_1", new FractionalSelectivity(1.0)); // 1.0 tuples of type SELF_STATE_UPDATE are emitted by Client module per incoming tuple of type CONCENTRATION
application.addTupleMapping("concentration_calculator_1", "_SENSOR_1", "CONCENTRATION_1", new FractionalSelectivity(1.0)); // 1.0 tuples of type CONCENTRATION are emitted by Concentration Calculator module per incoming tuple of type _SENSOR
application.addTupleMapping("client_1", "GLOBAL_GAME_STATE_1", "GLOBAL_STATE_UPDATE_1", new FractionalSelectivity(1.0)); // 1.0 tuples of type GLOBAL_STATE_UPDATE are emitted by Client module per incoming tuple of type GLOBAL_GAME_STATE
/*
* Defining application loops to monitor the latency of.
* Here, we add only one loop for monitoring : EEG(sensor) -> Client -> Concentration Calculator -> Client -> DISPLAY (actuator)
*/
final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("EEG_1");add("client_1");add("concentration_calculator_1");add("client_1");add("DISPLAY_1");}});
List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);}};
application.setLoops(loops);
return application;
}
}

View File

@@ -0,0 +1,283 @@
package org.fog.test.perfeval;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.application.AppEdge;
import org.fog.application.AppLoop;
import org.fog.application.Application;
import org.fog.application.selectivity.FractionalSelectivity;
import org.fog.entities.Actuator;
import org.fog.entities.FogBroker;
import org.fog.entities.FogDevice;
import org.fog.entities.FogDeviceCharacteristics;
import org.fog.entities.Sensor;
import org.fog.entities.Tuple;
import org.fog.placement.Controller;
import org.fog.placement.ModuleMapping;
import org.fog.placement.ModulePlacementEdgewards;
import org.fog.placement.ModulePlacementMapping;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.FogLinearPowerModel;
import org.fog.utils.FogUtils;
import org.fog.utils.TimeKeeper;
import org.fog.utils.distribution.DeterministicDistribution;
/**
* Simulation setup for case study 1 - EEG Beam Tractor Game
* @author Harshit Gupta
*
*/
public class VRGameFog {
static List<FogDevice> fogDevices = new ArrayList<FogDevice>();
static List<Sensor> sensors = new ArrayList<Sensor>();
static List<Actuator> actuators = new ArrayList<Actuator>();
static boolean CLOUD = false;
static int numOfDepts = 4;
static int numOfMobilesPerDept = 6;
static double EEG_TRANSMISSION_TIME = 5.1;
//static double EEG_TRANSMISSION_TIME = 10;
public static void main(String[] args) {
Log.printLine("Starting VRGame...");
try {
Log.disable();
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
CloudSim.init(num_user, calendar, trace_flag);
String appId = "vr_game"; // identifier of the application
FogBroker broker = new FogBroker("broker");
Application application = createApplication(appId, broker.getId());
application.setUserId(broker.getId());
createFogDevices(broker.getId(), appId);
ModuleMapping moduleMapping = ModuleMapping.createModuleMapping(); // initializing a module mapping
if(CLOUD){
// if the mode of deployment is cloud-based
/*moduleMapping.addModuleToDevice("connector", "cloud", numOfDepts*numOfMobilesPerDept); // fixing all instances of the Connector module to the Cloud
moduleMapping.addModuleToDevice("concentration_calculator", "cloud", numOfDepts*numOfMobilesPerDept); // fixing all instances of the Concentration Calculator module to the Cloud
*/ moduleMapping.addModuleToDevice("connector", "cloud"); // fixing all instances of the Connector module to the Cloud
moduleMapping.addModuleToDevice("concentration_calculator", "cloud"); // fixing all instances of the Concentration Calculator module to the Cloud
for(FogDevice device : fogDevices){
if(device.getName().startsWith("m")){
//moduleMapping.addModuleToDevice("client", device.getName(), 1); // fixing all instances of the Client module to the Smartphones
moduleMapping.addModuleToDevice("client", device.getName()); // fixing all instances of the Client module to the Smartphones
}
}
}else{
// if the mode of deployment is cloud-based
//moduleMapping.addModuleToDevice("connector", "cloud", numOfDepts*numOfMobilesPerDept); // fixing all instances of the Connector module to the Cloud
moduleMapping.addModuleToDevice("connector", "cloud"); // fixing all instances of the Connector module to the Cloud
// rest of the modules will be placed by the Edge-ward placement policy
}
Controller controller = new Controller("master-controller", fogDevices, sensors,
actuators);
controller.submitApplication(application, 0,
(CLOUD)?(new ModulePlacementMapping(fogDevices, application, moduleMapping))
:(new ModulePlacementEdgewards(fogDevices, sensors, actuators, application, moduleMapping)));
TimeKeeper.getInstance().setSimulationStartTime(Calendar.getInstance().getTimeInMillis());
CloudSim.startSimulation();
CloudSim.stopSimulation();
Log.printLine("VRGame finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
/**
* Creates the fog devices in the physical topology of the simulation.
* @param userId
* @param appId
*/
private static void createFogDevices(int userId, String appId) {
FogDevice cloud = createFogDevice("cloud", 44800, 40000, 100, 10000, 0, 0.01, 16*103, 16*83.25); // creates the fog device Cloud at the apex of the hierarchy with level=0
cloud.setParentId(-1);
FogDevice proxy = createFogDevice("proxy-server", 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333); // creates the fog device Proxy Server (level=1)
proxy.setParentId(cloud.getId()); // setting Cloud as parent of the Proxy Server
proxy.setUplinkLatency(100); // latency of connection from Proxy Server to the Cloud is 100 ms
fogDevices.add(cloud);
fogDevices.add(proxy);
for(int i=0;i<numOfDepts;i++){
addGw(i+"", userId, appId, proxy.getId()); // adding a fog device for every Gateway in physical topology. The parent of each gateway is the Proxy Server
}
}
private static FogDevice addGw(String id, int userId, String appId, int parentId){
FogDevice dept = createFogDevice("d-"+id, 2800, 4000, 10000, 10000, 1, 0.0, 107.339, 83.4333);
fogDevices.add(dept);
dept.setParentId(parentId);
dept.setUplinkLatency(4); // latency of connection between gateways and proxy server is 4 ms
for(int i=0;i<numOfMobilesPerDept;i++){
String mobileId = id+"-"+i;
FogDevice mobile = addMobile(mobileId, userId, appId, dept.getId()); // adding mobiles to the physical topology. Smartphones have been modeled as fog devices as well.
mobile.setUplinkLatency(2); // latency of connection between the smartphone and proxy server is 4 ms
fogDevices.add(mobile);
}
return dept;
}
private static FogDevice addMobile(String id, int userId, String appId, int parentId){
FogDevice mobile = createFogDevice("m-"+id, 1000, 1000, 10000, 270, 3, 0, 87.53, 82.44);
mobile.setParentId(parentId);
Sensor eegSensor = new Sensor("s-"+id, "EEG", userId, appId, new DeterministicDistribution(EEG_TRANSMISSION_TIME)); // inter-transmission time of EEG sensor follows a deterministic distribution
sensors.add(eegSensor);
Actuator display = new Actuator("a-"+id, userId, appId, "DISPLAY");
actuators.add(display);
eegSensor.setGatewayDeviceId(mobile.getId());
eegSensor.setLatency(6.0); // latency of connection between EEG sensors and the parent Smartphone is 6 ms
display.setGatewayDeviceId(mobile.getId());
display.setLatency(1.0); // latency of connection between Display actuator and the parent Smartphone is 1 ms
return mobile;
}
/**
* Creates a vanilla fog device
* @param nodeName name of the device to be used in simulation
* @param mips MIPS
* @param ram RAM
* @param upBw uplink bandwidth
* @param downBw downlink bandwidth
* @param level hierarchy level of the device
* @param ratePerMips cost rate per MIPS used
* @param busyPower
* @param idlePower
* @return
*/
private static FogDevice createFogDevice(String nodeName, long mips,
int ram, long upBw, long downBw, int level, double ratePerMips, double busyPower, double idlePower) {
List<Pe> peList = new ArrayList<Pe>();
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); // need to store Pe id and MIPS Rating
int hostId = FogUtils.generateEntityId();
long storage = 1000000; // host storage
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
new FogLinearPowerModel(busyPower, idlePower)
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this
// resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are not adding SAN
// devices by now
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
FogDevice fogdevice = null;
try {
fogdevice = new FogDevice(nodeName, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
fogdevice.setLevel(level);
return fogdevice;
}
/**
* Function to create the EEG Tractor Beam game application in the DDF model.
* @param appId unique identifier of the application
* @param userId identifier of the user of the application
* @return
*/
@SuppressWarnings({"serial" })
private static Application createApplication(String appId, int userId){
Application application = Application.createApplication(appId, userId); // creates an empty application model (empty directed graph)
/*
* Adding modules (vertices) to the application model (directed graph)
*/
application.addAppModule("client", 10); // adding module Client to the application model
application.addAppModule("concentration_calculator", 10); // adding module Concentration Calculator to the application model
application.addAppModule("connector", 10); // adding module Connector to the application model
/*
* Connecting the application modules (vertices) in the application model (directed graph) with edges
*/
if(EEG_TRANSMISSION_TIME==10)
application.addAppEdge("EEG", "client", 2000, 500, "EEG", Tuple.UP, AppEdge.SENSOR); // adding edge from EEG (sensor) to Client module carrying tuples of type EEG
else
application.addAppEdge("EEG", "client", 3000, 500, "EEG", Tuple.UP, AppEdge.SENSOR);
application.addAppEdge("client", "concentration_calculator", 3500, 500, "_SENSOR", Tuple.UP, AppEdge.MODULE); // adding edge from Client to Concentration Calculator module carrying tuples of type _SENSOR
application.addAppEdge("concentration_calculator", "connector", 100, 1000, 1000, "PLAYER_GAME_STATE", Tuple.UP, AppEdge.MODULE); // adding periodic edge (period=1000ms) from Concentration Calculator to Connector module carrying tuples of type PLAYER_GAME_STATE
application.addAppEdge("concentration_calculator", "client", 14, 500, "CONCENTRATION", Tuple.DOWN, AppEdge.MODULE); // adding edge from Concentration Calculator to Client module carrying tuples of type CONCENTRATION
application.addAppEdge("connector", "client", 100, 28, 1000, "GLOBAL_GAME_STATE", Tuple.DOWN, AppEdge.MODULE); // adding periodic edge (period=1000ms) from Connector to Client module carrying tuples of type GLOBAL_GAME_STATE
application.addAppEdge("client", "DISPLAY", 1000, 500, "SELF_STATE_UPDATE", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Client module to Display (actuator) carrying tuples of type SELF_STATE_UPDATE
application.addAppEdge("client", "DISPLAY", 1000, 500, "GLOBAL_STATE_UPDATE", Tuple.DOWN, AppEdge.ACTUATOR); // adding edge from Client module to Display (actuator) carrying tuples of type GLOBAL_STATE_UPDATE
/*
* Defining the input-output relationships (represented by selectivity) of the application modules.
*/
application.addTupleMapping("client", "EEG", "_SENSOR", new FractionalSelectivity(0.9)); // 0.9 tuples of type _SENSOR are emitted by Client module per incoming tuple of type EEG
application.addTupleMapping("client", "CONCENTRATION", "SELF_STATE_UPDATE", new FractionalSelectivity(1.0)); // 1.0 tuples of type SELF_STATE_UPDATE are emitted by Client module per incoming tuple of type CONCENTRATION
application.addTupleMapping("concentration_calculator", "_SENSOR", "CONCENTRATION", new FractionalSelectivity(1.0)); // 1.0 tuples of type CONCENTRATION are emitted by Concentration Calculator module per incoming tuple of type _SENSOR
application.addTupleMapping("client", "GLOBAL_GAME_STATE", "GLOBAL_STATE_UPDATE", new FractionalSelectivity(1.0)); // 1.0 tuples of type GLOBAL_STATE_UPDATE are emitted by Client module per incoming tuple of type GLOBAL_GAME_STATE
/*
* Defining application loops to monitor the latency of.
* Here, we add only one loop for monitoring : EEG(sensor) -> Client -> Concentration Calculator -> Client -> DISPLAY (actuator)
*/
final AppLoop loop1 = new AppLoop(new ArrayList<String>(){{add("EEG");add("client");add("concentration_calculator");add("client");add("DISPLAY");}});
List<AppLoop> loops = new ArrayList<AppLoop>(){{add(loop1);}};
application.setLoops(loops);
return application;
}
}

View File

@@ -0,0 +1,46 @@
package org.fog.utils;
public class CanBeSentResult {
private double cpuLoad;
private double nwLoad;
private boolean canBeSent;
public CanBeSentResult(double cpuLoad, double nwLoad, boolean canBeSent){
this.cpuLoad = cpuLoad;
this.nwLoad = nwLoad;
this.canBeSent = canBeSent;
}
public CanBeSentResult() {
// TODO Auto-generated constructor stub
}
public double getCpuLoad() {
return cpuLoad;
}
public void setCpuLoad(double cpuLoad) {
this.cpuLoad = cpuLoad;
}
public double getNwLoad() {
return nwLoad;
}
public void setNwLoad(double nwLoad) {
this.nwLoad = nwLoad;
}
public boolean isCanBeSent() {
return canBeSent;
}
public void setCanBeSent(boolean canBeSent) {
this.canBeSent = canBeSent;
}
}

View File

@@ -0,0 +1,16 @@
package org.fog.utils;
public class Config {
public static final double RESOURCE_MGMT_INTERVAL = 100;
public static int MAX_SIMULATION_TIME = 300;
public static int RESOURCE_MANAGE_INTERVAL = 100;
public static String FOG_DEVICE_ARCH = "x86";
public static String FOG_DEVICE_OS = "Linux";
public static String FOG_DEVICE_VMM = "Xen";
public static double FOG_DEVICE_TIMEZONE = 10.0;
public static double FOG_DEVICE_COST = 3.0;
public static double FOG_DEVICE_COST_PER_MEMORY = 0.05;
public static double FOG_DEVICE_COST_PER_STORAGE = 0.001;
public static double FOG_DEVICE_COST_PER_BW = 0.0;
}

View File

@@ -0,0 +1,73 @@
package org.fog.utils;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.power.models.PowerModelLinear;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.entities.FogDevice;
import org.fog.entities.FogDeviceCharacteristics;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
public class FogEntityFactory {
public static FogDevice createFogDevice(String name, int mips, double uplinkBandwidth, double downlinkBandwidth, double latency, double ratePerMips) {
List<Pe> peList = new ArrayList<Pe>();
peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); // need to store Pe id and MIPS Rating
int hostId = FogUtils.generateEntityId();
int ram = 2048; // host memory (MB)
long storage = 1000000; // host storage
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
new PowerModelLinear(100, 40)
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this
// resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are not adding SAN
// devices by now
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
FogDevice fogdevice = null;
try {
fogdevice = new FogDevice(name, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, uplinkBandwidth, downlinkBandwidth, latency, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
return fogdevice;
}
}

View File

@@ -0,0 +1,31 @@
package org.fog.utils;
public class FogEvents {
private static final int BASE = 50;
public static final int TUPLE_ARRIVAL = BASE + 1;
public static final int LAUNCH_MODULE = BASE + 2;
public static final int RELEASE_OPERATOR = BASE + 3;
public static final int SENSOR_JOINED = BASE + 4;
public static final int TUPLE_ACK = BASE + 5;
public static final int APP_SUBMIT = BASE + 6;
public static final int CALCULATE_INPUT_RATE = BASE + 7;
public static final int CALCULATE_UTIL = BASE + 8;
public static final int UPDATE_RESOURCE_USAGE = BASE + 9;
//public static final int UPDATE_TUPLE_QUEUE = BASE + 10;
public static final int TUPLE_FINISHED = BASE + 11;
public static final int ACTIVE_APP_UPDATE = BASE+12;
public static final int CONTROLLER_RESOURCE_MANAGE = BASE+13;
public static final int ADAPTIVE_OPERATOR_REPLACEMENT = BASE+14;
public static final int GET_RESOURCE_USAGE = BASE+15;
public static final int RESOURCE_USAGE = BASE+16;
public static final int CONTROL_MSG_ARRIVAL = BASE + 17;
public static final int UPDATE_NORTH_TUPLE_QUEUE = BASE+18;
public static final int UPDATE_SOUTH_TUPLE_QUEUE = BASE+19;
public static final int ACTUATOR_JOINED = BASE+20;
public static final int STOP_SIMULATION = BASE + 21;
public static final int SEND_PERIODIC_TUPLE = BASE+22;
public static final int LAUNCH_MODULE_INSTANCE = BASE+23;
public static final int RESOURCE_MGMT = BASE+24;
public static final int INITIALIZE_SENSOR = BASE+24;
public static final int EMIT_TUPLE = BASE+25;
}

View File

@@ -0,0 +1,110 @@
package org.fog.utils;
import org.cloudbus.cloudsim.power.models.PowerModel;
/**
* The Class PowerModelLinear.
*
* If you are using any algorithms, policies or workload included in the power package, please cite
* the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic Algorithms and Adaptive
* Heuristics for Energy and Performance Efficient Dynamic Consolidation of Virtual Machines in
* Cloud Data Centers", Concurrency and Computation: Practice and Experience (CCPE), Volume 24,
* Issue 13, Pages: 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
*
* @author Anton Beloglazov
* @since CloudSim Toolkit 2.0
*/
public class FogLinearPowerModel implements PowerModel {
/** The max power. */
private double maxPower;
/** The constant. */
private double constant;
/** The static power. */
private double staticPower;
/**
* Instantiates a new linear power model.
*
* @param maxPower the max power
* @param staticPower the static power
*/
public FogLinearPowerModel(double maxPower, double staticPower) {
setMaxPower(maxPower);
setStaticPower(staticPower);
setConstant((maxPower - getStaticPower()) / 100);
}
/*
* (non-Javadoc)
* @see cloudsim.power.PowerModel#getPower(double)
*/
@Override
public double getPower(double utilization) throws IllegalArgumentException {
if (utilization < 0 || utilization > 1) {
throw new IllegalArgumentException("Utilization value must be between 0 and 1");
}
return getStaticPower() + getConstant() * utilization * 100;
}
/**
* Gets the max power.
*
* @return the max power
*/
protected double getMaxPower() {
return maxPower;
}
/**
* Sets the max power.
*
* @param maxPower the new max power
*/
protected void setMaxPower(double maxPower) {
this.maxPower = maxPower;
}
/**
* Gets the constant.
*
* @return the constant
*/
protected double getConstant() {
return constant;
}
/**
* Sets the constant.
*
* @param constant the new constant
*/
protected void setConstant(double constant) {
this.constant = constant;
}
/**
* Gets the static power.
*
* @return the static power
*/
protected double getStaticPower() {
return staticPower;
}
/**
* Sets the static power.
*
* @param staticPower the new static power
*/
protected void setStaticPower(double staticPower) {
this.staticPower = staticPower;
}
}

View File

@@ -0,0 +1,33 @@
package org.fog.utils;
import java.util.HashMap;
import java.util.Map;
public class FogUtils {
private static int TUPLE_ID = 1;
private static int ENTITY_ID = 1;
private static int ACTUAL_TUPLE_ID = 1;
public static int generateTupleId(){
return TUPLE_ID++;
}
public static String getSensorTypeFromSensorName(String sensorName){
return sensorName.substring(sensorName.indexOf('-')+1, sensorName.lastIndexOf('-'));
}
public static int generateEntityId(){
return ENTITY_ID++;
}
public static int generateActualTupleId(){
return ACTUAL_TUPLE_ID++;
}
public static int USER_ID = 1;
//public static int MAX = 10000000;
public static int MAX = 10000000;
public static Map<String, GeoCoverage> appIdToGeoCoverageMap = new HashMap<String, GeoCoverage>();
}

View File

@@ -0,0 +1,56 @@
package org.fog.utils;
public class GeoCoverage {
private double lat_l;
private double lat_u;
private double long_l;
private double long_u;
public GeoCoverage(double lat_l, double lat_u, double long_l, double long_u){
this.lat_l = lat_l;
this.lat_u = lat_u;
this.long_l = long_l;
this.long_u = long_u;
}
public boolean covers(GeoCoverage geo){
if(this.lat_l <= geo.lat_l && this.lat_u >= geo.lat_u && this.long_l <= geo.long_l && this.long_u >= geo.long_u)
return true;
return false;
}
public double getLat_l() {
return lat_l;
}
public void setLat_l(double lat_l) {
this.lat_l = lat_l;
}
public double getLat_u() {
return lat_u;
}
public void setLat_u(double lat_u) {
this.lat_u = lat_u;
}
public double getLong_l() {
return long_l;
}
public void setLong_l(double long_l) {
this.long_l = long_l;
}
public double getLong_u() {
return long_u;
}
public void setLong_u(double long_u) {
this.long_u = long_u;
}
}

View File

@@ -0,0 +1,27 @@
package org.fog.utils;
public class GeoLocation {
private double latitude;
private double longitude;
public GeoLocation(double latitude, double longitude){
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}

View File

@@ -0,0 +1,244 @@
package org.fog.utils;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.power.PowerHost;
import org.cloudbus.cloudsim.power.models.PowerModelLinear;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
import org.cloudbus.cloudsim.sdn.overbooking.BwProvisionerOverbooking;
import org.cloudbus.cloudsim.sdn.overbooking.PeProvisionerOverbooking;
import org.fog.entities.Actuator;
import org.fog.entities.FogDevice;
import org.fog.entities.FogDeviceCharacteristics;
import org.fog.entities.PhysicalTopology;
import org.fog.entities.Sensor;
import org.fog.policy.AppModuleAllocationPolicy;
import org.fog.scheduler.StreamOperatorScheduler;
import org.fog.utils.distribution.DeterministicDistribution;
import org.fog.utils.distribution.Distribution;
import org.fog.utils.distribution.NormalDistribution;
import org.fog.utils.distribution.UniformDistribution;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonToTopology {
private static List<FogDevice> fogDevices = new ArrayList<FogDevice>();
private static List<Sensor> sensors = new ArrayList<Sensor>();
private static List<Actuator> actuators = new ArrayList<Actuator>();
private static boolean isFogDevice(String name){
for(FogDevice fogDevice : fogDevices){
if(fogDevice.getName().equalsIgnoreCase(name))
return true;
}
return false;
}
private static FogDevice getFogDevice(String name){
for(FogDevice fogDevice : fogDevices){
if(fogDevice.getName().equalsIgnoreCase(name))
return fogDevice;
}
return null;
}
private static boolean isActuator(String name){
for(Actuator actuator : actuators){
if(actuator.getName().equalsIgnoreCase(name))
return true;
}
return false;
}
private static Actuator getActuator(String name){
for(Actuator actuator : actuators){
if(actuator.getName().equalsIgnoreCase(name))
return actuator;
}
return null;
}
private static boolean isSensor(String name){
for(Sensor sensor : sensors){
if(sensor.getName().equalsIgnoreCase(name))
return true;
}
return false;
}
private static Sensor getSensor(String name){
for(Sensor sensor : sensors){
if(sensor.getName().equalsIgnoreCase(name))
return sensor;
}
return null;
}
public static PhysicalTopology getPhysicalTopology(int userId, String appId, String physicalTopologyFile) throws Exception{
fogDevices = new ArrayList<FogDevice>();
sensors = new ArrayList<Sensor>();
actuators = new ArrayList<Actuator>();
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(physicalTopologyFile));
JSONArray nodes = (JSONArray) doc.get("nodes");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter =nodes.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String nodeType = (String) node.get("type");
String nodeName = (String) node.get("name");
if(nodeType.equalsIgnoreCase("FOG_DEVICE")){
long mips = (Long) node.get("mips");
int ram = new BigDecimal((Long)node.get("ram")).intValueExact();
long upBw = new BigDecimal((Long)node.get("upBw")).intValueExact();
long downBw = new BigDecimal((Long)node.get("downBw")).intValueExact();
int level = new BigDecimal((Long)node.get("level")).intValue();
double ratePerMips = new BigDecimal((Double)node.get("ratePerMips")).doubleValue();
FogDevice fogDevice = createFogDevice(nodeName, mips, ram, upBw, downBw, level, ratePerMips);
fogDevice.setParentId(-1);
fogDevices.add(fogDevice);
} else if(nodeType.equals("SENSOR")){
String sensorType = node.get("sensorType").toString();
int distType = new BigDecimal((Long)node.get("distribution")).intValue();
Distribution distribution = null;
if(distType == Distribution.DETERMINISTIC)
distribution = new DeterministicDistribution(new BigDecimal((Double)node.get("value")).doubleValue());
else if(distType == Distribution.NORMAL){
distribution = new NormalDistribution(new BigDecimal((Double)node.get("mean")).doubleValue(),
new BigDecimal((Double)node.get("stdDev")).doubleValue());
} else if(distType == Distribution.UNIFORM){
distribution = new UniformDistribution(new BigDecimal((Double)node.get("min")).doubleValue(),
new BigDecimal((Double)node.get("max")).doubleValue());
}
System.out.println("Sensor type : "+sensorType);
sensors.add(new Sensor(nodeName, sensorType, userId, appId, distribution));
} else if(nodeType.equals("ACTUATOR")){
String actuatorType = node.get("actuatorType").toString();
actuators.add(new Actuator(nodeName, userId, appId, actuatorType));
}
}
JSONArray links = (JSONArray) doc.get("links");
@SuppressWarnings("unchecked")
Iterator<JSONObject> linksIter =links.iterator();
while(linksIter.hasNext()){
JSONObject link = linksIter.next();
String src = (String) link.get("source");
String dst = (String) link.get("destination");
double lat = (Double) link.get("latency");
connectEntities(src, dst, lat);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PhysicalTopology physicalTopology = new PhysicalTopology();
physicalTopology.setFogDevices(fogDevices);
physicalTopology.setActuators(actuators);
physicalTopology.setSensors(sensors);
return physicalTopology;
}
private static FogDevice createFogDevice(String nodeName, long mips,
int ram, long upBw, long downBw, int level, double ratePerMips) {
List<Pe> peList = new ArrayList<Pe>();
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerOverbooking(mips))); // need to store Pe id and MIPS Rating
int hostId = FogUtils.generateEntityId();
long storage = 1000000; // host storage
int bw = 10000;
PowerHost host = new PowerHost(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerOverbooking(bw),
storage,
peList,
new StreamOperatorScheduler(peList),
new PowerModelLinear(107.339, 83.4333)
);
List<Host> hostList = new ArrayList<Host>();
hostList.add(host);
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this
// resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are not adding SAN
// devices by now
FogDeviceCharacteristics characteristics = new FogDeviceCharacteristics(
arch, os, vmm, host, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
FogDevice fogdevice = null;
try {
fogdevice = new FogDevice(nodeName, characteristics,
new AppModuleAllocationPolicy(hostList), storageList, 10, upBw, downBw, 0, ratePerMips);
} catch (Exception e) {
e.printStackTrace();
}
fogdevice.setLevel(level);
return fogdevice;
}
private static void connectEntities(String src, String dst, double lat) {
if(isFogDevice(src) && isFogDevice(dst)){
FogDevice srcDev = getFogDevice(src);
FogDevice destDev = getFogDevice(dst);
FogDevice southernDev = (srcDev.getLevel() > destDev.getLevel())?srcDev:destDev;
FogDevice northernDev = (srcDev.getLevel() > destDev.getLevel())?destDev:srcDev;
southernDev.setUplinkLatency(lat);
southernDev.setParentId(northernDev.getId());
} else if(isFogDevice(src) && isSensor(dst)){
FogDevice srcDev = getFogDevice(src);
Sensor sensor = getSensor(dst);
sensor.setLatency(lat);
sensor.setGatewayDeviceId(srcDev.getId());
} else if(isSensor(src) && isFogDevice(dst)){
FogDevice fogDevice = getFogDevice(dst);
Sensor sensor = getSensor(src);
sensor.setLatency(lat);
sensor.setGatewayDeviceId(fogDevice.getId());
} else if(isFogDevice(src) && isActuator(dst)){
FogDevice fogDevice = getFogDevice(src);
Actuator actuator = getActuator(dst);
actuator.setLatency(lat);
actuator.setGatewayDeviceId(fogDevice.getId());
} else if(isActuator(src) && isFogDevice(dst)){
FogDevice fogDevice = getFogDevice(dst);
Actuator actuator = getActuator(src);
actuator.setLatency(lat);
actuator.setGatewayDeviceId(fogDevice.getId());
}
}
}

View File

@@ -0,0 +1,34 @@
package org.fog.utils;
import java.text.DecimalFormat;
import org.cloudbus.cloudsim.core.CloudSim;
public class Logger {
public static final int ERROR = 1;
public static final int DEBUG = 0;
public static int LOG_LEVEL = Logger.DEBUG;
private static DecimalFormat df = new DecimalFormat("#.00");
public static boolean ENABLED = false;;
public static void setLogLevel(int level){
Logger.LOG_LEVEL = level;
}
public static void debug(String name, String message){
if(!ENABLED)
return;
if(Logger.LOG_LEVEL <= Logger.DEBUG)
System.out.println(df.format(CloudSim.clock())+" : "+name+" : "+message);
}
public static void error(String name, String message){
if(!ENABLED)
return;
if(Logger.LOG_LEVEL <= Logger.ERROR)
System.out.println(df.format(CloudSim.clock())+" : "+name+" : "+message);
}
}

View File

@@ -0,0 +1,28 @@
package org.fog.utils;
import org.fog.application.AppModule;
public class ModuleLaunchConfig {
private AppModule module;
private int instanceCount;
public ModuleLaunchConfig(AppModule module, int instanceCount){
setModule(module);
setInstanceCount(instanceCount);
}
public AppModule getModule() {
return module;
}
public void setModule(AppModule module) {
this.module = module;
}
public int getInstanceCount() {
return instanceCount;
}
public void setInstanceCount(int instanceCount) {
this.instanceCount = instanceCount;
}
}

View File

@@ -0,0 +1,14 @@
package org.fog.utils;
public class NetworkUsageMonitor {
private static double networkUsage = 0.0;
public static void sendingTuple(double latency, double tupleNwSize){
networkUsage += latency*tupleNwSize;
}
public static double getNetworkUsage(){
return networkUsage;
}
}

View File

@@ -0,0 +1,34 @@
package org.fog.utils;
public class OperatorEdge {
private String src;
private String dst;
private double selectivity;
public OperatorEdge(String src, String dst, double selectivity){
this.src = src;
this.dst = dst;
this.selectivity = selectivity;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDst() {
return dst;
}
public void setDst(String dst) {
this.dst = dst;
}
public double getSelectivity() {
return selectivity;
}
public void setSelectivity(double selectivity) {
this.selectivity = selectivity;
}
}

View File

@@ -0,0 +1,13 @@
package org.fog.utils;
import java.util.Comparator;
import java.util.List;
public class OperatorSetComparator implements Comparator<List<String>>{
@Override
public int compare(List<String> arg0, List<String> arg1) {
return (arg1.size() - arg0.size());
}
}

View File

@@ -0,0 +1,43 @@
package org.fog.utils;
public class ResourceUsageDetails {
private double mips;
private double uplinkBandwidth;
private double cpuTrafficIntensity;
private double nwTrafficIntensity;
public ResourceUsageDetails(double mips, double uplinkBandwidth,
double cpuTrafficIntensity, double nwTrafficIntensity) {
super();
this.mips = mips;
this.uplinkBandwidth = uplinkBandwidth;
this.cpuTrafficIntensity = cpuTrafficIntensity;
this.nwTrafficIntensity = nwTrafficIntensity;
}
public double getMips() {
return mips;
}
public void setMips(double mips) {
this.mips = mips;
}
public double getUplinkBandwidth() {
return uplinkBandwidth;
}
public void setUplinkBandwidth(double uplinkBandwidth) {
this.uplinkBandwidth = uplinkBandwidth;
}
public double getCpuTrafficIntensity() {
return cpuTrafficIntensity;
}
public void setCpuTrafficIntensity(double cpuTrafficIntensity) {
this.cpuTrafficIntensity = cpuTrafficIntensity;
}
public double getNwTrafficIntensity() {
return nwTrafficIntensity;
}
public void setNwTrafficIntensity(double nwTrafficIntensity) {
this.nwTrafficIntensity = nwTrafficIntensity;
}
}

View File

@@ -0,0 +1,153 @@
package org.fog.utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cloudbus.cloudsim.core.CloudSim;
import org.fog.entities.Tuple;
public class TimeKeeper {
private static TimeKeeper instance;
private long simulationStartTime;
private int count;
private Map<Integer, Double> emitTimes;
private Map<Integer, Double> endTimes;
private Map<Integer, List<Integer>> loopIdToTupleIds;
private Map<Integer, Double> tupleIdToCpuStartTime;
private Map<String, Double> tupleTypeToAverageCpuTime;
private Map<String, Integer> tupleTypeToExecutedTupleCount;
private Map<Integer, Double> loopIdToCurrentAverage;
private Map<Integer, Integer> loopIdToCurrentNum;
public static TimeKeeper getInstance(){
if(instance == null)
instance = new TimeKeeper();
return instance;
}
public int getUniqueId(){
return count++;
}
public void tupleStartedExecution(Tuple tuple){
tupleIdToCpuStartTime.put(tuple.getCloudletId(), CloudSim.clock());
}
public void tupleEndedExecution(Tuple tuple){
if(!tupleIdToCpuStartTime.containsKey(tuple.getCloudletId()))
return;
double executionTime = CloudSim.clock() - tupleIdToCpuStartTime.get(tuple.getCloudletId());
if(!tupleTypeToAverageCpuTime.containsKey(tuple.getTupleType())){
tupleTypeToAverageCpuTime.put(tuple.getTupleType(), executionTime);
tupleTypeToExecutedTupleCount.put(tuple.getTupleType(), 1);
} else{
double currentAverage = tupleTypeToAverageCpuTime.get(tuple.getTupleType());
int currentCount = tupleTypeToExecutedTupleCount.get(tuple.getTupleType());
tupleTypeToAverageCpuTime.put(tuple.getTupleType(), (currentAverage*currentCount+executionTime)/(currentCount+1));
}
}
public Map<Integer, List<Integer>> loopIdToTupleIds(){
return getInstance().getLoopIdToTupleIds();
}
private TimeKeeper(){
count = 1;
setEmitTimes(new HashMap<Integer, Double>());
setEndTimes(new HashMap<Integer, Double>());
setLoopIdToTupleIds(new HashMap<Integer, List<Integer>>());
setTupleTypeToAverageCpuTime(new HashMap<String, Double>());
setTupleTypeToExecutedTupleCount(new HashMap<String, Integer>());
setTupleIdToCpuStartTime(new HashMap<Integer, Double>());
setLoopIdToCurrentAverage(new HashMap<Integer, Double>());
setLoopIdToCurrentNum(new HashMap<Integer, Integer>());
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Map<Integer, Double> getEmitTimes() {
return emitTimes;
}
public void setEmitTimes(Map<Integer, Double> emitTimes) {
this.emitTimes = emitTimes;
}
public Map<Integer, Double> getEndTimes() {
return endTimes;
}
public void setEndTimes(Map<Integer, Double> endTimes) {
this.endTimes = endTimes;
}
public Map<Integer, List<Integer>> getLoopIdToTupleIds() {
return loopIdToTupleIds;
}
public void setLoopIdToTupleIds(Map<Integer, List<Integer>> loopIdToTupleIds) {
this.loopIdToTupleIds = loopIdToTupleIds;
}
public Map<String, Double> getTupleTypeToAverageCpuTime() {
return tupleTypeToAverageCpuTime;
}
public void setTupleTypeToAverageCpuTime(
Map<String, Double> tupleTypeToAverageCpuTime) {
this.tupleTypeToAverageCpuTime = tupleTypeToAverageCpuTime;
}
public Map<String, Integer> getTupleTypeToExecutedTupleCount() {
return tupleTypeToExecutedTupleCount;
}
public void setTupleTypeToExecutedTupleCount(
Map<String, Integer> tupleTypeToExecutedTupleCount) {
this.tupleTypeToExecutedTupleCount = tupleTypeToExecutedTupleCount;
}
public Map<Integer, Double> getTupleIdToCpuStartTime() {
return tupleIdToCpuStartTime;
}
public void setTupleIdToCpuStartTime(Map<Integer, Double> tupleIdToCpuStartTime) {
this.tupleIdToCpuStartTime = tupleIdToCpuStartTime;
}
public long getSimulationStartTime() {
return simulationStartTime;
}
public void setSimulationStartTime(long simulationStartTime) {
this.simulationStartTime = simulationStartTime;
}
public Map<Integer, Double> getLoopIdToCurrentAverage() {
return loopIdToCurrentAverage;
}
public void setLoopIdToCurrentAverage(Map<Integer, Double> loopIdToCurrentAverage) {
this.loopIdToCurrentAverage = loopIdToCurrentAverage;
}
public Map<Integer, Integer> getLoopIdToCurrentNum() {
return loopIdToCurrentNum;
}
public void setLoopIdToCurrentNum(Map<Integer, Integer> loopIdToCurrentNum) {
this.loopIdToCurrentNum = loopIdToCurrentNum;
}
}

View File

@@ -0,0 +1,51 @@
package org.fog.utils;
public class TupleFinishDetails {
private String queryId;
private int actualTupleId;
private double emitTime;
private double finishTime;
private String sensorType;
public TupleFinishDetails(String queryId, int actualTupleId, double emitTime, double finishTime, String sensorType){
this.queryId = queryId;
this.actualTupleId = actualTupleId;
this.emitTime = emitTime;
this.finishTime = finishTime;
this.sensorType = sensorType;
}
public String getQueryId() {
return queryId;
}
public void setQueryId(String queryId) {
this.queryId = queryId;
}
public int getActualTupleId() {
return actualTupleId;
}
public void setActualTupleId(int actualTupleId) {
this.actualTupleId = actualTupleId;
}
public double getEmitTime() {
return emitTime;
}
public void setEmitTime(double emitTime) {
this.emitTime = emitTime;
}
public double getFinishTime() {
return finishTime;
}
public void setFinishTime(double finishTime) {
this.finishTime = finishTime;
}
public String getSensorType() {
return sensorType;
}
public void setSensorType(String sensorType) {
this.sensorType = sensorType;
}
}

View File

@@ -0,0 +1,35 @@
package org.fog.utils.distribution;
public class DeterministicDistribution extends Distribution{
private double value;
public DeterministicDistribution(double value) {
super();
setValue(value);
}
@Override
public double getNextValue() {
return value;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
@Override
public int getDistributionType() {
return Distribution.DETERMINISTIC;
}
@Override
public double getMeanInterTransmitTime() {
return value;
}
}

View File

@@ -0,0 +1,24 @@
package org.fog.utils.distribution;
import java.util.Random;
public abstract class Distribution {
public static int NORMAL = 1;
public static int DETERMINISTIC = 2;
public static int UNIFORM = 3;
protected Random random;
public abstract double getNextValue();
public Random getRandom() {
return random;
}
public void setRandom(Random random) {
this.random = random;
}
public abstract int getDistributionType();
public abstract double getMeanInterTransmitTime();
}

View File

@@ -0,0 +1,47 @@
package org.fog.utils.distribution;
import java.util.Random;
public class NormalDistribution extends Distribution{
private double mean;
private double stdDev;
public NormalDistribution(double mean, double stdDev) {
setMean(mean);
setStdDev(stdDev);
setRandom(new Random());
}
@Override
public double getNextValue() {
return random.nextGaussian()*stdDev + mean;
}
public double getMean() {
return mean;
}
public void setMean(double mean) {
this.mean = mean;
}
public double getStdDev() {
return stdDev;
}
public void setStdDev(double stdDev) {
this.stdDev = stdDev;
}
@Override
public int getDistributionType() {
return Distribution.NORMAL;
}
@Override
public double getMeanInterTransmitTime() {
return mean;
}
}

View File

@@ -0,0 +1,45 @@
package org.fog.utils.distribution;
public class UniformDistribution extends Distribution{
private double min;
private double max;
public UniformDistribution(double min, double max){
super();
setMin(min);
setMax(max);
}
@Override
public double getNextValue() {
return getRandom().nextDouble()*(getMax()-getMin())+getMin();
}
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
@Override
public int getDistributionType() {
return Distribution.UNIFORM;
}
@Override
public double getMeanInterTransmitTime() {
return (min+max)/2;
}
}