PageRenderTime 41ms CodeModel.GetById 18ms app.highlight 20ms RepoModel.GetById 0ms app.codeStats 0ms

/compute/src/test/java/org/jclouds/compute/BaseTemplateBuilderLiveTest.java

https://github.com/alasdairhodge/jclouds
Java | 304 lines | 235 code | 43 blank | 26 comment | 27 complexity | b0e8952fc5d9f18759f3eb07d4a1307d MD5 | raw file
  1/**
  2 * Licensed to jclouds, Inc. (jclouds) under one or more
  3 * contributor license agreements.  See the NOTICE file
  4 * distributed with this work for additional information
  5 * regarding copyright ownership.  jclouds licenses this file
  6 * to you under the Apache License, Version 2.0 (the
  7 * "License"); you may not use this file except in compliance
  8 * with the License.  You may obtain a copy of the License at
  9 *
 10 *   http://www.apache.org/licenses/LICENSE-2.0
 11 *
 12 * Unless required by applicable law or agreed to in writing,
 13 * software distributed under the License is distributed on an
 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 15 * KIND, either express or implied.  See the License for the
 16 * specific language governing permissions and limitations
 17 * under the License.
 18 */
 19package org.jclouds.compute;
 20
 21import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
 22import static org.testng.Assert.assertEquals;
 23
 24import java.io.IOException;
 25import java.util.Map;
 26import java.util.Map.Entry;
 27import java.util.NoSuchElementException;
 28import java.util.Properties;
 29import java.util.Set;
 30import java.util.concurrent.ExecutionException;
 31import java.util.concurrent.TimeoutException;
 32
 33import org.jclouds.compute.config.BaseComputeServiceContextModule;
 34import org.jclouds.compute.domain.Hardware;
 35import org.jclouds.compute.domain.OsFamily;
 36import org.jclouds.compute.domain.OsFamilyVersion64Bit;
 37import org.jclouds.compute.domain.Template;
 38import org.jclouds.compute.domain.TemplateBuilder;
 39import org.jclouds.compute.reference.ComputeServiceConstants;
 40import org.jclouds.domain.Location;
 41import org.jclouds.domain.LocationScope;
 42import org.jclouds.domain.LoginCredentials;
 43import org.jclouds.json.Json;
 44import org.jclouds.json.config.GsonModule;
 45import org.jclouds.logging.log4j.config.Log4JLoggingModule;
 46import org.testng.annotations.AfterTest;
 47import org.testng.annotations.BeforeClass;
 48import org.testng.annotations.DataProvider;
 49import org.testng.annotations.Test;
 50
 51import com.google.common.base.Predicate;
 52import com.google.common.base.Predicates;
 53import com.google.common.base.Splitter;
 54import com.google.common.collect.ImmutableSet;
 55import com.google.common.collect.Iterables;
 56import com.google.common.collect.Sets;
 57import com.google.inject.Guice;
 58import com.google.inject.Module;
 59
 60/**
 61 * 
 62 * @author Adrian Cole
 63 */
 64@Test(groups = "integration,live")
 65public abstract class BaseTemplateBuilderLiveTest extends BaseVersionedServiceLiveTest {
 66
 67   protected ComputeServiceContext context;
 68
 69   public void testCompareSizes() throws Exception {
 70      Hardware defaultSize = context.getComputeService().templateBuilder().build().getHardware();
 71
 72      Hardware smallest = context.getComputeService().templateBuilder().smallest().build().getHardware();
 73      Hardware fastest = context.getComputeService().templateBuilder().fastest().build().getHardware();
 74      Hardware biggest = context.getComputeService().templateBuilder().biggest().build().getHardware();
 75
 76      System.out.printf("smallest %s%n", smallest);
 77      System.out.printf("fastest %s%n", fastest);
 78      System.out.printf("biggest %s%n", biggest);
 79
 80      assertEquals(defaultSize, smallest);
 81
 82      assert getCores(smallest) <= getCores(fastest) : String.format("%s ! <= %s", smallest, fastest);
 83      assert getCores(biggest) <= getCores(fastest) : String.format("%s ! <= %s", biggest, fastest);
 84
 85      assert biggest.getRam() >= fastest.getRam() : String.format("%s ! >= %s", biggest, fastest);
 86      assert biggest.getRam() >= smallest.getRam() : String.format("%s ! >= %s", biggest, smallest);
 87
 88      assert getCores(fastest) >= getCores(biggest) : String.format("%s ! >= %s", fastest, biggest);
 89      assert getCores(fastest) >= getCores(smallest) : String.format("%s ! >= %s", fastest, smallest);
 90   }
 91
 92   public void testFromTemplate() {
 93      Template defaultTemplate = context.getComputeService().templateBuilder().build();
 94      assertEquals(context.getComputeService().templateBuilder().fromTemplate(defaultTemplate).build().toString(),
 95            defaultTemplate.toString());
 96   }
 97
 98   @BeforeClass
 99   public void setupClient() throws InterruptedException, ExecutionException, TimeoutException, IOException {
100      setupCredentials();
101      context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider,
102            ImmutableSet.<Module> of(new Log4JLoggingModule()), setupProperties());
103   }
104
105   @DataProvider(name = "osSupported")
106   public Object[][] osSupported() {
107      return convertToArray(Sets.filter(provideAllOperatingSystems(),
108            Predicates.not(defineUnsupportedOperatingSystems())));
109   }
110
111   protected Object[][] convertToArray(Set<OsFamilyVersion64Bit> supportedOperatingSystems) {
112      Object[][] returnVal = new Object[supportedOperatingSystems.size()][1];
113      int i = 0;
114      for (OsFamilyVersion64Bit config : supportedOperatingSystems)
115         returnVal[i++][0] = config;
116      return returnVal;
117   }
118
119   protected Predicate<OsFamilyVersion64Bit> defineUnsupportedOperatingSystems() {
120      return Predicates.alwaysFalse();
121   }
122
123   @DataProvider(name = "osNotSupported")
124   public Object[][] osNotSupported() {
125      return convertToArray(Sets.filter(provideAllOperatingSystems(), defineUnsupportedOperatingSystems()));
126   }
127
128   protected Set<OsFamilyVersion64Bit> provideAllOperatingSystems() {
129      Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {
130      }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())
131            .getInstance(Json.class));
132
133      Set<OsFamilyVersion64Bit> supportedOperatingSystems = Sets.newHashSet();
134      for (Entry<OsFamily, Map<String, String>> osVersions : map.entrySet()) {
135         for (String version : Sets.newHashSet(osVersions.getValue().values())) {
136            supportedOperatingSystems.add(new OsFamilyVersion64Bit(osVersions.getKey(), version, false));
137            supportedOperatingSystems.add(new OsFamilyVersion64Bit(osVersions.getKey(), version, true));
138         }
139      }
140      return supportedOperatingSystems;
141   }
142
143   @Test(dataProvider = "osSupported")
144   public void testTemplateBuilderCanFind(OsFamilyVersion64Bit matrix) throws InterruptedException {
145      TemplateBuilder builder = context.getComputeService().templateBuilder().osFamily(matrix.family)
146            .os64Bit(matrix.is64Bit);
147      if (!matrix.version.equals(""))
148         builder.osVersionMatches("^" + matrix.version + "$");
149      Template template = builder.build();
150      if (!matrix.version.equals(""))
151         assertEquals(template.getImage().getOperatingSystem().getVersion(), matrix.version);
152      assertEquals(template.getImage().getOperatingSystem().is64Bit(), matrix.is64Bit);
153      assertEquals(template.getImage().getOperatingSystem().getFamily(), matrix.family);
154   }
155
156   @Test(dataProvider = "osNotSupported", expectedExceptions = NoSuchElementException.class)
157   public void testTemplateBuilderCannotFind(OsFamilyVersion64Bit matrix) throws InterruptedException {
158      TemplateBuilder builder = context.getComputeService().templateBuilder().osFamily(matrix.family)
159            .os64Bit(matrix.is64Bit);
160      if (!matrix.version.equals(""))
161         builder.osVersionMatches("^" + matrix.version + "$");
162      builder.build();
163   }
164
165   @Test
166   public void testTemplateBuilderCanUseImageId() throws Exception {
167      Template defaultTemplate = context.getComputeService().templateBuilder().build();
168      context.close();
169      setupClient();
170
171      Template template = context.getComputeService().templateBuilder().imageId(defaultTemplate.getImage().getId())
172            .locationId(defaultTemplate.getLocation().getId()).build();
173      assertEquals(template.getImage(), defaultTemplate.getImage());
174   }
175
176   @Test
177   public void testDefaultTemplateBuilder() throws IOException {
178      Template defaultTemplate = context.getComputeService().templateBuilder().build();
179      assert defaultTemplate.getImage().getOperatingSystem().getVersion().matches("1[012].[10][04]") : defaultTemplate
180            .getImage().getOperatingSystem().getVersion();
181      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
182      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);
183      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);
184   }
185
186   protected abstract Set<String> getIso3166Codes();
187
188   @Test(groups = { "integration", "live" })
189   public void testGetAssignableLocations() throws Exception {
190      assertProvider(context.getProviderSpecificContext());
191      for (Location location : context.getComputeService().listAssignableLocations()) {
192         System.err.printf("location %s%n", location);
193         assert location.getId() != null : location;
194         assert location != location.getParent() : location;
195         assert location.getScope() != null : location;
196         switch (location.getScope()) {
197         case PROVIDER:
198            assertProvider(location);
199            break;
200         case REGION:
201            assertProvider(location.getParent());
202            assert location.getIso3166Codes().size() == 0
203                  || location.getParent().getIso3166Codes().containsAll(location.getIso3166Codes()) : location + " ||"
204                  + location.getParent();
205            break;
206         case ZONE:
207            Location provider = location.getParent().getParent();
208            // zone can be a direct descendant of provider
209            if (provider == null)
210               provider = location.getParent();
211            assertProvider(provider);
212            assert location.getIso3166Codes().size() == 0
213                  || location.getParent().getIso3166Codes().containsAll(location.getIso3166Codes()) : location + " ||"
214                  + location.getParent();
215            break;
216         case HOST:
217            Location provider2 = location.getParent().getParent().getParent();
218            // zone can be a direct descendant of provider
219            if (provider2 == null)
220               provider2 = location.getParent().getParent();
221            assertProvider(provider2);
222            break;
223         }
224      }
225   }
226
227   @Test
228   public void testTemplateBuilderWithImageIdSpecified() throws IOException {
229      Template defaultTemplate = context.getComputeService().templateBuilder().build();
230
231      ComputeServiceContext context = null;
232      try {
233         Properties overrides = setupProperties();
234         overrides.setProperty("jclouds.image-id", defaultTemplate.getImage().getId());
235
236         context = new ComputeServiceContextFactory().createContext(provider,
237               ImmutableSet.<Module> of(new Log4JLoggingModule()), overrides);
238
239         assertEquals(context.getComputeService().templateBuilder().build().toString(), defaultTemplate.toString());
240      } finally {
241         if (context != null)
242            context.close();
243      }
244
245      context = null;
246      try {
247         Properties overrides = setupProperties();
248         overrides.setProperty(provider + ".image-id", defaultTemplate.getImage().getId());
249
250         context = new ComputeServiceContextFactory().createContext(provider,
251               ImmutableSet.<Module> of(new Log4JLoggingModule()), overrides);
252
253         assertEquals(context.getComputeService().templateBuilder().build().toString(), defaultTemplate.toString());
254      } finally {
255         if (context != null)
256            context.close();
257      }
258   }
259
260   @Test
261   public void testTemplateBuilderWithLoginUserSpecified() throws IOException {
262      tryOverrideUsingPropertyKey("jclouds");
263      tryOverrideUsingPropertyKey(provider);
264   }
265
266   protected void tryOverrideUsingPropertyKey(String propertyKey) {
267      ComputeServiceContext context = null;
268      try {
269         Properties overrides = setupProperties();
270         String login = loginUser != null ? loginUser : "foo:bar";
271         overrides.setProperty(propertyKey + ".image.login-user", login);
272         boolean auth = authenticateSudo != null ? Boolean.valueOf(authenticateSudo) : true;
273         overrides.setProperty(propertyKey + ".image.authenticate-sudo", auth + "");
274
275         context = new ComputeServiceContextFactory().createContext(provider,
276               ImmutableSet.<Module> of(new Log4JLoggingModule()), overrides);
277
278         Iterable<String> userPass = Splitter.on(':').split(login);
279         String user = Iterables.get(userPass, 0);
280         String pass = Iterables.size(userPass) > 1 ? Iterables.get(userPass, 1) : null;
281         assertEquals(context.getComputeService().templateBuilder().build().getImage().getDefaultCredentials(),
282               LoginCredentials.builder().user(user).password(pass).authenticateSudo(auth).build());
283      } finally {
284         if (context != null)
285            context.close();
286         
287         // Need to clear persisted credentials; otherwise next time a ComputeServiceContext is created  
288         // then it will have these "foo" credentials!
289         context.credentialStore().clear();
290      }
291   }
292
293   void assertProvider(Location provider) {
294      assertEquals(provider.getScope(), LocationScope.PROVIDER);
295      assertEquals(provider.getParent(), null);
296      assertEquals(provider.getIso3166Codes(), getIso3166Codes());
297   }
298
299   @AfterTest
300   protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException {
301      context.close();
302   }
303
304}