Invoke Setup Networks from the Java SDK

In order to use the latest and greatest host networking feature, the ‘setup networks’ api should be used. The ‘setup networks’ api expects to get as a parameter the complete target network configuration.

The following example demonstrates attaching network ‘red’ to network interface ‘eth4’ and assigning IP address to it in a single api call.

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ovirt.engine.sdk.Api;
import org.ovirt.engine.sdk.decorators.HostNIC;
import org.ovirt.engine.sdk.decorators.HostNICs;
import org.ovirt.engine.sdk.entities.Action;
import org.ovirt.engine.sdk.entities.BaseResource;
import org.ovirt.engine.sdk.entities.HostNics;
import org.ovirt.engine.sdk.entities.IP;
import org.ovirt.engine.sdk.entities.Network;

public class SetupNetworksExample {

    public static void main(String[] args) throws Exception {

        try (Api api = new Api("http://localhost:8080/api",
                "admin@internal",
                "1",
                null, null, null, null, null, null, true)) {

            HostNICs nicsApi = api.getHosts().get("venus-vdsb").getHostNics();
            List<HostNIC> nics = nicsApi.list();

            Map<String, HostNIC> nicsByNames = entitiesByName(nics);
            HostNIC nic = nicsByNames.get("eth4");

            // add network 'red' to 'eth4' and assign IP address
            Network net = new Network();
            net.setName("red");
            nic.setNetwork(net);
            IP ip = new IP();
            ip.setAddress("192.168.1.151");
            ip.setNetmask("255.255.255.0");

            // In case a specific gateway other than the default should be set for 'red'
            // ip.setGateway(RED_GATEWAY);
            nic.setIp(ip);
            nic.setBootProtocol("static");

            nicsApi.setupnetworks(createSetupNetworksParams(nics));
        }
    }

    public static Action createSetupNetworksParams(List<HostNIC> nics) {
        Action action = new Action();
        HostNics nicsParams = new HostNics();
        nicsParams.getHostNics().addAll(nics);
        action.setHostNics(nicsParams);
        action.setCheckConnectivity(true);
        return action;
    }

    public static <E extends BaseResource> Map<String, E> entitiesByName(List<E> entityList) {
        if (entityList != null) {
            Map<String, E> map = new HashMap<String, E>();
            for (E e : entityList) {
                map.put(e.getName(), e);
            }
            return map;
        } else {
            return Collections.emptyMap();
        }
    }
}

Leave a comment