Search in sources :

Example 1 with Agent

use of org.ovirt.engine.sdk4.types.Agent in project ovirt-engine-sdk-java by oVirt.

the class UpdateFencingOptions method main.

public static void main(String[] args) throws Exception {
    // Create the connection to the server:
    Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
    // The name and value of the option that we want to add or update:
    String name = "lanplus";
    String value = "1";
    // Get the reference to the service that manages the hosts:
    HostsService hostsService = connection.systemService().hostsService();
    // Find the host:
    Host host = hostsService.list().search("name=myhost").send().hosts().get(0);
    // Get the reference to the service that manages the fencing agents used by the host that we found in the
    // previous step:
    HostService hostService = hostsService.hostService(host.id());
    FenceAgentsService agentsService = hostService.fenceAgentsService();
    // The host may have multiple fencing agents, so we need to locate the first of type 'ipmilan':
    List<Agent> agents = agentsService.list().send().agents();
    Agent agent = null;
    for (Agent x : agents) {
        if ("ipmlan".equals(x.type())) {
            agent = x;
            break;
        }
    }
    // Get the options of the fencing agent. There may be no options, in that case we need to use an empty list.
    List<Option> original = agent.options();
    if (original == null) {
        original = Collections.emptyList();
    }
    // Create a list of modified options, containing all the original options except the one with the name we want
    // to modify, as we will add that with the right value later:
    List<Option> modified = new ArrayList<>();
    for (Option option : original) {
        if (!name.equals(option.name())) {
            modified.add(option);
        }
    }
    // Add the modified option to the list of modified options:
    Option option = option().name(name).value(value).build();
    modified.add(option);
    // Find the service that manages the fence agent:
    FenceAgentService agentService = agentsService.agentService(agent.id());
    // Send the update request containing the modified list of options:
    agentService.update().agent(agent().options(modified)).send();
    // Close the connection to the server:
    connection.close();
}
Also used : HostService(org.ovirt.engine.sdk4.services.HostService) Agent(org.ovirt.engine.sdk4.types.Agent) FenceAgentService(org.ovirt.engine.sdk4.services.FenceAgentService) Connection(org.ovirt.engine.sdk4.Connection) ArrayList(java.util.ArrayList) HostsService(org.ovirt.engine.sdk4.services.HostsService) Host(org.ovirt.engine.sdk4.types.Host) Option(org.ovirt.engine.sdk4.types.Option) FenceAgentsService(org.ovirt.engine.sdk4.services.FenceAgentsService)

Example 2 with Agent

use of org.ovirt.engine.sdk4.types.Agent in project ovirt-engine-sdk-java by oVirt.

the class VmBackup method run.

/**
 * This is the method that performs the actual work.
 *
 * @param systemService the reference to the root of services
 * @throws Exception if something fails while doing the work
 */
