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