Skip to content

@apuig /.gitignore secret
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
scala REPL to jclouds-abiquo api client
target/
project/

scala REPL for abiquo api client

  • Install sbt

  • Clone the repository

git clone git@gist.github.com:09a5faacc5936089231f.git
  • Fire it
sbt console

or

sbt -Dabiquo.endpoint=http://10.60.1.223/api console

Wait for internet complet download (considere removing thie .ivy cache if some dep problem), at the end you get the scala> prompt, now you can start using AbiquoContext from context or the AbiquoApi from abiquo, current Enterprise fetched from enter value. dc will get an existing datacenter or setup one by default (127.0.0.1)

Check sprawl.scala file to see the different possibilities when using the jclouds API

  • Domain objects
scala> enter.listVirtualMachines
  • Sprawl utils
scala> machine("10.60.1.223")
scala> vm("testVm", template("Core").get, vapp("testVapp", vdc("testVdc")))
  • Context Services
scala> context.getCloudService.listVirtualMachines.filter(vm => vm.getState.name == "UNKNOWN").foreach(vm => vm.delete)
  • API binding
scala> abiquo.getVirtualMachineTemplateApi.listVirtualMachineTemplates(enter.getId,dc.getId)
  • Dtos manipulation
scala> val enterDto = enter.unwrap
enterDto: com.abiquo.server.core.enterprise.EnterpriseDto = com.abiquo.server.core.enterprise.EnterpriseDto@4e61d0f4
scala> println(marshal(enterDto))
scala> val enter2 = unmarshal[EnterpriseDto]("""<enterprise></enterprise>""")
  • Going restful