private void run(SystemService systemService) throws Exception {
    // Get the reference to the service that we will use to send events to the audit log:
    EventsService eventsService = systemService.eventsService();
    // In order to send events we need to also send unique integer ids. These should usually come from an external
    // database, but in this example we will just generate them from the current time in seconds since Jan 1st 1970.
    int eventId = (int) (System.currentTimeMillis() / 1000);
    // Get the reference to the service that manages the virtual machines:
    VmsService vmsService = systemService.vmsService();
    // Find the virtual machine that we want to back up. Note that we need to use the 'all_content' parameter to
    // retrieve the retrieve the OVF, as it isn't retrieved by default:
    Vm dataVm = vmsService.list().search(String.format("name=%s", DATA_VM_NAME)).allContent(true).send().vms().get(0);
    log.info("Found data virtual machine '{}', the id is '{}'.", dataVm.name(), dataVm.id());
    // Find the virtual machine were we will attach the disks in order to do the backup:
    Vm agentVm = vmsService.list().search(String.format("name=%s", AGENT_VM_NAME)).send().vms().get(0);
    log.info("Found agent virtual machine '{}', the id is '{}'.", agentVm.name(), agentVm.id());
    // Find the services that manage the data and agent virtual machines:
    VmService dataVmService = vmsService.vmService(dataVm.id());
    VmService agentVmService = vmsService.vmService(agentVm.id());
    // Create an unique description for the snapshot, so that it is easier for the administrator to identify this
    // snapshot as a temporary one created just for backup purposes:
    String snapDescription = String.format("%s-backup-%s", dataVm.name(), UUID.randomUUID());
    // Send an external event to indicate to the administrator that the backup of the virtual machine is starting.
    // Note that the description of the event contains the name of the virtual machine and the name of the temporary
    // snapshot, this way, if something fails, the administrator will know what snapshot was used and remove it
    // manually.
    eventsService.add().event(event().vm(vm().id(dataVm.id())).origin(APPLICATION_NAME).severity(LogSeverity.NORMAL).customId(eventId++).description(String.format("Backup of virtual machine '%s' using snapshot '%s' is starting.", dataVm.name(), snapDescription))).send();
    // Save the OVF to a file, so that we can use to restore the virtual machine later. The name of the file is the
    // name of the virtual machine, followed by a dash and the identifier of the virtual machine, to make it unique:
    String ovfData = dataVm.initialization().configuration().data();
    File ovfFile = new File(String.format("%s-%s.ovf", dataVm.name(), dataVm.id()));
    try (OutputStream ovfStream = new FileOutputStream(ovfFile)) {
        ovfStream.write(ovfData.getBytes(StandardCharsets.UTF_8));
    }
    log.info("Wrote OVF to file '{}'", ovfFile.getAbsolutePath());
    // Send the request to create the snapshot. Note that this will return before the snapshot is completely
    // created, so we will later need to wait till the snapshot is completely created.
    SnapshotsService snapsService = dataVmService.snapshotsService();
    Snapshot snap = snapsService.add().snapshot(snapshot().description(snapDescription)).send().snapshot();
    log.info("Sent request to create snapshot '{}', the id is '{}'.", snap.description(), snap.id());
    // Poll and wait till the status of the snapshot is 'ok', which means that it is completely created:
    SnapshotService snapService = snapsService.snapshotService(snap.id());
    while (snap.snapshotStatus() != SnapshotStatus.OK) {
        log.info("Waiting till the snapshot is created, the status is now '{}'.", snap.snapshotStatus());
        Thread.sleep(1 * 1000);
        snap = snapService.get().send().snapshot();
    }
    log.info("The snapshot is now complete.");
    // Retrieve the descriptions of the disks of the snapshot:
    SnapshotDisksService snapDisksService = snapService.disksService();
    List<Disk> snapDisks = snapDisksService.list().send().disks();
    // Attach all the disks of the snapshot to the agent virtual machine, and save the resulting disk attachments
    // in a list so that we can later detach them easily:
    DiskAttachmentsService attachmentsService = agentVmService.diskAttachmentsService();
    List<DiskAttachment> attachments = new ArrayList<>();
    for (Disk snapDisk : snapDisks) {
        DiskAttachment attachment = attachmentsService.add().attachment(diskAttachment().disk(disk().id(snapDisk.id()).snapshot(snapshot().id(snap.id()))).active(true).bootable(false).interface_(DiskInterface.VIRTIO)).send().attachment();
        attachments.add(attachment);
        log.info("Attached disk '{}' to the agent virtual machine.", attachment.disk().id());
    }
    // been attached.
    for (DiskAttachment attachment : attachments) {
        if (attachment.logicalNamePresent()) {
            log.info("Logical name for disk '{}' is '{}'.", attachment.disk().id(), attachment.logicalName());
        } else {
            log.info("The logical name for disk '{}' isn't available. Is the guest agent installed?", attachment.disk().id());
        }
    }
    // Insert here the code to contact the backup agent and do the actual backup ...
    log.info("Doing the actual backup ...");
    // Detach the disks from the agent virtual machine:
    for (DiskAttachment attachment : attachments) {
        DiskAttachmentService attachmentService = attachmentsService.attachmentService(attachment.id());
        attachmentService.remove().send();
        log.info("Detached disk '{}' to from the agent virtual machine.", attachment.disk().id());
    }
    // Remove the snapshot:
    snapService.remove().send();
    log.info("Removed the snapshot '{}'.", snap.description());
    // Send an external event to indicate to the administrator that the backup of the virtual machine is completed:
    eventsService.add().event(event().vm(vm().id(dataVm.id())).origin(APPLICATION_NAME).severity(LogSeverity.NORMAL).customId(eventId++).description(String.format("Backup of virtual machine '%s' using snapshot '%s' is completed.", dataVm.name(), snapDescription))).send();
    // Bye:
    log.info("Bye!");
}
Also used : SnapshotService(org.ovirt.engine.sdk4.services.SnapshotService) SnapshotsService(org.ovirt.engine.sdk4.services.SnapshotsService) DiskAttachmentService(org.ovirt.engine.sdk4.services.DiskAttachmentService) VmService(org.ovirt.engine.sdk4.services.VmService) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) VmsService(org.ovirt.engine.sdk4.services.VmsService) Snapshot(org.ovirt.engine.sdk4.types.Snapshot) SnapshotDisksService(org.ovirt.engine.sdk4.services.SnapshotDisksService) DiskAttachment(org.ovirt.engine.sdk4.types.DiskAttachment) Vm(org.ovirt.engine.sdk4.types.Vm) FileOutputStream(java.io.FileOutputStream) EventsService(org.ovirt.engine.sdk4.services.EventsService) File(java.io.File) Disk(org.ovirt.engine.sdk4.types.Disk) DiskAttachmentsService(org.ovirt.engine.sdk4.services.DiskAttachmentsService)

