Change nexus values to properties
[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 UnknownProviderException
263      *             If the provider cannot be found
264      */
265     // @Ignore
266     @Test
267     public void testRestartRunningServer()
268         throws IllegalStateException, IllegalArgumentException, ZoneException, UnknownProviderException, IOException {
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 UnknownProviderException
354      *             If the provider cannot be found
355      * @throws IOException
356      *             if an I/O error occurs
357      */
358     // @Ignore
359     @Test
360     public void testRestartStoppedServer()
361         throws IllegalStateException, IllegalArgumentException, ZoneException, UnknownProviderException, IOException {
362         Properties properties = new Properties();
363         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
364         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
365         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
366         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
367
368         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
369             context.login(PRINCIPAL, CREDENTIAL);
370             VMURL vm = VMURL.parseURL(SERVER_URL);
371
372             ComputeService computeService = context.getComputeService();
373             Server server = computeService.getServer(vm.getServerId());
374             if (!server.getStatus().equals(Status.READY)) {
375                 server.stop();
376                 assertTrue(waitForStateChange(server, Status.READY));
377             }
378
379             Map<String, String> params = new HashMap<>();
380             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
381             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
382             SvcLogicContext svcContext = new SvcLogicContext();
383
384             server = adapter.restartServer(params, svcContext);
385
386             assertEquals(Server.Status.RUNNING, server.getStatus());
387
388         }
389     }
390
391     /**
392      * Tests that we can rebuild a running server (not created from a bootable volume)
393      * 
394      * @throws ZoneException
395      *             If the login cannot be performed because the principal and/or credentials are invalid.
396      * @throws IllegalArgumentException
397      *             If the principal and/or credential are null or empty, or if the expected argument(s) are not defined
398      *             or are invalid.
399      * @throws IllegalStateException
400      *             If the identity service is not available or cannot be created
401      * @throws UnknownProviderException
402      *             If the provider cannot be found
403      * @throws IOException
404      *             if an I/O error occurs
405      * @throws APPCException
406      *             If the server cannot be rebuilt for some reason
407      */
408     // @Ignore
409     @Test
410     public void testRebuildRunningServer()
411         throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
412         Properties properties = new Properties();
413         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
414         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
415         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
416         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
417
418         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
419             context.login(PRINCIPAL, CREDENTIAL);
420             VMURL vm = VMURL.parseURL(SERVER_URL);
421
422             ComputeService computeService = context.getComputeService();
423             Server server = computeService.getServer(vm.getServerId());
424             ensureRunning(server);
425
426             Map<String, String> params = new HashMap<>();
427             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
428             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
429             SvcLogicContext svcContext = new SvcLogicContext();
430
431             server = adapter.rebuildServer(params, svcContext);
432             assertTrue(waitForStateChange(server, Status.RUNNING));
433
434         }
435     }
436
437     /**
438      * Tests that we can rebuild a paused server (not created from a bootable volume)
439      * 
440      * @throws ZoneException
441      *             If the login cannot be performed because the principal and/or credentials are invalid.
442      * @throws IllegalArgumentException
443      *             If the principal and/or credential are null or empty, or if the expected argument(s) are not defined
444      *             or are invalid.
445      * @throws IllegalStateException
446      *             If the identity service is not available or cannot be created
447      * @throws UnknownProviderException
448      *             If the provider cannot be found
449      * @throws IOException
450      *             if an I/O error occurs
451      * @throws APPCException
452      *             If the server cannot be rebuilt for some reason
453      */
454     // @Ignore
455     @Test
456     public void testRebuildPausedServer()
457         throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
458         Properties properties = new Properties();
459         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
460         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
461         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
462         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
463
464         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
465             context.login(PRINCIPAL, CREDENTIAL);
466             VMURL vm = VMURL.parseURL(SERVER_URL);
467
468             ComputeService computeService = context.getComputeService();
469             Server server = computeService.getServer(vm.getServerId());
470             ensurePaused(server);
471
472             Map<String, String> params = new HashMap<>();
473             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
474             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
475             SvcLogicContext svcContext = new SvcLogicContext();
476
477             server = adapter.rebuildServer(params, svcContext);
478             assertTrue(waitForStateChange(server, Status.RUNNING));
479         }
480     }
481
482     /**
483      * Tests that we can rebuild a paused server (not created from a bootable volume)
484      * 
485      * @throws ZoneException
486      *             If the login cannot be performed because the principal and/or credentials are invalid.
487      * @throws IllegalArgumentException
488      *             If the principal and/or credential are null or empty, or if the expected argument(s) are not defined
489      *             or are invalid.
490      * @throws IllegalStateException
491      *             If the identity service is not available or cannot be created
492      * @throws UnknownProviderException
493      *             If the provider cannot be found
494      * @throws IOException
495      *             if an I/O error occurs
496      * @throws APPCException
497      *             If the server cannot be rebuilt for some reason
498      */
499     // @Ignore
500     @Test
501     public void testRebuildSuspendedServer()
502         throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
503         Properties properties = new Properties();
504         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
505         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
506         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
507         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
508
509         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
510             context.login(PRINCIPAL, CREDENTIAL);
511             VMURL vm = VMURL.parseURL(SERVER_URL);
512
513             ComputeService computeService = context.getComputeService();
514             Server server = computeService.getServer(vm.getServerId());
515             ensureSuspended(server);
516
517             Map<String, String> params = new HashMap<>();
518             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
519             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
520             SvcLogicContext svcContext = new SvcLogicContext();
521
522             server = adapter.rebuildServer(params, svcContext);
523             assertTrue(waitForStateChange(server, Status.RUNNING));
524         }
525     }
526
527     /**
528      * Tests that we can rebuild a paused server (not created from a bootable volume)
529      * 
530      * @throws ZoneException
531      *             If the login cannot be performed because the principal and/or credentials are invalid.
532      * @throws IllegalArgumentException
533      *             If the principal and/or credential are null or empty, or if the expected argument(s) are not defined
534      *             or are invalid.
535      * @throws IllegalStateException
536      *             If the identity service is not available or cannot be created
537      * @throws UnknownProviderException
538      *             If the provider cannot be found
539      * @throws IOException
540      *             if an I/O error occurs
541      * @throws APPCException
542      *             If the server cannot be rebuilt for some reason
543      */
544     // @Ignore
545     @Test
546     public void testRebuildStoppedServer()
547         throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
548         Properties properties = new Properties();
549         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
550         properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
551         properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
552         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
553
554         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
555             context.login(PRINCIPAL, CREDENTIAL);
556             VMURL vm = VMURL.parseURL(SERVER_URL);
557
558             ComputeService computeService = context.getComputeService();
559             Server server = computeService.getServer(vm.getServerId());
560             ensureStopped(server);
561
562             Map<String, String> params = new HashMap<>();
563             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
564             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
565             SvcLogicContext svcContext = new SvcLogicContext();
566
567             server = adapter.rebuildServer(params, svcContext);
568             assertTrue(waitForStateChange(server, Status.RUNNING));
569         }
570     }
571
572     /**
573      * Test subsequent action on second vm in different Tenant resulting in {"itemNotFound": {"message": "Instance could not be found", "code": 404}}
574      * 
575      * @throws ZoneException
576      *             If the login cannot be performed because the principal and/or credentials are invalid.
577      * @throws IllegalArgumentException
578      *             If the principal and/or credential are null or empty, or if the expected argument(s) are not defined
579      *             or are invalid
580      * @throws IllegalStateException
581      *             If the identity service is not available or cannot be created
582      * @throws IOException
583      *             if an I/O error occurs
584      * @throws APPCException 
585      */
586
587     @Test
588     public void testTenantVerification() throws IllegalStateException, IllegalArgumentException, ZoneException,
589         IOException, APPCException {
590         
591         Properties properties = new Properties();
592         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000");
593         properties.setProperty(ContextFactory.PROPERTY_TENANT, "APP-C");
594         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
595
596         String vmUrl =
597             "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
598
599         //try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
600         //    context.login("AppC", "AppC");
601             
602             // call lookupServer on vm in defined tenant "APP-C_TLV"
603             VMURL vm = VMURL.parseURL(vmUrl);
604
605             Map<String, String> params = new HashMap<>();
606             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
607             params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0");
608             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0");
609             SvcLogicContext svcContext = new SvcLogicContext();
610             
611             long start, end = 0;
612
613             System.out.println("\n--------------------Begin lookupServer on tenant 1--------------------");          
614             start = System.currentTimeMillis();
615             Server server = adapter.lookupServer(params, svcContext);
616             end = System.currentTimeMillis();
617             
618             System.out.println(String.format("lookupServer on tenant 1 took %ds", (end - start) / 1000));
619             System.out.println("----------------------------------------------------------------------\n");
620             assertNotNull(server);
621             
622             //repeat to show that context is reused for second request
623             System.out.println("\n-----------------Begin repeat lookupServer on tenant 1----------------");               
624             start = System.currentTimeMillis();
625             server = adapter.lookupServer(params, svcContext);
626             end = System.currentTimeMillis();
627             
628             System.out.println(String.format("Repeat lookupServer on tenant 1 took %ds", (end - start) / 1000));
629             System.out.println("----------------------------------------------------------------------\n");
630             assertNotNull(server);
631             
632             // call lookupServer on vm in second tenant "Play"
633             // This is where we would fail due to using the previous
634             // tenants context
635             vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
636             vm = VMURL.parseURL(vmUrl);
637             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
638             
639             System.out.println("\n--------------------Begin lookupServer on tenant 2--------------------");
640             start = System.currentTimeMillis();
641             server = adapter.lookupServer(params, svcContext);
642             end = System.currentTimeMillis();
643             System.out.println(String.format("\nlookupServer on tenant 2 took %ds", (end - start) / 1000));
644             System.out.println("----------------------------------------------------------------------\n");
645             assertNotNull(server);
646             
647             // call lookupServer on vm in non-existing tenant
648             vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
649             vm = VMURL.parseURL(vmUrl);
650             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
651             
652             System.out.println("\n--------------Begin lookupServer on non-existant tenant--------------");
653             start = System.currentTimeMillis();
654             server = adapter.lookupServer(params, svcContext);
655             end = System.currentTimeMillis();            
656             System.out.println(String.format("\nlookupServer on tenant 3 took %ds", (end - start) / 1000));
657             System.out.println("----------------------------------------------------------------------\n");
658             assertNull(server);
659             
660         //}
661     }
662     /****************************************/
663
664     
665     @Test
666     public void testSnapshotServer() throws Exception {
667         Properties properties = new Properties();
668         properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000");
669         // properties.setProperty(ContextFactory.PROPERTY_REGION, "");
670         properties.setProperty(ContextFactory.PROPERTY_TENANT, "Play");
671         properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
672
673         String vmUrl =
674             "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
675
676         try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
677             context.login("AppC", "AppC");
678             VMURL vm = VMURL.parseURL(vmUrl);
679
680             Map<String, String> params = new HashMap<>();
681             params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
682             params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0");
683             params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0");
684             SvcLogicContext svcContext = new SvcLogicContext();
685
686             long start, end = 0;
687
688             start = System.currentTimeMillis();
689             Image image = adapter.createSnapshot(params, svcContext);
690             end = System.currentTimeMillis();
691
692             System.out.println(String.format("Image ID: %s", image.getId()));
693             System.out.println(String.format("Snapshot took %ds", (end - start) / 1000));
694
695             start = System.currentTimeMillis();
696             adapter.rebuildServer(params, svcContext);
697             end = System.currentTimeMillis();
698             System.out.println(String.format("Rebuild took %ds", (end - start) / 1000));
699         }
700
701     }
702
703     /**
704      * Ensures that the server is in stopped (shutdown) state prior to test
705      * 
706      * @param server
707      *            The server to ensure is stopped
708      * @throws ZoneException
709      *             If the server can't be operated upon for some reason
710      */
711     @SuppressWarnings("nls")
712     private static void ensureStopped(Server server) throws ZoneException {
713         switch (server.getStatus()) {
714             case READY:
715                 break;
716
717             case PENDING:
718                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
719                     Server.Status.SUSPENDED, Server.Status.ERROR);
720                 ensureSuspended(server);
721                 break;
722
723             case PAUSED:
724                 server.unpause();
725                 waitForStateChange(server, Server.Status.RUNNING);
726                 server.stop();
727                 waitForStateChange(server, Server.Status.READY);
728                 break;
729
730             case SUSPENDED:
731                 server.resume();
732                 waitForStateChange(server, Server.Status.RUNNING);
733                 server.stop();
734                 waitForStateChange(server, Server.Status.READY);
735                 break;
736
737             case RUNNING:
738                 server.stop();
739                 waitForStateChange(server, Server.Status.READY);
740                 break;
741
742             case DELETED:
743             case ERROR:
744             default:
745                 fail("Server state is not valid for test - " + server.getStatus().name());
746         }
747     }
748
749     /**
750      * Ensures that the server is in suspended state prior to test
751      * 
752      * @param server
753      *            The server to ensure is suspended
754      * @throws ZoneException
755      *             If the server can't be operated upon for some reason
756      */
757     @SuppressWarnings("nls")
758     private static void ensureSuspended(Server server) throws ZoneException {
759         switch (server.getStatus()) {
760             case SUSPENDED:
761                 break;
762
763             case PENDING:
764                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
765                     Server.Status.SUSPENDED, Server.Status.ERROR);
766                 ensureSuspended(server);
767                 break;
768
769             case PAUSED:
770                 server.unpause();
771                 waitForStateChange(server, Server.Status.RUNNING);
772                 server.suspend();
773                 waitForStateChange(server, Server.Status.SUSPENDED);
774                 break;
775
776             case READY:
777                 server.start();
778                 waitForStateChange(server, Server.Status.RUNNING);
779                 server.suspend();
780                 waitForStateChange(server, Server.Status.SUSPENDED);
781                 break;
782
783             case RUNNING:
784                 server.suspend();
785                 waitForStateChange(server, Server.Status.SUSPENDED);
786                 break;
787
788             case DELETED:
789             case ERROR:
790             default:
791                 fail("Server state is not valid for test - " + server.getStatus().name());
792         }
793     }
794
795     /**
796      * This method makes sure that the indicated server is running before performing a test
797      * 
798      * @param server
799      *            The server to ensure is running
800      * @throws ZoneException
801      *             If the server can't be operated upon
802      */
803     @SuppressWarnings("nls")
804     private static void ensureRunning(Server server) throws ZoneException {
805         switch (server.getStatus()) {
806             case RUNNING:
807                 break;
808
809             case PENDING:
810                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
811                     Server.Status.SUSPENDED, Server.Status.ERROR);
812                 ensureRunning(server);
813                 break;
814
815             case PAUSED:
816                 server.unpause();
817                 waitForStateChange(server, Server.Status.RUNNING);
818                 break;
819
820             case SUSPENDED:
821                 server.resume();
822                 waitForStateChange(server, Server.Status.RUNNING);
823                 break;
824
825             case READY:
826                 server.start();
827                 waitForStateChange(server, Server.Status.RUNNING);
828                 break;
829
830             case DELETED:
831             case ERROR:
832             default:
833                 fail("Server state is not valid for test - " + server.getStatus().name());
834         }
835     }
836
837     /**
838      * This method will make sure that the server we are testing is paused
839      * 
840      * @param server
841      *            The server to make sure is paused for the test
842      * @throws ZoneException
843      *             If anything fails
844      */
845     @SuppressWarnings("nls")
846     private static void ensurePaused(Server server) throws ZoneException {
847         switch (server.getStatus()) {
848             case PAUSED:
849                 break;
850
851             case PENDING:
852                 waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
853                     Server.Status.SUSPENDED, Server.Status.ERROR);
854                 ensurePaused(server);
855                 break;
856
857             case READY:
858                 server.start();
859                 waitForStateChange(server, Server.Status.RUNNING);
860                 server.pause();
861                 waitForStateChange(server, Server.Status.PAUSED);
862                 break;
863
864             case RUNNING:
865                 server.pause();
866                 waitForStateChange(server, Server.Status.PAUSED);
867                 break;
868
869             case SUSPENDED:
870                 server.resume();
871                 waitForStateChange(server, Server.Status.RUNNING);
872                 server.pause();
873                 waitForStateChange(server, Server.Status.PAUSED);
874                 break;
875
876             case ERROR:
877             case DELETED:
878             default:
879                 fail("Server state is not valid for test - " + server.getStatus().name());
880         }
881     }
882
883     /**
884      * Enter a pool-wait loop checking the server state to see if it has entered one of the desired states or not.
885      * <p>
886      * This method checks the state of the server periodically for one of the desired states. When the server enters one
887      * of the desired states, the method returns a successful indication (true). If the server never enters one of the
888      * desired states within the alloted timeout period, then the method returns a failed response (false). No
889      * exceptions are thrown from this method.
890      * </p>
891      * 
892      * @param server
893      *            The server to wait on
894      * @param desiredStates
895      *            A variable list of desired states, any one of which is allowed.
896      * @return True if the server entered one of the desired states, and false if not and the wait loop timed out.
897      */
898     private static boolean waitForStateChange(Server server, Server.Status... desiredStates) {
899         int timeout =
900             ConfigurationFactory.getConfiguration().getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT);
901         long limit = System.currentTimeMillis() + (timeout * 1000);
902         Server vm = server;
903
904         try {
905             while (limit > System.currentTimeMillis()) {
906                 vm.refresh();
907                 for (Server.Status desiredState : desiredStates) {
908                     if (server.getStatus().equals(desiredState)) {
909                         return true;
910                     }
911                 }
912
913                 try {
914                     Thread.sleep(10000L);
915                 } catch (InterruptedException e) {
916                     // ignore
917                 }
918             }
919         } catch (ZoneException e) {
920             e.printStackTrace();
921         }
922
923         return false;
924     }
925
926     /*
927      * @Test public void testTerminateStack() throws IllegalStateException, IllegalArgumentException, ZoneException,
928      * UnknownProviderException, IOException { Properties properties = new Properties();
929      * properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
930      * properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
931      * properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
932      * properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
933      * properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); try (Context context =
934      * ContextFactory.getContext(PROVIDER_TYPE, properties)) { context.login(PRINCIPAL, CREDENTIAL); VMURL vm =
935      * VMURL.parseURL(SERVER_URL); ComputeService computeService = context.getComputeService(); Server server =
936      * computeService.getServer(vm.getServerId()); if (!server.getStatus().equals(Status.RUNNING)) { server.start();
937      * assertTrue(waitForStateChange(server, Status.RUNNING)); } Map<String, String> params = new HashMap<>();
938      * params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL); params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME,
939      * PROVIDER_NAME); SvcLogicContext svcContext = new SvcLogicContext(); Stack stack = adapter.terminateStack(params,
940      * svcContext); assertNotNull(stack); } }
941      */
942
943 }