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