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