scala> val myenter = get[EnterpriseDto]("http://10.60.1.223:80/api/admin/enterprises/1")
scala> myenter.setName("foo")
scala> val modified = put(myenter)
scala> delete(modified)
scalaVersion := "2.10.2"
libraryDependencies += "org.apache.jclouds.labs" % "abiquo" % "1.6.2-incubating"
libraryDependencies += "org.apache.jclouds.driver" % "jclouds-slf4j" % "1.6.2-incubating"
libraryDependencies += "com.google.code.findbugs" % "jsr305" % "2.0.1"
libraryDependencies += "com.sun.jersey" % "jersey-core" % "1.17.1"
libraryDependencies += "com.sun.jersey" % "jersey-client" % "1.17.1"
libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.0.0"
resolvers += ".m2" at "file://"+Path.userHome.absolutePath+"/.m2/repository"
resolvers += "abirepo" at "http://repo.community.abiquo.com/artifactory"
initialCommands := """import sprawl._
import jaxbfoo._
import com.abiquo.model.enumerator._
import com.abiquo.model.transport._
import com.abiquo.server.core._, appslibrary._, cloud._, enterprise._, infrastructure._
import scala.collection.JavaConversions._
"""
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.WebResource
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter
import javax.xml.bind.JAXBContext
import javax.xml.bind.JAXBException
import javax.xml.bind.Marshaller
import javax.xml.bind.Unmarshaller
import java.io.ByteArrayInputStream
import java.io.StringWriter
import com.abiquo.model.transport.SingleResourceTransportDto
object jaxbfoo {
lazy val http = { val c = Client.create; c.addFilter(new HTTPBasicAuthFilter("admin","xabiquo")); c }
def get[T](uri: String)(implicit tag : reflect.ClassTag[T]): T = {
http.resource(uri).get(tag.runtimeClass.asInstanceOf[Class[T]])
}
def put[T <: SingleResourceTransportDto](obj: T)(implicit tag : reflect.ClassTag[T]): T = {
http.resource(obj.getEditLink.getHref).accept(obj.getMediaType).header("Content-Type", obj.getMediaType).put(tag.runtimeClass.asInstanceOf[Class[T]], obj)
}
def post[T <:SingleResourceTransportDto](uri: String, obj: T)(implicit tag : reflect.ClassTag[T]): T = {
http.resource(uri).accept(obj.getMediaType).header("Content-Type", obj.getMediaType).post(tag.runtimeClass.asInstanceOf[Class[T]], obj)
}
def delete[T <: SingleResourceTransportDto](obj: T) = {
http.resource(obj.getEditLink.getHref).delete()
}
def unmarshal[T](response: String)(implicit tag : reflect.ClassTag[T]): T = {
val unmarshaller = createUnmarshaller(tag.runtimeClass)
unmarshal(response, unmarshaller)
}
def marshal[T](objectToMarshal: T)(implicit tag : reflect.ClassTag[T]): String = {
try {
val ctx = JAXBContext.newInstance(tag.runtimeClass.asInstanceOf[Class[T]])
val marshaller = ctx.createMarshaller
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
val writer = new StringWriter(500)
marshaller.marshal(objectToMarshal, writer)
writer.toString
} catch {
case e: JAXBException => throw new RuntimeException(e)
}
}
private def unmarshal[T](response: String, unmarshaller: Unmarshaller)(implicit tag : reflect.ClassTag[T]): T = {
val is = new ByteArrayInputStream(response.getBytes)
unmarshaller.unmarshal(is).asInstanceOf[T]
}
private def createUnmarshaller[T](clazz: Class[T]): Unmarshaller = {
val ctx = JAXBContext.newInstance(clazz)
ctx.createUnmarshaller
}
}
import java.util.Properties
import com.google.common.collect.ImmutableSet
import scala.collection.JavaConversions._
import com.abiquo.model.enumerator._
import org.jclouds.ContextBuilder
import org.jclouds.abiquo.domain.cloud._
import org.jclouds.abiquo.domain.infrastructure._
import org.jclouds.abiquo.AbiquoApiMetadata
import org.jclouds.abiquo.AbiquoContext
import jaxbfoo._
object sprawl
{
var htype = HypervisorType.VBOX;
val props = new Properties(); props.put("jclouds.max-retries","0"); props.put("jclouds.max-redirects","0"); props.put("jclouds.timeouts.InfrastructureClient.discoverSingleMachine","120000");
props.put("abiquo.api-version","2.4")
val context = ContextBuilder.newBuilder(new AbiquoApiMetadata())
.endpoint(System.getProperty("abiquo.endpoint","http://localhost:80/api"))
.credentials("admin","xabiquo")
.modules(ImmutableSet.of(new org.jclouds.logging.config.NullLoggingModule())).overrides(props).build(classOf[AbiquoContext])
lazy val api = context.getApiContext
lazy val abiquo = api.getApi
lazy val enter = context.getAdministrationService().getCurrentEnterprise()
lazy val dc : Datacenter = context.getAdministrationService.listDatacenters.headOption.getOrElse({
val dc = Datacenter.builder(api).name("default").location("home").remoteServices("127.0.0.1").build(); dc.save();
enter.refreshTemplateRepository(dc); loadLevel(); dc
})
lazy val rack : Rack = dc.listRacks.headOption.getOrElse({
val rack = Rack.builder(context.getApiContext(), dc).name("default").build(); rack.save(); rack
})
def machine(address : String) : Machine = {
import org.jclouds.abiquo.predicates.infrastructure.MachinePredicates
Option(context.getAdministrationService.findMachine(MachinePredicates.ip(address))).getOrElse({
val machine = dc.discoverSingleMachine(address, htype, "root", "temporal");
val ds = machine.getDatastores.head; ds.setEnabled(true)
val vswitch = machine.getNetworkInterfaces.head; vswitch.setNetworkServiceType(dc.defaultNetworkServiceType())
machine.setRack(rack)
machine.save(); machine
})
}
def template(name : String) : Option[VirtualMachineTemplate] = {
import org.jclouds.abiquo.predicates.cloud.VirtualMachineTemplatePredicates
Option(enter.findTemplate(VirtualMachineTemplatePredicates.name(name)))
}
def vdc(name : String) : VirtualDatacenter = {
import org.jclouds.abiquo.predicates.cloud.VirtualDatacenterPredicates
Option(context.getCloudService().findVirtualDatacenter(VirtualDatacenterPredicates.name(name))).getOrElse({
import org.jclouds.abiquo.domain.network.PrivateNetwork
val vdc = VirtualDatacenter.builder(api, dc, enter).network(
PrivateNetwork.builder(api).name(name).gateway("192.168.1.1").address("192.168.1.0").mask(24).build()
).hypervisorType(htype).name(name).build(); vdc.save; vdc
})
}
def vapp(name : String, vdc : VirtualDatacenter) : VirtualAppliance = {
import org.jclouds.abiquo.predicates.cloud.VirtualAppliancePredicates
Option(vdc.findVirtualAppliance(VirtualAppliancePredicates.name(name))).getOrElse({
val vapp = VirtualAppliance.builder(api, vdc).name(name).build(); vapp.save(); vapp
})
}
def vm(name : String, template : VirtualMachineTemplate, vapp : VirtualAppliance) : VirtualMachine = {
context.getCloudService.listVirtualMachines.filter(vm => vm.getNameLabel() == name).headOption.getOrElse({
val vm = VirtualMachine.builder(api, vapp, template).nameLabel(name).description(name).build(); vm.save(); vm
})
}
def loadLevel() = {
val MLR_MT = """application/vnd.abiquo.machineloadrule+xml""";
http.resource(System.getProperty("abiquo.endpoint","http://localhost:80/api")+"""/admin/rules/machineLoadLevel""")
.header("Content-Type", MLR_MT).accept(MLR_MT).post(
"""<machineLoadRule>
<link rel="datacenter" href=""""+dc.unwrap.getEditLink.getHref+""""/>
<cpuLoadPercentage>9999999</cpuLoadPercentage>
<ramLoadPercentage>9999999</ramLoadPercentage>
</machineLoadRule>""")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.