Example 3 with Agent

use of org.ovirt.engine.sdk4.types.Agent in project ovirt-engine-sdk-java by oVirt.

the class HttpConnection method getSsoResponse.

private JsonNode getSsoResponse(URI uri, List<NameValuePair> params) {
    HttpResponse response = null;
    try {
        // Send request and parse token:
        HttpPost requestToken = new HttpPost(uri);
        requestToken.addHeader("User-Agent", "JavaSDK");
        requestToken.addHeader("Accept", "application/json");
        requestToken.setEntity(new UrlEncodedFormEntity(params));
        response = client.execute(requestToken);
        checkContentType(JSON_CONTENT_TYPE_RE, "JSON", response.getFirstHeader("content-type").getValue());
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readTree(response.getEntity().getContent());
    } catch (IOException ex) {
        throw new Error("Failed to parse JSON response", ex);
    } catch (Exception ex) {
        throw new Error("Failed to send SSO request", ex);
    } finally {
        if (response != null) {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpResponse(org.apache.http.HttpResponse) Error(org.ovirt.engine.sdk4.Error) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

ArrayList (java.util.ArrayList)2 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 MalformedURLException (java.net.MalformedURLException)1 HttpResponse (org.apache.http.HttpResponse)1 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)1 HttpPost (org.apache.http.client.methods.HttpPost)1 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)1 Connection (org.ovirt.engine.sdk4.Connection)1 Error (org.ovirt.engine.sdk4.Error)1 DiskAttachmentService (org.ovirt.engine.sdk4.services.DiskAttachmentService)1 DiskAttachmentsService (org.ovirt.engine.sdk4.services.DiskAttachmentsService)1 EventsService (org.ovirt.engine.sdk4.services.EventsService)1 FenceAgentService (org.ovirt.engine.sdk4.services.FenceAgentService)1 FenceAgentsService (org.ovirt.engine.sdk4.services.FenceAgentsService)1 HostService (org.ovirt.engine.sdk4.services.HostService)1 HostsService (org.ovirt.engine.sdk4.services.HostsService)1