1 package at.ac.tuwien.lsdc.types;
3 import java.util.ArrayList;
4 import java.util.HashMap;
6 import at.ac.tuwien.lsdc.exception.VMResizeException;
8 public class VirtualMachine {
11 Resizable, NonResizable
14 private static int count = 0;
17 private PhysicalMachine runningOn;
19 private HashMap<Integer, Application> applications = new HashMap<Integer, Application>();
23 public static final int initialSize = 100;
24 public static final int initialRAM = 50;
25 public static final int initialCPU = 150;
27 private int reservedSize;
28 private int reservedRAM;
29 private int reservedCPU;
33 public VirtualMachine(int size, int RAM, int CPU, PhysicalMachine pm, VMType type) {
36 reservedSize = size + initialSize;
37 reservedRAM = RAM + initialRAM;
38 reservedCPU = CPU + initialCPU;
40 posOnPM = pm.countCurrentlyRunningVMs();
44 public boolean startApplication(Application app) {
45 if (enoughResources(app)) {
46 applications.put(app.getID(), app);
47 app.setRunningOn(this);
54 * Set the VM size to the given new values.
61 public boolean resizeVM(int newSize, int newRAM, int newCPU) {
62 if (type == VMType.Resizable && runningOn.checkVM(newSize, newRAM, newCPU)) {
64 reservedSize = initialSize + newSize;
65 reservedRAM = initialRAM + newRAM;
66 reservedCPU = initialCPU + newCPU;
69 throw new VMResizeException("Could not resize VM!", this);
72 public boolean stopApplication(Application app) {
73 if (applications.containsKey(app.getID())) {
74 applications.remove(app.getID());
75 app.setRunningOn(null);
81 private boolean enoughResources(Application app) {
82 return (app.getSize() <= availableSize()) && (app.getRam() <= availableRAM()) && (app.getCpu() <= availableCPU());
85 private int availableSize() {
86 return reservedSize - getSize();
89 private int availableRAM() {
90 return reservedRAM - getRAM();
93 private int availableCPU() {
94 return reservedCPU - getCPU();
101 public PhysicalMachine getRunningOn() {
105 public int getPositionOnPM() {
109 public ArrayList<Application> getApplications() {
110 return new ArrayList<Application>(applications.values());
113 public int getSize() {
114 int usedSize = initialSize;
115 for (Application a : applications.values())
116 usedSize += a.getSize();
120 public int getRAM() {
121 int usedRAM = initialRAM;
122 for (Application a : applications.values())
123 usedRAM += a.getRam();
127 public int getCPU() {
128 int usedCPU = initialCPU;
129 for (Application a : applications.values())
130 usedCPU += a.getCpu();
134 public int getReservedSize() {
138 public int getReservedRAM() {
142 public int getReservedCPU() {
147 public String toString() {
148 return "VirtualMachine [posOnPM=" + posOnPM + ", runningOn=" + runningOn + ", id=" + id + ", reservedSize="
149 + reservedSize + ", reservedRAM=" + reservedRAM + ", reservedCPU=" + reservedCPU + ", type=" + type + "]";