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