View Javadoc

1   /*
2    * JBoss, Home of Professional Open Source.
3    * Copyright 2013, Red Hat Middleware LLC, and individual contributors
4    * as indicated by the @author tags. See the copyright.txt file in the
5    * distribution for a full listing of individual contributors.
6    *
7    * This is free software; you can redistribute it and/or modify it
8    * under the terms of the GNU Lesser General Public License as
9    * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */
22  package org.redhat.vmtruckloader.vmware;
23  
24  import java.rmi.RemoteException;
25  import java.util.ArrayList;
26  import java.util.List;
27  
28  import org.slf4j.Logger;
29  import org.slf4j.LoggerFactory;
30  
31  import com.vmware.vim25.mo.Datastore;
32  import com.vmware.vim25.mo.Folder;
33  import com.vmware.vim25.mo.InventoryNavigator;
34  import com.vmware.vim25.mo.ManagedEntity;
35  import com.vmware.vim25.mo.ResourcePool;
36  import com.vmware.vim25.mo.ServiceInstance;
37  import com.vmware.vim25.mo.VirtualMachine;
38  
39  /**
40   * 
41   * @author Romain Pelisse - romain@redhat.com
42   *
43   */
44  public class VMWareManagedObjectUtils {
45  
46  	private static final Logger LOGGER = LoggerFactory.getLogger(VMWareManagedObjectUtils.class);
47  	
48  	private static final boolean WMWARE_FREESPACE_RECO_ENABLED = true;
49  	
50  	public  static List<ManagedEntity> getManagedEntities(InventoryNavigator inventoryNavigator, String entityClass) {
51  		List<ManagedEntity> managedEntities = new ArrayList<ManagedEntity>();
52  
53  		try {
54  			for (ManagedEntity me : inventoryNavigator.searchManagedEntities(entityClass)) {
55  				managedEntities.add(me);
56  			}
57  		} catch (RemoteException e) {
58  			e.printStackTrace();
59              throw new IllegalArgumentException(e);
60  		}
61  
62  		return managedEntities;
63  	}
64  
65      public  static List<ManagedEntity> getManagedEntities(ServiceInstance serviceInstance, String entityClass) {
66          List<ManagedEntity> managedEntities = new ArrayList<ManagedEntity>();
67  
68          try {
69  			InventoryNavigator inventoryNavigator = new InventoryNavigator(serviceInstance.getRootFolder());
70              for (ManagedEntity me : inventoryNavigator.searchManagedEntities(entityClass)) {
71                   managedEntities.add(me);
72              }
73          } catch (RemoteException e) {
74              e.printStackTrace();
75              throw new IllegalArgumentException(e);
76          }
77  
78          return managedEntities;
79      }
80  
81  	public  static ResourcePool findResourcePoolByName(ServiceInstance serviceInstance, String resourcePoolName) {
82  		List<ManagedEntity> pools = getManagedEntities(serviceInstance, ResourcePool.class.getSimpleName());
83  		for ( ManagedEntity resourcePool : pools) {
84  			if ( resourcePool instanceof ResourcePool ) {
85  				ResourcePool pool = (ResourcePool)resourcePool;
86  				if ( pool.getName().equals(resourcePool.getName()))
87  					return pool;
88  			}
89  		}
90  		return null;
91  	}
92  
93  	public  static Folder lookVmFolder(ServiceInstance serviceInstance, String foldername) {
94  		Folder vmFolder = null;
95  		List<ManagedEntity> folders = getManagedEntities(serviceInstance,Folder.class.getSimpleName());
96  		for ( ManagedEntity folder : folders) {
97  			String mssg = "- " + folder.getName();
98  			if ( folder instanceof Folder ) {
99  				mssg += ", parent:" + ((Folder)folder).getParent();
100 				if ( foldername.equals(folder.getName()))
101 					vmFolder = (Folder)folder;
102 			}
103 			if ( LOGGER.isDebugEnabled() ) LOGGER.debug(mssg);
104 		}
105 		
106 		if ( vmFolder == null ) {
107 			LOGGER.error("No folder named " + foldername + " found");
108 			throw new IllegalArgumentException("No folder named " + foldername + " found");
109 		}
110 		return vmFolder;
111 	}
112 	
113 	/**
114 	 * Find datastore with max available space in a given storage pod for a new
115 	 * virtual machine with diskSize bytes. VMWare recommends to use data stores
116 	 * up to 90%.
117 	 * 
118 	 * @param storagePodName
119 	 *            the storage pod name to use
120 	 * @param vc
121 	 *            the virtual data center
122 	 * @param diskSize
123 	 *            required disk size (in KB)
124 	 * @return a datastore or null if none found
125 	 */
126 	public static Datastore findDataStore(String storagePodName,
127 			int diskSize, ServiceInstance instance) {
128 		Datastore targetDS = null;
129 		final List<Datastore> dss = getDatastores(instance);
130 		long maxSize = 0;
131 		for (Datastore ds : dss) {
132 			if (ds.getName().equals(storagePodName)) {
133 				final long usableSize = ds.getSummary().getFreeSpace() * 90 / 100; // VMWare
134 																					// recommendation
135 				maxSize = usableSize;
136 				targetDS = ds;
137 				if (usableSize > maxSize && usableSize >= diskSize * 1024) {
138 					final String errorMssg = "Datastore " + storagePodName
139 							+ " found, but not with enough free space:"
140 							+ ds.getSummary().getFreeSpace();
141 					LOGGER.warn(errorMssg);
142 					if (WMWARE_FREESPACE_RECO_ENABLED)
143 						throw new IllegalArgumentException("Datastore "
144 								+ storagePodName
145 								+ " found, but not with enough free space:"
146 								+ ds.getSummary().getFreeSpace());
147 				}
148 			}
149 		}
150 		if (targetDS == null)
151 			throw new IllegalArgumentException("No storage found with name "
152 					+ storagePodName + ".");
153 		return targetDS;
154 	}
155 	
156 	
157 	private static List<Datastore> getDatastores(ServiceInstance serviceInstance) {
158 		final List<Datastore> datastores = new ArrayList<Datastore>();
159 
160 		try {
161 			final InventoryNavigator inventoryNavigator = new InventoryNavigator(
162 					serviceInstance.getRootFolder());
163 			for (ManagedEntity me : inventoryNavigator
164 					.searchManagedEntities(Datastore.class.getSimpleName())) {
165 				if ( LOGGER.isDebugEnabled())
166 					LOGGER.debug("Datastore found:" + me.getName());
167 				datastores.add((Datastore) me);
168 			}
169 		} catch (RemoteException e) {
170 			e.printStackTrace();
171 			throw new IllegalArgumentException(e);
172 		}
173 
174 		return datastores;
175 	}
176 	
177 	public static VirtualMachine getVm(ServiceInstance serviceInstance, String vmName) {
178 		VirtualMachine vm = null;
179 		try {
180 			Folder rootFolder = serviceInstance.getRootFolder();
181 			InventoryNavigator inventoryNavigator = new InventoryNavigator(rootFolder);
182 
183 			vm = (VirtualMachine) inventoryNavigator.searchManagedEntity(VirtualMachine.class.getSimpleName(), vmName);
184 		} catch (RemoteException re) {
185 			String errorMessage = "Error retrieving VirtualMachine with name: '" + vmName + "'.";
186 			LOGGER.error(errorMessage, re);
187 
188 		}
189 		return vm;
190 	}
191 }