First part of onap rename
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / test / java / org / openecomp / appc / adapter / iaas / impl / TestProviderAdapterImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.iaas.impl;
26
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertNotNull;
29 import static org.junit.Assert.assertNull;
30 import static org.junit.Assert.assertTrue;
31 import static org.junit.Assert.fail;
32 import java.io.IOException;
33 import java.lang.reflect.Field;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.Set;
39 import org.junit.Before;
40 import org.junit.BeforeClass;
41 import org.junit.Ignore;
42 import org.junit.Test;
43 import org.junit.experimental.categories.Category;
44 import org.onap.appc.Constants;
45 import org.onap.appc.adapter.iaas.ProviderAdapter;
46 import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl;
47 import org.onap.appc.adapter.iaas.impl.ProviderCache;
48 import org.onap.appc.adapter.iaas.impl.ServiceCatalog;
49 import org.onap.appc.adapter.iaas.impl.TenantCache;
50 import org.onap.appc.adapter.iaas.impl.VMURL;
51 import org.onap.appc.configuration.ConfigurationFactory;
52 import org.onap.appc.exceptions.APPCException;
53 import org.onap.appc.exceptions.UnknownProviderException;
54 import com.att.cdp.exceptions.ZoneException;
55 import com.att.cdp.zones.ComputeService;
56 import com.att.cdp.zones.Context;
57 import com.att.cdp.zones.ContextFactory;
58 import com.att.cdp.zones.model.Image;
59 import com.att.cdp.zones.model.Server;
60 import com.att.cdp.zones.model.Server.Status;
61 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
62 import com.woorea.openstack.keystone.model.Access.Service.Endpoint;
63
64 /**
65  * Test the ProviderAdapter implementation.
66  */
67 @Category(org.onap.appc.adapter.iaas.impl.TestProviderAdapterImpl.class)
68 public class TestProviderAdapterImpl {
69
70     @SuppressWarnings("nls")
71     private static final String PROVIDER_NAME = "ILAB";
72
73     @SuppressWarnings("nls")
74     private static final String PROVIDER_TYPE = "OpenStackProvider";
75
76     private static String IDENTITY_URL;
77
78     private static String PRINCIPAL;
79
80     private static String CREDENTIAL;
81
82     private static String TENANT_NAME;
83
84     private static String TENANT_ID;
85
86     private static String USER_ID;
87
88     private static String REGION_NAME;
89
90     private static String SERVER_URL;
91
92     private static Class<?> providerAdapterImplClass;
93     private static Class<?> configurationFactoryClass;
94     private static Field providerCacheField;
95     private static Field configField;
96
97     private ProviderAdapterImpl adapter;
98
99     /**
100      * Use reflection to locate fields and methods so that they can be manipulated during the test
101      * to change the internal state accordingly.
102      * 
103      * @throws NoSuchFieldException if the field(s) dont exist
104      * @throws SecurityException if reflective access is not allowed
105      * @throws NoSuchMethodException If the method(s) dont exist
106      */
107     @SuppressWarnings("nls")
108     @BeforeClass
109     public static void once() throws NoSuchFieldException, SecurityException, NoSuchMethodException {
110         providerAdapterImplClass = ProviderAdapterImpl.class;
111         configurationFactoryClass = ConfigurationFactory.class;
112
113         providerCacheField = providerAdapterImplClass.getDeclaredField("providerCache");
114         providerCacheField.setAccessible(true);
115
116         configField = configurationFactoryClass.getDeclaredField("config");
117         configField.setAccessible(true);
118
119         Properties props = ConfigurationFactory.getConfiguration().getProperties();
120         IDENTITY_URL = props.getProperty("provider1.identity");
121         PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc");
122         CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc");
123         TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc");
124         TENANT_ID = props.getProperty("provider1.tenant1.id", "abcde12345fghijk6789lmnopq123rst");
125         REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne");
126         SERVER_URL = props.getProperty("test.url");
127     }
128
129     /**
130      * Setup the test environment.
131      * 
132      * @throws IllegalAccessException if this Field object is enforcing Java language access control
133      *         and the underlying field is either inaccessible or final.
134      * @throws IllegalArgumentException if the specified object is not an instance of the class or
135      *         interface declaring the underlying field (or a subclass or implementor thereof), or
136      *         if an unwrapping conversion fails.
137      * @throws NullPointerException if the specified object is null and the field is an instance
138      *         field.
139      * @throws ExceptionInInitializerError if the initialization provoked by this method fails.
140      */
141     @Before
142     public void setup() throws IllegalArgumentException, IllegalAccessException {
143         configField.set(null, null);
144         Properties properties = new Properties();
145         adapter = new ProviderAdapterImpl(properties);
146     }
147
148     /**
149      * This method inspects the provider adapter implementation to make sure that the cache of
150      * providers and tenants, as well as the service catalog, and all pools of contexts have been
151      * set up correctly.
152      * 
153      * @throws IllegalAccessException if this Field object is enforcing Java language access control
154      *         and the underlying field is inaccessible.
155      * @throws IllegalArgumentException if the specified object is not an instance of the class or
156      *         interface declaring the underlying field (or a subclass or implementor thereof).
157      */
158     @SuppressWarnings({"unchecked"})
159     @Ignore
160     @Test
161     public void validateCacheIsCreatedCorrectly() throws IllegalArgumentException, IllegalAccessException {
162         Map<String, ProviderCache> providerCaches = (Map<String, ProviderCache>) providerCacheField.get(adapter);
163
164         assertNotNull(providerCaches);
165         assertEquals(1, providerCaches.size());
166         assertTrue(providerCaches.containsKey(PROVIDER_NAME));
167
168         ProviderCache providerCache = providerCaches.get(PROVIDER_NAME);
169         assertEquals(PROVIDER_NAME, providerCache.getProviderName());
170         assertEquals(PROVIDER_TYPE, providerCache.getProviderType());
171
172         Map<String, TenantCache> tenantCaches = providerCache.getTenants();
173         assertNotNull(tenantCaches);
174         assertEquals(1, tenantCaches.size());
175         assertTrue(tenantCaches.containsKey(TENANT_NAME));
176
177         TenantCache tenantCache = tenantCaches.get(TENANT_NAME);
178
179         assertEquals(TENANT_ID, tenantCache.getTenantId());
180         assertEquals(TENANT_NAME, tenantCache.getTenantName());
181         assertEquals(USER_ID, tenantCache.getUserid());
182
183         ServiceCatalog catalog = tenantCache.getServiceCatalog();
184         assertNotNull(catalog);
185
186         System.out.println(catalog.toString());
187         List<String> serviceTypes = catalog.getServiceTypes();
188         assertNotNull(serviceTypes);
189         assertEquals(12, serviceTypes.size());
190
191         assertEquals(TENANT_NAME, catalog.getProjectName());
192         assertEquals(TENANT_ID, catalog.getProjectId());
193
194         Set<String> regionNames = catalog.getRegions();
195         assertNotNull(regionNames);
196         assertEquals(1, regionNames.size());
197         assertTrue(regionNames.contains(REGION_NAME));
198
199         List<?> endpoints = catalog.getEndpoints(ServiceCatalog.IDENTITY_SERVICE);
200         assertNotNull(endpoints);
201         assertEquals(1, endpoints.size());
202         Endpoint endpoint = (Endpoint) endpoints.get(0);
203         assertNotNull(endpoint);
204         assertEquals(REGION_NAME, endpoint.getRegion());
205         assertEquals(IDENTITY_URL, endpoint.getPublicURL());
206
207         endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE);
208         assertNotNull(endpoints);
209         assertEquals(1, endpoints.size());
210         endpoint = (Endpoint) endpoints.get(0);
211         assertNotNull(endpoint);
212         assertEquals(REGION_NAME, endpoint.getRegion());
213
214         endpoints = catalog.getEndpoints(ServiceCatalog.VOLUME_SERVICE);
215         assertNotNull(endpoints);
216         assertEquals(1, endpoints.size());
217         endpoint = (Endpoint) endpoints.get(0);
218         assertNotNull(endpoint);
219         assertEquals(REGION_NAME, endpoint.getRegion());
220
221         endpoints = catalog.getEndpoints(ServiceCatalog.IMAGE_SERVICE);
222         assertNotNull(endpoints);
223         assertEquals(1, endpoints.size());
224         endpoint = (Endpoint) endpoints.get(0);
225         assertNotNull(endpoint);
226         assertEquals(REGION_NAME, endpoint.getRegion());
227
228         endpoints = catalog.getEndpoints(ServiceCatalog.NETWORK_SERVICE);
229         assertNotNull(endpoints);
230         assertEquals(1, endpoints.size());
231         endpoint = (Endpoint) endpoints.get(0);
232         assertNotNull(endpoint);
233         assertEquals(REGION_NAME, endpoint.getRegion());
234
235         assertTrue(catalog.isServicePublished(ServiceCatalog.IDENTITY_SERVICE));
236         assertTrue(catalog.isServicePublished(ServiceCatalog.COMPUTE_SERVICE));
237         assertTrue(catalog.isServicePublished(ServiceCatalog.VOLUME_SERVICE));
238         assertTrue(catalog.isServicePublished(ServiceCatalog.IMAGE_SERVICE));
239         assertTrue(catalog.isServicePublished(ServiceCatalog.NETWORK_SERVICE));
240     }
241
242     /**
243      * This test case is used to actually validate that a server has been restarted from an already
244      * running state
245      * 
246      * @throws ZoneException If the login cannot be performed because the principal and/or
247      *         credentials are invalid.
248      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
249      *         the expected argument(s) are not defined or are invalid
250      * @throws IllegalStateException If the identity service is not available or cannot be created
251      * @throws IOException if an I/O error occurs
252      * @throws APPCException
253      */
254     // @Ignore
255     @Test
256     public void testRestartRunningServer()
257             throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
258         Properties properties = new Properties();
259         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
260         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
261         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
262         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
263         properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true");
264
265         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
266             context.login(PRINCIPAL, CREDENTIAL);
267             VMURL vm = VMURL.parseURL(SERVER_URL);
268
269             ComputeService computeService = context.getComputeService();
270             Server server = computeService.getServer(vm.getServerId());
271             if (!server.getStatus().equals(Status.RUNNING)) {
272                 server.start();
273                 assertTrue(waitForStateChange(server, Status.RUNNING));
274             }
275
276             Map<String, String> params = new HashMap<>();
277             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
278             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
279             SvcLogicContext svcContext = new SvcLogicContext();
280
281             server = adapter.restartServer(params, svcContext);
282
283             assertEquals(Server.Status.RUNNING, server.getStatus());
284         }
285     }
286
287
288     /****************************************/
289     /**
290      * Tests that the vmStatuschecker method works and returns the correct status of the VM
291      * requested
292      * 
293      * @throws ZoneException If the login cannot be performed because the principal and/or
294      *         credentials are invalid.
295      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
296      *         the expected argument(s) are not defined or are invalid
297      * @throws IllegalStateException If the identity service is not available or cannot be created
298      * @throws IOException if an I/O error occurs
299      * @throws UnknownProviderException If the provider cannot be found
300      */
301     // @Ignore
302     @Test
303     public void testVmStatuschecker() throws IllegalStateException, IllegalArgumentException, ZoneException,
304             UnknownProviderException, IOException {
305         Properties properties = new Properties();
306         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
307         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
308         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
309         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
310         properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true");
311
312         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
313             context.login(PRINCIPAL, CREDENTIAL);
314             VMURL vm = VMURL.parseURL(SERVER_URL);
315
316             ComputeService computeService = context.getComputeService();
317             Server server = computeService.getServer(vm.getServerId());
318             if (!server.getStatus().equals(Status.RUNNING)) {
319                 server.start();
320                 assertTrue(waitForStateChange(server, Status.RUNNING));
321             }
322             // or instead of the if-block, can ensureRunning(server) be used?
323             ensureRunning(server);
324             assertEquals(Server.Status.RUNNING, server.getStatus());
325         }
326     }
327
328     /****************************************/
329
330
331     /**
332      * Tests that we can restart a server that is already stopped
333      * 
334      * @throws ZoneException If the login cannot be performed because the principal and/or
335      *         credentials are invalid.
336      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
337      *         the expected argument(s) are not defined or are invalid.
338      * @throws IllegalStateException If the identity service is not available or cannot be created
339      * @throws IOException if an I/O error occurs
340      * @throws APPCException
341      */
342     // @Ignore
343     @Test
344     public void testRestartStoppedServer()
345             throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
346         Properties properties = new Properties();
347         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
348         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
349         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
350         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
351
352         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
353             context.login(PRINCIPAL, CREDENTIAL);
354             VMURL vm = VMURL.parseURL(SERVER_URL);
355
356             ComputeService computeService = context.getComputeService();
357             Server server = computeService.getServer(vm.getServerId());
358             if (!server.getStatus().equals(Status.READY)) {
359                 server.stop();
360                 assertTrue(waitForStateChange(server, Status.READY));
361             }
362
363             Map<String, String> params = new HashMap<>();
364             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
365             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
366             SvcLogicContext svcContext = new SvcLogicContext();
367
368             server = adapter.restartServer(params, svcContext);
369
370             assertEquals(Server.Status.RUNNING, server.getStatus());
371
372         }
373     }
374
375     /**
376      * Tests that we can rebuild a running server (not created from a bootable volume)
377      * 
378      * @throws ZoneException If the login cannot be performed because the principal and/or
379      *         credentials are invalid.
380      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
381      *         the expected argument(s) are not defined or are invalid.
382      * @throws IllegalStateException If the identity service is not available or cannot be created
383      * @throws UnknownProviderException If the provider cannot be found
384      * @throws IOException if an I/O error occurs
385      * @throws APPCException If the server cannot be rebuilt for some reason
386      */
387     // @Ignore
388     @Test
389     public void testRebuildRunningServer()
390             throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
391         Properties properties = new Properties();
392         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
393         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
394         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
395         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
396
397         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
398             context.login(PRINCIPAL, CREDENTIAL);
399             VMURL vm = VMURL.parseURL(SERVER_URL);
400
401             ComputeService computeService = context.getComputeService();
402             Server server = computeService.getServer(vm.getServerId());
403             ensureRunning(server);
404
405             Map<String, String> params = new HashMap<>();
406             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
407             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
408             SvcLogicContext svcContext = new SvcLogicContext();
409
410             server = adapter.rebuildServer(params, svcContext);
411             assertTrue(waitForStateChange(server, Status.RUNNING));
412
413         }
414     }
415
416     /**
417      * Tests that we can rebuild a paused server (not created from a bootable volume)
418      * 
419      * @throws ZoneException If the login cannot be performed because the principal and/or
420      *         credentials are invalid.
421      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
422      *         the expected argument(s) are not defined or are invalid.
423      * @throws IllegalStateException If the identity service is not available or cannot be created
424      * @throws UnknownProviderException If the provider cannot be found
425      * @throws IOException if an I/O error occurs
426      * @throws APPCException If the server cannot be rebuilt for some reason
427      */
428     // @Ignore
429     @Test
430     public void testRebuildPausedServer()
431             throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
432         Properties properties = new Properties();
433         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
434         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
435         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
436         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
437
438         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
439             context.login(PRINCIPAL, CREDENTIAL);
440             VMURL vm = VMURL.parseURL(SERVER_URL);
441
442             ComputeService computeService = context.getComputeService();
443             Server server = computeService.getServer(vm.getServerId());
444             ensurePaused(server);
445
446             Map<String, String> params = new HashMap<>();
447             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
448             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
449             SvcLogicContext svcContext = new SvcLogicContext();
450
451             server = adapter.rebuildServer(params, svcContext);
452             assertTrue(waitForStateChange(server, Status.RUNNING));
453         }
454     }
455
456     /**
457      * Tests that we can rebuild a paused server (not created from a bootable volume)
458      * 
459      * @throws ZoneException If the login cannot be performed because the principal and/or
460      *         credentials are invalid.
461      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
462      *         the expected argument(s) are not defined or are invalid.
463      * @throws IllegalStateException If the identity service is not available or cannot be created
464      * @throws UnknownProviderException If the provider cannot be found
465      * @throws IOException if an I/O error occurs
466      * @throws APPCException If the server cannot be rebuilt for some reason
467      */
468     // @Ignore
469     @Test
470     public void testRebuildSuspendedServer()
471             throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
472         Properties properties = new Properties();
473         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
474         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
475         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
476         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
477
478         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
479             context.login(PRINCIPAL, CREDENTIAL);
480             VMURL vm = VMURL.parseURL(SERVER_URL);
481
482             ComputeService computeService = context.getComputeService();
483             Server server = computeService.getServer(vm.getServerId());
484             ensureSuspended(server);
485
486             Map<String, String> params = new HashMap<>();
487             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
488             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
489             SvcLogicContext svcContext = new SvcLogicContext();
490
491             server = adapter.rebuildServer(params, svcContext);
492             assertTrue(waitForStateChange(server, Status.RUNNING));
493         }
494     }
495
496     /**
497      * Tests that we can rebuild a paused server (not created from a bootable volume)
498      * 
499      * @throws ZoneException If the login cannot be performed because the principal and/or
500      *         credentials are invalid.
501      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
502      *         the expected argument(s) are not defined or are invalid.
503      * @throws IllegalStateException If the identity service is not available or cannot be created
504      * @throws UnknownProviderException If the provider cannot be found
505      * @throws IOException if an I/O error occurs
506      * @throws APPCException If the server cannot be rebuilt for some reason
507      */
508     // @Ignore
509     @Test
510     public void testRebuildStoppedServer()
511             throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
512         Properties properties = new Properties();
513         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
514         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
515         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
516         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
517
518         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
519             context.login(PRINCIPAL, CREDENTIAL);
520             VMURL vm = VMURL.parseURL(SERVER_URL);
521
522             ComputeService computeService = context.getComputeService();
523             Server server = computeService.getServer(vm.getServerId());
524             ensureStopped(server);
525
526             Map<String, String> params = new HashMap<>();
527             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
528             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
529             SvcLogicContext svcContext = new SvcLogicContext();
530
531             server = adapter.rebuildServer(params, svcContext);
532             assertTrue(waitForStateChange(server, Status.RUNNING));
533         }
534     }
535
536     /**
537      * Test subsequent action on second vm in different Tenant resulting in {"itemNotFound":
538      * {"message": "Instance could not be found", "code": 404}}
539      * 
540      * @throws ZoneException If the login cannot be performed because the principal and/or
541      *         credentials are invalid.
542      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
543      *         the expected argument(s) are not defined or are invalid
544      * @throws IllegalStateException If the identity service is not available or cannot be created
545      * @throws IOException if an I/O error occurs
546      * @throws APPCException
547      */
548
549     @Test
550     public void testTenantVerification()
551             throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
552
553         Properties properties = new Properties();
554         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000");
555         properties.setProperty(ContextFactory.PROPERTY_TENANT, "APP-C");
556         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
557
558         String vmUrl =
559                 "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
560
561         // try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
562         // context.login("AppC", "AppC");
563
564         // call lookupServer on vm in defined tenant "APP-C_TLV"
565         VMURL vm = VMURL.parseURL(vmUrl);
566
567         Map<String, String> params = new HashMap<>();
568         params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
569         params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0");
570         params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0");
571         SvcLogicContext svcContext = new SvcLogicContext();
572
573         long start, end = 0;
574
575         System.out.println("\n--------------------Begin lookupServer on tenant 1--------------------");
576         start = System.currentTimeMillis();
577         Server server = adapter.lookupServer(params, svcContext);
578         end = System.currentTimeMillis();
579
580         System.out.println(String.format("lookupServer on tenant 1 took %ds", (end - start) / 1000));
581         System.out.println("----------------------------------------------------------------------\n");
582         assertNotNull(server);
583
584         // repeat to show that context is reused for second request
585         System.out.println("\n-----------------Begin repeat lookupServer on tenant 1----------------");
586         start = System.currentTimeMillis();
587         server = adapter.lookupServer(params, svcContext);
588         end = System.currentTimeMillis();
589
590         System.out.println(String.format("Repeat lookupServer on tenant 1 took %ds", (end - start) / 1000));
591         System.out.println("----------------------------------------------------------------------\n");
592         assertNotNull(server);
593
594         // call lookupServer on vm in second tenant "Play"
595         // This is where we would fail due to using the previous
596         // tenants context
597         vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
598         vm = VMURL.parseURL(vmUrl);
599         params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
600
601         System.out.println("\n--------------------Begin lookupServer on tenant 2--------------------");
602         start = System.currentTimeMillis();
603         server = adapter.lookupServer(params, svcContext);
604         end = System.currentTimeMillis();
605         System.out.println(String.format("\nlookupServer on tenant 2 took %ds", (end - start) / 1000));
606         System.out.println("----------------------------------------------------------------------\n");
607         assertNotNull(server);
608
609         // call lookupServer on vm in non-existing tenant
610         vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
611         vm = VMURL.parseURL(vmUrl);
612         params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
613
614         System.out.println("\n--------------Begin lookupServer on non-existant tenant--------------");
615         start = System.currentTimeMillis();
616         server = adapter.lookupServer(params, svcContext);
617         end = System.currentTimeMillis();
618         System.out.println(String.format("\nlookupServer on tenant 3 took %ds", (end - start) / 1000));
619         System.out.println("----------------------------------------------------------------------\n");
620         assertNull(server);
621
622         // }
623     }
624
625     /****************************************/
626
627
628     @Test
629     public void testSnapshotServer() throws Exception {
630         Properties properties = new Properties();
631         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000");
632         // properties.setProperty(ContextFactory.PROPERTY_REGION, "");
633         properties.setProperty(ContextFactory.PROPERTY_TENANT, "Play");
634         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
635
636         String vmUrl =
637                 "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
638
639         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
640             context.login("AppC", "AppC");
641             VMURL vm = VMURL.parseURL(vmUrl);
642
643             Map<String, String> params = new HashMap<>();
644             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
645             params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0");
646             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0");
647             SvcLogicContext svcContext = new SvcLogicContext();
648
649             long start, end = 0;
650
651             start = System.currentTimeMillis();
652             Image image = adapter.createSnapshot(params, svcContext);
653             end = System.currentTimeMillis();
654
655             System.out.println(String.format("Image ID: %s", image.getId()));
656             System.out.println(String.format("Snapshot took %ds", (end - start) / 1000));
657
658             start = System.currentTimeMillis();
659             adapter.rebuildServer(params, svcContext);
660             end = System.currentTimeMillis();
661             System.out.println(String.format("Rebuild took %ds", (end - start) / 1000));
662         }
663
664     }
665
666     /**
667      * Ensures that the server is in stopped (shutdown) state prior to test
668      * 
669      * @param server The server to ensure is stopped
670      * @throws ZoneException If the server can't be operated upon for some reason
671      */
672     @SuppressWarnings("nls")
673     private static void ensureStopped(Server server) throws ZoneException {
674         switch (server.getStatus()) {
675             case READY:
676                 break;
677
678             case PENDING:
679                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
680                         Server.Status.SUSPENDED, Server.Status.ERROR);
681                 ensureSuspended(server);
682                 break;
683
684             case PAUSED:
685                 server.unpause();
686                 waitForStateChange(server, Server.Status.RUNNING);
687                 server.stop();
688                 waitForStateChange(server, Server.Status.READY);
689                 break;
690
691             case SUSPENDED:
692                 server.resume();
693                 waitForStateChange(server, Server.Status.RUNNING);
694                 server.stop();
695                 waitForStateChange(server, Server.Status.READY);
696                 break;
697
698             case RUNNING:
699                 server.stop();
700                 waitForStateChange(server, Server.Status.READY);
701                 break;
702
703             case DELETED:
704             case ERROR:
705             default:
706                 fail("Server state is not valid for test - " + server.getStatus().name());
707         }
708     }
709
710     /**
711      * Ensures that the server is in suspended state prior to test
712      * 
713      * @param server The server to ensure is suspended
714      * @throws ZoneException If the server can't be operated upon for some reason
715      */
716     @SuppressWarnings("nls")
717     private static void ensureSuspended(Server server) throws ZoneException {
718         switch (server.getStatus()) {
719             case SUSPENDED:
720                 break;
721
722             case PENDING:
723                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
724                         Server.Status.SUSPENDED, Server.Status.ERROR);
725                 ensureSuspended(server);
726                 break;
727
728             case PAUSED:
729                 server.unpause();
730                 waitForStateChange(server, Server.Status.RUNNING);
731                 server.suspend();
732                 waitForStateChange(server, Server.Status.SUSPENDED);
733                 break;
734
735             case READY:
736                 server.start();
737                 waitForStateChange(server, Server.Status.RUNNING);
738                 server.suspend();
739                 waitForStateChange(server, Server.Status.SUSPENDED);
740                 break;
741
742             case RUNNING:
743                 server.suspend();
744                 waitForStateChange(server, Server.Status.SUSPENDED);
745                 break;
746
747             case DELETED:
748             case ERROR:
749             default:
750                 fail("Server state is not valid for test - " + server.getStatus().name());
751         }
752     }
753
754     /**
755      * This method makes sure that the indicated server is running before performing a test
756      * 
757      * @param server The server to ensure is running
758      * @throws ZoneException If the server can't be operated upon
759      */
760     @SuppressWarnings("nls")
761     private static void ensureRunning(Server server) throws ZoneException {
762         switch (server.getStatus()) {
763             case RUNNING:
764                 break;
765
766             case PENDING:
767                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
768                         Server.Status.SUSPENDED, Server.Status.ERROR);
769                 ensureRunning(server);
770                 break;
771
772             case PAUSED:
773                 server.unpause();
774                 waitForStateChange(server, Server.Status.RUNNING);
775                 break;
776
777             case SUSPENDED:
778                 server.resume();
779                 waitForStateChange(server, Server.Status.RUNNING);
780                 break;
781
782             case READY:
783                 server.start();
784                 waitForStateChange(server, Server.Status.RUNNING);
785                 break;
786
787             case DELETED:
788             case ERROR:
789             default:
790                 fail("Server state is not valid for test - " + server.getStatus().name());
791         }
792     }
793
794     /**
795      * This method will make sure that the server we are testing is paused
796      * 
797      * @param server The server to make sure is paused for the test
798      * @throws ZoneException If anything fails
799      */
800     @SuppressWarnings("nls")
801     private static void ensurePaused(Server server) throws ZoneException {
802         switch (server.getStatus()) {
803             case PAUSED:
804                 break;
805
806             case PENDING:
807                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
808                         Server.Status.SUSPENDED, Server.Status.ERROR);
809                 ensurePaused(server);
810                 break;
811
812             case READY:
813                 server.start();
814                 waitForStateChange(server, Server.Status.RUNNING);
815                 server.pause();
816                 waitForStateChange(server, Server.Status.PAUSED);
817                 break;
818
819             case RUNNING:
820                 server.pause();
821                 waitForStateChange(server, Server.Status.PAUSED);
822                 break;
823
824             case SUSPENDED:
825                 server.resume();
826                 waitForStateChange(server, Server.Status.RUNNING);
827                 server.pause();
828                 waitForStateChange(server, Server.Status.PAUSED);
829                 break;
830
831             case ERROR:
832             case DELETED:
833             default:
834                 fail("Server state is not valid for test - " + server.getStatus().name());
835         }
836     }
837
838     /**
839      * Enter a pool-wait loop checking the server state to see if it has entered one of the desired
840      * states or not.
841      * <p>
842      * This method checks the state of the server periodically for one of the desired states. When
843      * the server enters one of the desired states, the method returns a successful indication
844      * (true). If the server never enters one of the desired states within the alloted timeout
845      * period, then the method returns a failed response (false). No exceptions are thrown from this
846      * method.
847      * </p>
848      * 
849      * @param server The server to wait on
850      * @param desiredStates A variable list of desired states, any one of which is allowed.
851      * @return True if the server entered one of the desired states, and false if not and the wait
852      *         loop timed out.
853      */
854     private static boolean waitForStateChange(Server server, Server.Status... desiredStates) {
855         int timeout = ConfigurationFactory.getConfiguration()
856                 .getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT);
857         long limit = System.currentTimeMillis() + (timeout * 1000);
858         Server vm = server;
859
860         try {
861             while (limit > System.currentTimeMillis()) {
862                 vm.refresh();
863                 for (Server.Status desiredState : desiredStates) {
864                     if (server.getStatus().equals(desiredState)) {
865                         return true;
866                     }
867                 }
868
869                 try {
870                     Thread.sleep(10000L);
871                 } catch (InterruptedException e) {
872                     // ignore
873                 }
874             }
875         } catch (ZoneException e) {
876             e.printStackTrace();
877         }
878
879         return false;
880     }
881
882     /*
883      * @Test public void testTerminateStack() throws IllegalStateException,
884      * IllegalArgumentException, ZoneException, UnknownProviderException, IOException { Properties
885      * properties = new Properties(); properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL,
886      * IDENTITY_URL); properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
887      * properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
888      * properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
889      * properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); try (Context context =
890      * ContextFactory.getContext(PROVIDER_TYPE, properties)) { context.login(PRINCIPAL, CREDENTIAL);
891      * VMURL vm = VMURL.parseURL(SERVER_URL); ComputeService computeService =
892      * context.getComputeService(); Server server = computeService.getServer(vm.getServerId()); if
893      * (!server.getStatus().equals(Status.RUNNING)) { server.start();
894      * assertTrue(waitForStateChange(server, Status.RUNNING)); } Map<String, String> params = new
895      * HashMap<>(); params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
896      * params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); SvcLogicContext svcContext
897      * = new SvcLogicContext(); Stack stack = adapter.terminateStack(params, svcContext);
898      * assertNotNull(stack); } }
899      */
900
901 }