PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/internal/BaseVCloudDirectorApiLiveTest.java

https://github.com/richardcloudsoft/legacy-jclouds
Java | 752 lines | 580 code | 124 blank | 48 comment | 60 complexity | a32597d3bacbb7face299fabd349a249 MD5 | raw file
  1. /**
  2. * Licensed to jclouds, Inc. (jclouds) under one or more
  3. * contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. jclouds licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package org.jclouds.vcloud.director.v1_5.internal;
  20. import static com.google.common.base.Predicates.and;
  21. import static com.google.common.base.Strings.emptyToNull;
  22. import static com.google.common.collect.Iterables.any;
  23. import static com.google.common.collect.Iterables.contains;
  24. import static com.google.common.collect.Iterables.find;
  25. import static com.google.common.collect.Iterables.getFirst;
  26. import static com.google.common.collect.Iterables.tryFind;
  27. import static org.jclouds.util.Predicates2.retry;
  28. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.ENTITY_NON_NULL;
  29. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.TASK_COMPLETE_TIMELY;
  30. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.URN_REQ_LIVE;
  31. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.CATALOG;
  32. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.MEDIA;
  33. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.NETWORK;
  34. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.ORG_NETWORK;
  35. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.USER;
  36. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.VAPP;
  37. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.VAPP_TEMPLATE;
  38. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.VDC;
  39. import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.VM;
  40. import static org.jclouds.vcloud.director.v1_5.predicates.LinkPredicates.relEquals;
  41. import static org.jclouds.vcloud.director.v1_5.predicates.LinkPredicates.typeEquals;
  42. import static org.testng.Assert.assertEquals;
  43. import static org.testng.Assert.assertNotNull;
  44. import static org.testng.Assert.assertTrue;
  45. import static org.testng.Assert.fail;
  46. import java.net.URI;
  47. import java.text.SimpleDateFormat;
  48. import java.util.Date;
  49. import java.util.Random;
  50. import java.util.Set;
  51. import javax.annotation.Resource;
  52. import javax.inject.Inject;
  53. import org.jclouds.apis.BaseContextLiveTest;
  54. import org.jclouds.date.DateService;
  55. import org.jclouds.io.Payloads;
  56. import org.jclouds.logging.Logger;
  57. import org.jclouds.rest.RestContext;
  58. import org.jclouds.vcloud.director.testng.FormatApiResultsListener;
  59. import org.jclouds.vcloud.director.v1_5.VCloudDirectorApiMetadata;
  60. import org.jclouds.vcloud.director.v1_5.VCloudDirectorContext;
  61. import org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType;
  62. import org.jclouds.vcloud.director.v1_5.admin.VCloudDirectorAdminApi;
  63. import org.jclouds.vcloud.director.v1_5.admin.VCloudDirectorAdminAsyncApi;
  64. import org.jclouds.vcloud.director.v1_5.domain.Catalog;
  65. import org.jclouds.vcloud.director.v1_5.domain.Checks;
  66. import org.jclouds.vcloud.director.v1_5.domain.Link;
  67. import org.jclouds.vcloud.director.v1_5.domain.Link.Rel;
  68. import org.jclouds.vcloud.director.v1_5.domain.Media;
  69. import org.jclouds.vcloud.director.v1_5.domain.Reference;
  70. import org.jclouds.vcloud.director.v1_5.domain.ResourceEntity.Status;
  71. import org.jclouds.vcloud.director.v1_5.domain.Role.DefaultRoles;
  72. import org.jclouds.vcloud.director.v1_5.domain.RoleReferences;
  73. import org.jclouds.vcloud.director.v1_5.domain.Session;
  74. import org.jclouds.vcloud.director.v1_5.domain.Task;
  75. import org.jclouds.vcloud.director.v1_5.domain.User;
  76. import org.jclouds.vcloud.director.v1_5.domain.VApp;
  77. import org.jclouds.vcloud.director.v1_5.domain.VAppTemplate;
  78. import org.jclouds.vcloud.director.v1_5.domain.Vdc;
  79. import org.jclouds.vcloud.director.v1_5.domain.Vm;
  80. import org.jclouds.vcloud.director.v1_5.domain.network.Network;
  81. import org.jclouds.vcloud.director.v1_5.domain.network.NetworkConfiguration;
  82. import org.jclouds.vcloud.director.v1_5.domain.network.VAppNetworkConfiguration;
  83. import org.jclouds.vcloud.director.v1_5.domain.org.Org;
  84. import org.jclouds.vcloud.director.v1_5.domain.params.InstantiateVAppTemplateParams;
  85. import org.jclouds.vcloud.director.v1_5.domain.params.InstantiationParams;
  86. import org.jclouds.vcloud.director.v1_5.domain.params.UndeployVAppParams;
  87. import org.jclouds.vcloud.director.v1_5.domain.section.NetworkConfigSection;
  88. import org.jclouds.vcloud.director.v1_5.features.TaskApi;
  89. import org.jclouds.vcloud.director.v1_5.features.VAppApi;
  90. import org.jclouds.vcloud.director.v1_5.features.VAppTemplateApi;
  91. import org.jclouds.vcloud.director.v1_5.features.VdcApi;
  92. import org.jclouds.vcloud.director.v1_5.predicates.LinkPredicates;
  93. import org.jclouds.vcloud.director.v1_5.predicates.ReferencePredicates;
  94. import org.jclouds.vcloud.director.v1_5.predicates.TaskStatusEquals;
  95. import org.jclouds.vcloud.director.v1_5.predicates.TaskSuccess;
  96. import org.jclouds.vcloud.director.v1_5.user.VCloudDirectorApi;
  97. import org.testng.annotations.BeforeClass;
  98. import org.testng.annotations.Listeners;
  99. import org.testng.annotations.Test;
  100. import com.google.common.base.Function;
  101. import com.google.common.base.Objects;
  102. import com.google.common.base.Optional;
  103. import com.google.common.base.Predicate;
  104. import com.google.common.base.Predicates;
  105. import com.google.common.collect.FluentIterable;
  106. import com.google.common.collect.ImmutableSet;
  107. import com.google.common.collect.Iterables;
  108. import com.google.common.collect.Lists;
  109. import com.google.common.collect.Sets;
  110. import com.google.common.reflect.TypeToken;
  111. import com.google.inject.Guice;
  112. /**
  113. * Tests behavior of {@link VCloudDirectorApi} and acts as parent for other api live tests.
  114. *
  115. * @author Adrian Cole
  116. * @author grkvlt@apache.org
  117. */
  118. @Listeners(FormatApiResultsListener.class)
  119. @Test(groups = "live")
  120. public abstract class BaseVCloudDirectorApiLiveTest extends BaseContextLiveTest<VCloudDirectorContext> {
  121. @Resource
  122. protected Logger logger = Logger.NULL;
  123. protected static final long TASK_TIMEOUT_SECONDS = 100L;
  124. protected static final long LONG_TASK_TIMEOUT_SECONDS = 300L;
  125. public static final int REQUIRED_ADMIN_VM_QUOTA = 0;
  126. public static final int REQUIRED_USER_VM_QUOTA = 0;
  127. public Predicate<Task> retryTaskSuccess;
  128. public Predicate<Task> retryTaskSuccessLong;
  129. protected RestContext<VCloudDirectorAdminApi, VCloudDirectorAdminAsyncApi> adminContext;
  130. protected Session adminSession;
  131. protected Session session;
  132. protected String orgUrn;
  133. protected Org org;
  134. protected String catalogUrn;
  135. private Catalog catalog;
  136. protected String vAppTemplateUrn;
  137. private VAppTemplate vAppTemplate;
  138. protected String mediaUrn;
  139. private Media media;
  140. protected String networkUrn;
  141. private Network network;
  142. protected String vdcUrn;
  143. private Vdc vdc;
  144. protected String userUrn;
  145. private User user;
  146. protected final Set<String> vAppNames = Sets.newLinkedHashSet();
  147. protected static final Random random = new Random();
  148. protected BaseVCloudDirectorApiLiveTest() {
  149. provider = "vcloud-director";
  150. }
  151. protected DateService dateService;
  152. protected static String testStamp;
  153. @BeforeClass(alwaysRun = true)
  154. protected void setupDateService() {
  155. dateService = Guice.createInjector().getInstance(DateService.class);
  156. assertNotNull(dateService);
  157. }
  158. /** Implement as required to populate xxxApi fields, or NOP */
  159. protected abstract void setupRequiredApis();
  160. @Inject
  161. protected void initTaskSuccess(TaskSuccess taskSuccess) {
  162. retryTaskSuccess = retry(taskSuccess, TASK_TIMEOUT_SECONDS * 1000L);
  163. }
  164. @Inject
  165. protected void initTaskSuccessLong(TaskSuccess taskSuccess) {
  166. retryTaskSuccessLong = retry(taskSuccess, LONG_TASK_TIMEOUT_SECONDS * 1000L);
  167. }
  168. @BeforeClass(groups = { "integration", "live" })
  169. public void setupContext() {
  170. super.setupContext();
  171. adminContext = context.getAdminContext();
  172. adminSession = adminContext.getApi().getCurrentSession();
  173. adminContext.utils().injector().injectMembers(this);
  174. session = context.getApi().getCurrentSession();
  175. context.utils().injector().injectMembers(this);
  176. initTestParametersFromPropertiesOrLazyDiscover();
  177. setupRequiredApis();
  178. }
  179. public static String getTestDateTimeStamp() {
  180. if (testStamp == null) {
  181. testStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
  182. }
  183. return testStamp;
  184. }
  185. public Reference getRoleReferenceFor(String name) {
  186. return getRoleReferenceFor(name, adminContext);
  187. }
  188. public static Reference getRoleReferenceFor(String name,
  189. RestContext<VCloudDirectorAdminApi, VCloudDirectorAdminAsyncApi> adminContext) {
  190. RoleReferences roles = adminContext.getApi().getQueryApi().roleReferencesQueryAll();
  191. // backend in a builder to strip out unwanted xml cruft that the api chokes on
  192. return Reference.builder().fromReference(find(roles.getReferences(), ReferencePredicates.nameEquals(name)))
  193. .build();
  194. }
  195. public User randomTestUser(String prefix) {
  196. return randomTestUser(prefix, getRoleReferenceFor(DefaultRoles.USER.value()));
  197. }
  198. public User randomTestUser(String prefix, Reference role) {
  199. return User.builder().name(name(prefix) + getTestDateTimeStamp()).fullName("testFullName")
  200. .emailAddress("test@test.com").telephone("555-1234").isEnabled(false).im("testIM").isAlertEnabled(false)
  201. .alertEmailPrefix("testPrefix").alertEmail("testAlert@test.com").isExternal(false).isGroupRole(false)
  202. .role(role).password("password").build();
  203. }
  204. protected void initTestParametersFromPropertiesOrLazyDiscover() {
  205. catalogUrn = emptyToNull(System.getProperty("test." + provider + ".catalog-id"));
  206. vAppTemplateUrn = emptyToNull(System.getProperty("test." + provider + ".vapptemplate-id"));
  207. vdcUrn = emptyToNull(System.getProperty("test." + provider + ".vdc-id"));
  208. mediaUrn = emptyToNull(System.getProperty("test." + provider + ".media-id"));
  209. networkUrn = emptyToNull(System.getProperty("test." + provider + ".network-id"));
  210. userUrn = emptyToNull(System.getProperty("test." + provider + ".user-id"));
  211. org = context
  212. .getApi()
  213. .getOrgApi()
  214. .get(find(context.getApi().getOrgApi().list(), ReferencePredicates.<Reference> nameEquals(session.get()))
  215. .getHref());
  216. orgUrn = org.getId();
  217. if (any(Lists.newArrayList(vAppTemplateUrn, networkUrn, vdcUrn), Predicates.isNull())) {
  218. if (vdcUrn == null) {
  219. vdc = context.getApi().getVdcApi()
  220. .get(find(org.getLinks(), ReferencePredicates.<Link> typeEquals(VDC)).getHref());
  221. vdcUrn = vdc.getId();
  222. if (vAppTemplateUrn == null) {
  223. Optional<VAppTemplate> optionalvAppTemplate = tryFindVAppTemplateInOrg();
  224. if (optionalvAppTemplate.isPresent()) {
  225. vAppTemplate = optionalvAppTemplate.get();
  226. vAppTemplateUrn = vAppTemplate.getId();
  227. }
  228. }
  229. }
  230. if (networkUrn == null) {
  231. Optional<Network> optionalNetwork = tryFindBridgedNetworkInOrg();
  232. if (optionalNetwork.isPresent()) {
  233. network = optionalNetwork.get();
  234. networkUrn = network.getId();
  235. }
  236. }
  237. if (catalogUrn == null) {
  238. Optional<Catalog> optionalCatalog = tryFindWritableCatalogInOrg();
  239. if (optionalCatalog.isPresent()) {
  240. catalog = optionalCatalog.get();
  241. catalogUrn = catalog.getId();
  242. }
  243. }
  244. }
  245. }
  246. Function<VAppTemplate, String> prettyVAppTemplate = new Function<VAppTemplate, String>() {
  247. @Override
  248. public String apply(VAppTemplate input) {
  249. return Objects.toStringHelper("").omitNullValues().add("name", input.getName()).add("id", input.getId())
  250. .add("owner", input.getOwner()).toString();
  251. }
  252. };
  253. public Optional<VAppTemplate> tryFindVAppTemplateInOrg() {
  254. FluentIterable<VAppTemplate> vAppTemplates = FluentIterable.from(vdc.getResourceEntities())
  255. .filter(ReferencePredicates.<Reference> typeEquals(VAPP_TEMPLATE))
  256. .transform(new Function<Reference, VAppTemplate>() {
  257. @Override
  258. public VAppTemplate apply(Reference in) {
  259. return context.getApi().getVAppTemplateApi().get(in.getHref());
  260. }})
  261. .filter(Predicates.notNull());
  262. Optional<VAppTemplate> optionalVAppTemplate = tryFind(vAppTemplates, new Predicate<VAppTemplate>() {
  263. @Override
  264. public boolean apply(VAppTemplate input) {
  265. return input.getOwner().getUser().getName().equals(session.getUser());
  266. }
  267. });
  268. if (optionalVAppTemplate.isPresent()) {
  269. Logger.CONSOLE.info("found vAppTemplate: %s", prettyVAppTemplate.apply(optionalVAppTemplate.get()));
  270. } else {
  271. Logger.CONSOLE.warn("%s doesn't own any vApp Template in org %s; vApp templates: %s", context.getApi()
  272. .getCurrentSession().getUser(), org.getName(), Iterables.transform(vAppTemplates, prettyVAppTemplate));
  273. }
  274. return optionalVAppTemplate;
  275. }
  276. Function<Vm, String> prettyVm = new Function<Vm, String>() {
  277. @Override
  278. public String apply(Vm input) {
  279. return Objects.toStringHelper("").omitNullValues().add("name", input.getName()).add("id", input.getId()).toString();
  280. }
  281. };
  282. public Optional<Vm> tryFindVmInOrg() {
  283. FluentIterable<Vm> vms = FluentIterable.from(vdc.getResourceEntities())
  284. .filter(ReferencePredicates.<Reference> typeEquals(VM))
  285. .transform(new Function<Reference, Vm>() {
  286. @Override
  287. public Vm apply(Reference in) {
  288. return context.getApi().getVmApi().get(in.getHref());
  289. }})
  290. .filter(Predicates.notNull());
  291. Optional<Vm> optionalVm = tryFind(vms, new Predicate<Vm>() {
  292. @Override
  293. public boolean apply(Vm input) {
  294. return input.getId() != null;
  295. }
  296. });
  297. if (optionalVm.isPresent()) {
  298. Logger.CONSOLE.info("found vm: %s", prettyVm.apply(optionalVm.get()));
  299. } else {
  300. Logger.CONSOLE.warn("%s doesn't have any vm in org %s; vms: %s", context.getApi()
  301. .getCurrentSession().getUser(), org.getName(), Iterables.transform(vms, prettyVm));
  302. }
  303. return optionalVm;
  304. }
  305. Function<Catalog, String> prettyCatalog = new Function<Catalog, String>() {
  306. @Override
  307. public String apply(Catalog input) {
  308. return Objects.toStringHelper("").omitNullValues().add("name", input.getName()).add("id", input.getId())
  309. .add("owner", input.getOwner()).add("isPublished", input.isPublished()).toString();
  310. }
  311. };
  312. /**
  313. * If I can add to a catalog, I can write to it
  314. */
  315. public Optional<Catalog> tryFindWritableCatalogInOrg() {
  316. FluentIterable<Catalog> catalogs = FluentIterable.from(org.getLinks())
  317. .filter(ReferencePredicates.<Link> typeEquals(CATALOG)).transform(new Function<Link, Catalog>() {
  318. @Override
  319. public Catalog apply(Link in) {
  320. return context.getApi().getCatalogApi().get(in.getHref());
  321. }
  322. });
  323. Optional<Catalog> optionalCatalog = tryFind(catalogs, new Predicate<Catalog>() {
  324. @Override
  325. public boolean apply(Catalog input) {
  326. return Iterables.any(input.getLinks(), LinkPredicates.relEquals(Rel.ADD));
  327. }
  328. });
  329. if (optionalCatalog.isPresent()) {
  330. Logger.CONSOLE.info("found catalog: %s", prettyCatalog.apply(optionalCatalog.get()));
  331. } else {
  332. Logger.CONSOLE.warn("%s doesn't own any catalogs in org %s; catalogs: %s", context.getApi()
  333. .getCurrentSession().getUser(), org.getName(), Iterables.transform(catalogs, prettyCatalog));
  334. }
  335. return optionalCatalog;
  336. }
  337. Function<Network, String> prettyNetwork = new Function<Network, String>() {
  338. @Override
  339. public String apply(Network input) {
  340. return Objects.toStringHelper("").omitNullValues().add("name", input.getName()).add("id", input.getId())
  341. .add("fenceMode", input.getConfiguration().getFenceMode())
  342. .add("taskCount", input.getTasks().size() > 0 ? input.getTasks().size() : null).toString();
  343. }
  344. };
  345. public Optional<Network> tryFindBridgedNetworkInOrg() {
  346. FluentIterable<Network> networks = FluentIterable.from(org.getLinks())
  347. .filter(ReferencePredicates.<Link> typeEquals(ORG_NETWORK)).transform(new Function<Link, Network>() {
  348. @Override
  349. public Network apply(Link in) {
  350. return context.getApi().getNetworkApi().get(in.getHref());
  351. }
  352. });
  353. Optional<Network> optionalNetwork = tryFind(networks, new Predicate<Network>() {
  354. @Override
  355. public boolean apply(Network input) {
  356. if (input.getConfiguration().getFenceMode().equals(Network.FenceMode.BRIDGED)) {
  357. if (input.getTasks().size() == 0) {
  358. return true;
  359. }
  360. }
  361. return false;
  362. }
  363. });
  364. if (optionalNetwork.isPresent()) {
  365. Logger.CONSOLE.info("found network: %s", prettyNetwork.apply(optionalNetwork.get()));
  366. } else {
  367. Logger.CONSOLE.warn("no ready bridged networks present in org %s; networks: %s", org.getName(),
  368. Iterables.transform(networks, prettyNetwork));
  369. }
  370. return optionalNetwork;
  371. }
  372. public FluentIterable<Media> findAllEmptyMediaInOrg() {
  373. vdc = context.getApi().getVdcApi().get(vdc.getId());
  374. return FluentIterable
  375. .from(vdc.getResourceEntities())
  376. .filter(ReferencePredicates.<Reference> typeEquals(MEDIA))
  377. .transform(new Function<Reference, Media>() {
  378. @Override
  379. public Media apply(Reference in) {
  380. return context.getApi().getMediaApi()
  381. .get(in.getHref());
  382. }
  383. }).filter(new Predicate<Media>() {
  384. @Override
  385. public boolean apply(Media input) {
  386. return input.getSize() == 0;
  387. }
  388. });
  389. }
  390. public void cleanUpVAppTemplateInOrg() {
  391. FluentIterable<VAppTemplate> vAppTemplates = FluentIterable
  392. .from(vdc.getResourceEntities())
  393. .filter(ReferencePredicates
  394. .<Reference> typeEquals(VAPP_TEMPLATE))
  395. .transform(new Function<Reference, VAppTemplate>() {
  396. @Override
  397. public VAppTemplate apply(Reference in) {
  398. return context.getApi().getVAppTemplateApi()
  399. .get(in.getHref());
  400. }
  401. }).filter(Predicates.notNull());
  402. Iterables.removeIf(vAppTemplates, new Predicate<VAppTemplate>() {
  403. @Override
  404. public boolean apply(VAppTemplate input) {
  405. if(input.getName().startsWith("captured-") || input.getName().startsWith("uploaded-") || input.getName().startsWith("vappTemplateClone-"))
  406. context.getApi().getVAppTemplateApi().remove(input.getHref());
  407. return false;
  408. }});
  409. }
  410. protected Vdc lazyGetVdc() {
  411. if (vdc == null) {
  412. assertNotNull(vdcUrn, String.format(URN_REQ_LIVE, VDC));
  413. vdc = context.getApi().getVdcApi().get(vdcUrn);
  414. assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC));
  415. }
  416. return vdc;
  417. }
  418. protected Network lazyGetNetwork() {
  419. if (network == null) {
  420. assertNotNull(networkUrn, String.format(URN_REQ_LIVE, NETWORK));
  421. network = context.getApi().getNetworkApi().get(networkUrn);
  422. assertNotNull(network, String.format(ENTITY_NON_NULL, NETWORK));
  423. }
  424. return network;
  425. }
  426. protected Catalog lazyGetCatalog() {
  427. if (catalog == null) {
  428. assertNotNull(catalogUrn, String.format(URN_REQ_LIVE, CATALOG));
  429. catalog = context.getApi().getCatalogApi().get(catalogUrn);
  430. assertNotNull(catalog, String.format(ENTITY_NON_NULL, CATALOG));
  431. }
  432. return catalog;
  433. }
  434. protected User lazyGetUser() {
  435. if (user == null) {
  436. assertNotNull(userUrn, String.format(URN_REQ_LIVE, USER));
  437. user = adminContext.getApi().getUserApi().get(userUrn);
  438. assertNotNull(user, String.format(ENTITY_NON_NULL, USER));
  439. }
  440. return user;
  441. }
  442. protected Media lazyGetMedia(){
  443. if (media == null || mediaUrn == null) {
  444. Predicate<Link> addMediaLink = and(relEquals(Link.Rel.ADD), typeEquals(VCloudDirectorMediaType.MEDIA));
  445. if (contains(lazyGetVdc().getLinks(), addMediaLink)) {
  446. Link addMedia = find(lazyGetVdc().getLinks(), addMediaLink);
  447. byte[] iso = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
  448. Media sourceMedia = Media.builder().type(VCloudDirectorMediaType.MEDIA).name(name("media"))
  449. .size(iso.length).imageType(Media.ImageType.ISO)
  450. .description("Test media generated by VmApiLiveTest").build();
  451. media = context.getApi().getMediaApi().add(addMedia.getHref(), sourceMedia);
  452. Link uploadLink = getFirst(getFirst(media.getFiles(), null).getLinks(), null);
  453. context.getApi().getUploadApi().upload(uploadLink.getHref(), Payloads.newByteArrayPayload(iso));
  454. media = context.getApi().getMediaApi().get(media.getId());
  455. if (media.getTasks().size() == 1) {
  456. Task uploadTask = Iterables.getOnlyElement(media.getTasks());
  457. Checks.checkTask(uploadTask);
  458. assertEquals(uploadTask.getStatus(), Task.Status.RUNNING);
  459. assertTrue(retryTaskSuccess.apply(uploadTask), String.format(TASK_COMPLETE_TIMELY, "uploadTask"));
  460. media = context.getApi().getMediaApi().get(media.getId());
  461. }
  462. mediaUrn = media.getId();
  463. } else
  464. media = context.getApi().getMediaApi().get(mediaUrn);
  465. }
  466. return media;
  467. }
  468. protected VAppTemplate lazyGetVAppTemplate() {
  469. if (vAppTemplate == null) {
  470. assertNotNull(vAppTemplateUrn, String.format(URN_REQ_LIVE, VAPP_TEMPLATE));
  471. vAppTemplate = adminContext.getApi().getVAppTemplateApi().get(vAppTemplateUrn);
  472. assertNotNull(vAppTemplate, String.format(ENTITY_NON_NULL, VAPP_TEMPLATE));
  473. }
  474. return vAppTemplate;
  475. }
  476. protected void assertTaskSucceeds(Task task) {
  477. assertTrue(retryTaskSuccess.apply(task), String.format(TASK_COMPLETE_TIMELY, task));
  478. }
  479. protected void assertTaskSucceedsLong(Task task) {
  480. assertTrue(retryTaskSuccessLong.apply(task), String.format(TASK_COMPLETE_TIMELY, task));
  481. }
  482. protected boolean taskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
  483. TaskApi taskApi = context.getApi().getTaskApi();
  484. TaskStatusEquals predicate = new TaskStatusEquals(taskApi, running, immutableSet);
  485. return retry(predicate, TASK_TIMEOUT_SECONDS * 1000L).apply(task);
  486. }
  487. protected void assertTaskStatusEventually(Task task, Task.Status running, ImmutableSet<Task.Status> immutableSet) {
  488. assertTrue(taskStatusEventually(task, running, immutableSet),
  489. String.format("Task '%s' must reach status %s", task.getOperationName(), running));
  490. }
  491. protected boolean taskDoneEventually(Task task) {
  492. TaskApi taskApi = context.getApi().getTaskApi();
  493. TaskStatusEquals predicate = new TaskStatusEquals(taskApi, ImmutableSet.of(Task.Status.ABORTED,
  494. Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS), ImmutableSet.<Task.Status> of());
  495. return retry(predicate, TASK_TIMEOUT_SECONDS * 1000L).apply(task);
  496. }
  497. protected void assertTaskDoneEventually(Task task) {
  498. assertTrue(taskDoneEventually(task), String.format("Task '%s' must complete", task.getOperationName()));
  499. }
  500. /**
  501. * Instantiate a {@link VApp} in a {@link Vdc} using the {@link VAppTemplate} we have configured
  502. * for the tests.
  503. *
  504. * @return the VApp that is being instantiated
  505. */
  506. protected VApp instantiateVApp() {
  507. return instantiateVApp(name("test-vapp-"));
  508. }
  509. protected VApp instantiateVApp(String name) {
  510. InstantiateVAppTemplateParams instantiate = InstantiateVAppTemplateParams.builder().name(name).notDeploy()
  511. .notPowerOn().description("Test VApp").instantiationParams(instantiationParams())
  512. .source(Reference.builder().href(lazyGetVAppTemplate().getHref()).build()).build();
  513. VdcApi vdcApi = context.getApi().getVdcApi();
  514. VApp vAppInstantiated = vdcApi.instantiateVApp(vdcUrn, instantiate);
  515. assertNotNull(vAppInstantiated, String.format(ENTITY_NON_NULL, VAPP));
  516. Task instantiationTask = getFirst(vAppInstantiated.getTasks(), null);
  517. if (instantiationTask != null)
  518. assertTaskSucceedsLong(instantiationTask);
  519. // Save VApp name for cleanUp
  520. vAppNames.add(name);
  521. return vAppInstantiated;
  522. }
  523. /** Build an {@link InstantiationParams} object. */
  524. protected InstantiationParams instantiationParams() {
  525. InstantiationParams instantiationParams = InstantiationParams.builder()
  526. .sections(ImmutableSet.of(networkConfigSection())).build();
  527. return instantiationParams;
  528. }
  529. /** Build a {@link NetworkConfigSection} object. */
  530. private NetworkConfigSection networkConfigSection() {
  531. NetworkConfigSection networkConfigSection = NetworkConfigSection
  532. .builder()
  533. .info("Configuration parameters for logical networks")
  534. .networkConfigs(
  535. ImmutableSet.of(VAppNetworkConfiguration.builder()
  536. .networkName("vAppNetwork")
  537. .configuration(networkConfiguration()).build())).build();
  538. return networkConfigSection;
  539. }
  540. /** Build a {@link NetworkConfiguration} object. */
  541. private NetworkConfiguration networkConfiguration() {
  542. Vdc vdc = context.getApi().getVdcApi().get(vdcUrn);
  543. assertNotNull(vdc, String.format(ENTITY_NON_NULL, VDC));
  544. Set<Reference> networks = vdc.getAvailableNetworks();
  545. network = lazyGetNetwork();
  546. // Look up the network in the Vdc with the id configured for the tests
  547. Optional<Reference> parentNetwork = tryFind(networks, new Predicate<Reference>() {
  548. @Override
  549. public boolean apply(Reference reference) {
  550. return reference.getHref().equals(network.getHref());
  551. }
  552. });
  553. // Check we actually found a network reference
  554. if (!parentNetwork.isPresent()) {
  555. fail(String.format("Could not find network %s in vdc", network.getHref().toASCIIString()));
  556. }
  557. // Build the configuration object
  558. NetworkConfiguration networkConfiguration = NetworkConfiguration.builder().parentNetwork(parentNetwork.get())
  559. .fenceMode(Network.FenceMode.BRIDGED).build();
  560. return networkConfiguration;
  561. }
  562. protected void cleanUpVAppTemplate(VAppTemplate vAppTemplate) {
  563. VAppTemplateApi vappTemplateApi = context.getApi().getVAppTemplateApi();
  564. try {
  565. Task task = vappTemplateApi.remove(vAppTemplate.getId());
  566. taskDoneEventually(task);
  567. } catch (Exception e) {
  568. logger.warn(e, "Error deleting template '%s'", vAppTemplate.getName());
  569. }
  570. }
  571. protected void cleanUpVApp(VApp vApp) {
  572. VAppApi vAppApi = context.getApi().getVAppApi();
  573. String vAppUrn = vApp.getId();
  574. vApp = vAppApi.get(vAppUrn); // Refresh
  575. if (vApp == null) {
  576. logger.info("Cannot find VApp at %s", vAppUrn);
  577. return; // Presumably vApp has already been removed. Ignore.
  578. }
  579. logger.debug("Deleting VApp %s (%s)", vApp.getName(), vAppUrn);
  580. // Wait for busy tasks to complete (don't care if it's failed or successful)
  581. // Otherwise, get error on remove "entity is busy completing an operation.
  582. if (vApp.getTasks() != null) {
  583. for (Task task : vApp.getTasks()) {
  584. if (!taskDoneEventually(task)) {
  585. logger.warn("Task '%s' did not complete", task.getOperationName());
  586. }
  587. }
  588. }
  589. // power off the VApp if necessary
  590. if (vApp.getStatus() == Status.POWERED_ON) {
  591. try {
  592. Task shutdownTask = vAppApi.powerOff(vAppUrn);
  593. taskDoneEventually(shutdownTask);
  594. } catch (Exception e) {
  595. // keep going; cleanup as much as possible
  596. logger.warn(e, "Continuing cleanup after error shutting down VApp %s", vApp.getName());
  597. }
  598. }
  599. // Undeploy the VApp if necessary
  600. if (vApp.isDeployed()) {
  601. try {
  602. UndeployVAppParams params = UndeployVAppParams.builder()
  603. .undeployPowerAction(UndeployVAppParams.PowerAction.SHUTDOWN).build();
  604. Task undeployTask = vAppApi.undeploy(vAppUrn, params);
  605. taskDoneEventually(undeployTask);
  606. } catch (Exception e) {
  607. // keep going; cleanup as much as possible
  608. logger.warn(e, "Continuing cleanup after error undeploying VApp %s", vApp.getName());
  609. }
  610. }
  611. try {
  612. Task task = vAppApi.remove(vAppUrn);
  613. taskDoneEventually(task);
  614. vAppNames.remove(vApp.getName());
  615. logger.info("Deleted VApp %s", vApp.getName());
  616. } catch (Exception e) {
  617. vApp = vAppApi.get(vApp.getId()); // Refresh
  618. logger.warn(e, "Deleting VApp %s failed (%s)", vApp.getName(), vAppUrn);
  619. }
  620. }
  621. public static String name(String prefix) {
  622. return prefix + Integer.toString(random.nextInt(Integer.MAX_VALUE));
  623. }
  624. @Override
  625. protected TypeToken<VCloudDirectorContext> contextType() {
  626. return VCloudDirectorApiMetadata.CONTEXT_TOKEN;
  627. }
  628. }