private List<GlusterClientInfo> getClientList(int listSize) {
   ArrayList<GlusterClientInfo> list = new ArrayList<>();
   for (int i = 0; i < listSize; i++) {
     GlusterClientInfo clientInfo = new GlusterClientInfo();
     clientInfo.setBytesRead(RandomUtils.instance().nextLong());
     clientInfo.setBytesWritten(RandomUtils.instance().nextLong());
     clientInfo.setClientPort(RandomUtils.instance().nextInt());
     clientInfo.setHostname(RandomUtils.instance().nextString(7));
     list.add(clientInfo);
   }
   return list;
 }
예제 #2
0
 @Test
 public void testUpdateStatusAndReasons() {
   VdsDynamic before = dao.get(existingVds.getId());
   before.setStatus(RandomUtils.instance().nextEnum(VDSStatus.class));
   before.setNonOperationalReason(RandomUtils.instance().nextEnum(NonOperationalReason.class));
   before.setMaintenanceReason(RandomUtils.instance().nextString(50));
   dao.updateStatusAndReasons(before);
   VdsDynamic after = dao.get(existingVds.getId());
   assertEquals(before, after);
   assertEquals(before.getStatus(), after.getStatus());
   assertEquals(before.getNonOperationalReason(), after.getNonOperationalReason());
   assertEquals(before.getMaintenanceReason(), after.getMaintenanceReason());
 }
 private static VmNetworkInterface createNewViewableInterface(boolean plugged) {
   VmNetworkInterface iface = new VmNetworkInterface();
   iface.setId(Guid.newGuid());
   iface.setMacAddress(RandomUtils.instance().nextString(10));
   iface.setPlugged(plugged);
   return iface;
 }
  /** @return A new interface that can be used in tests. */
  private static VmNic createNewInterface() {
    VmNic iface = new VmNic();
    iface.setId(Guid.newGuid());
    iface.setMacAddress(RandomUtils.instance().nextString(10));

    return iface;
  }
  @Test
  public void testRemoveImageFromSnapshotConfiguration() throws OvfReaderException {
    Guid vmId = Guid.newGuid();
    VM vm = new VM();
    vm.setId(vmId);
    vm.setStoragePoolId(Guid.newGuid());
    vm.setVmtName(RandomUtils.instance().nextString(10));
    vm.setOrigin(OriginType.OVIRT);
    vm.setDbGeneration(1L);
    Guid vmSnapshotId = Guid.newGuid();

    DiskImage disk1 = addTestDisk(vm, vmSnapshotId);
    DiskImage disk2 = addTestDisk(vm, vmSnapshotId);

    OvfManager ovfManager = new OvfManager();
    ArrayList<DiskImage> disks = new ArrayList<DiskImage>(Arrays.asList(disk1, disk2));
    String ovf = ovfManager.ExportVm(vm, disks, Version.v3_1);
    Snapshot snap = new Snapshot();
    snap.setVmConfiguration(ovf);
    snap.setId(vmSnapshotId);

    when(snapshotDAO.get(vmSnapshotId)).thenReturn(snap);
    doReturn(disk2).when(cmd).getDiskImage();
    doReturn(disk2).when(cmd).getImage();
    doReturn(disk2.getId()).when(cmd).getImageId();
    Snapshot actual =
        cmd.prepareSnapshotConfigWithoutImageSingleImage(vmSnapshotId, disk2.getImageId());
    String actualOvf = actual.getVmConfiguration();

    ArrayList<DiskImage> actualImages = new ArrayList<DiskImage>();
    ovfManager.ImportVm(actualOvf, new VM(), actualImages, new ArrayList<VmNetworkInterface>());
    assertEquals("Wrong number of disks", 1, actualImages.size());
    assertEquals("Wrong disk", disk1, actualImages.get(0));
  }
  private MemoryStatus getMemoryStatus(int listSize) {
    MemoryStatus memStatus = new MemoryStatus();
    memStatus.setMallInfo(new MallInfo());

    memStatus.getMallInfo().setArena(RandomUtils.instance().nextInt());
    memStatus.getMallInfo().setUordblks(RandomUtils.instance().nextInt());
    ArrayList<Mempool> memPoolsList = new ArrayList<>();
    for (int i = 0; i < listSize; i++) {
      Mempool pool = new Mempool();
      pool.setAllocCount(RandomUtils.instance().nextInt());
      pool.setHotCount(0);
      pool.setName(RandomUtils.instance().nextString(5));
      memPoolsList.add(pool);
    }
    memStatus.setMemPools(memPoolsList);
    return memStatus;
  }
  /**
   * Mocks a call to {@link Config#GetValue(ConfigValues)) and returns the value it should return.
   * @return The mocked value
   */
  private static String mockConfig(Version version, ConfigurationValues configurationValues) {
    String returnValue = RandomUtils.instance().nextString(10, true);

    ConfigValues configValues = ConfigValues.valueOf(configurationValues.name());
    mcr.mockConfigValue(configValues, version, returnValue);

    return returnValue;
  }
 /** The following method will create a new DiskImage */
 private DiskImage createDiskImage() {
   DiskImage disk = new DiskImage();
   disk.setId(diskImageGuid);
   disk.setSize(100000L);
   disk.setDiskInterface(DiskInterface.VirtIO);
   disk.setStorageIds(new ArrayList<>(Collections.singleton(sdId)));
   disk.setStoragePoolId(spId);
   disk.setDescription(RandomUtils.instance().nextString(10));
   return disk;
 }
  private void canDoActionUpdateDescription(VMStatus status) {
    DiskImage disk = createDiskImage();
    disk.setReadOnly(false);
    when(diskDao.get(diskImageGuid)).thenReturn(disk);
    UpdateVmDiskParameters parameters = createParameters();
    parameters.getDiskInfo().setReadOnly(false);
    disk.setDescription(RandomUtils.instance().nextString(10));
    initializeCommand(parameters, Collections.singletonList(createVm(status)));

    CanDoActionTestUtils.runAndAssertCanDoActionSuccess(command);
  }
  @Test
  public void testExecuteQueryWithoutDirectOnly() {
    VdcObjectType type = RandomUtils.instance().pickRandom(VdcObjectType.values());
    when(getQueryParameters().getVdcObjectType()).thenReturn(type);

    PermissionDAO permissionDAOMock = mock(PermissionDAO.class);
    when(permissionDAOMock.getTreeForEntity(
            objectID, type, getUser().getId(), getQueryParameters().isFiltered()))
        .thenReturn(mockedPermissions);
    when(getDbFacadeMockInstance().getPermissionDao()).thenReturn(permissionDAOMock);

    assertQueryDAOCall(false);
  }
  private void assertQueryExecution(
      ConfigurationValues configValue, boolean isFiltered, boolean shouldSucceed) {
    // Mock the parameters
    Version version = RandomUtils.instance().pickRandom(Version.ALL);
    when(getQueryParameters().getVersion()).thenReturn(version.toString());
    when(getQueryParameters().getConfigValue()).thenReturn(configValue);
    when(getQueryParameters().isFiltered()).thenReturn(isFiltered);

    // Mock the config
    String expected = mockConfig(version, configValue);

    getQuery().executeQueryCommand();

    Object actual = getQuery().getQueryReturnValue().getReturnValue();

    if (shouldSucceed) {
      assertEquals("Got wrong expected value for " + configValue, expected, actual);
    } else {
      assertNull("Should get null result for " + configValue, actual);
    }
  }
@RunWith(MockitoJUnitRunner.class)
public class NetworkDeviceHelperImplTest {

  private static final String NIC_NAME = RandomUtils.instance().nextString(5);
  private static final Guid NIC_ID = Guid.newGuid();
  private static final Guid HOST_ID = Guid.newGuid();
  private static final String NET_DEVICE_NAME = RandomUtils.instance().nextString(5);
  private static final String PCI_DEVICE_NAME = RandomUtils.instance().nextString(5);
  private static final String PCI_DEVICE_NAME_2 = RandomUtils.instance().nextString(5);
  private static int TOTAL_NUM_OF_VFS = 7;

  @Mock private HostDevice netDevice;

  @Mock private HostDevice pciDevice;

  @Mock private VdsNetworkInterface nic;

  @Mock private HostNicVfsConfig hostNicVfsConfig;

  @Mock private InterfaceDao interfaceDao;

  @Mock private HostDeviceDao hostDeviceDao;

  @Mock private HostNicVfsConfigDao hostNicVfsConfigDao;

  @Mock private VdsDao vdsDao;

  @Captor private ArgumentCaptor<HostDeviceId> hostDeviceIdCaptor;

  @Captor private ArgumentCaptor<Guid> vmIdCaptor;
  private NetworkDeviceHelperImpl networkDeviceHelper;

  @Rule public MockConfigRule mockConfigRule = new MockConfigRule();

  @Before
  public void setUp() {
    networkDeviceHelper =
        new NetworkDeviceHelperImpl(interfaceDao, hostDeviceDao, hostNicVfsConfigDao, vdsDao);

    when(netDevice.getHostId()).thenReturn(HOST_ID);
    when(netDevice.getDeviceName()).thenReturn(NET_DEVICE_NAME);
    when(netDevice.getName()).thenReturn(NET_DEVICE_NAME);
    when(netDevice.getNetworkInterfaceName()).thenReturn(NIC_NAME);
    when(netDevice.getParentDeviceName()).thenReturn(PCI_DEVICE_NAME);

    when(pciDevice.getHostId()).thenReturn(HOST_ID);
    when(pciDevice.getDeviceName()).thenReturn(PCI_DEVICE_NAME);
    when(pciDevice.getName()).thenReturn(PCI_DEVICE_NAME);

    List<HostDevice> devices = new ArrayList<>();
    devices.add(netDevice);
    devices.add(pciDevice);
    mockHostDevices(devices);

    when(nic.getId()).thenReturn(NIC_ID);
    when(nic.getName()).thenReturn(NIC_NAME);
    when(nic.getVdsId()).thenReturn(HOST_ID);
    when(interfaceDao.get(NIC_ID)).thenReturn(nic);
    when(nic.getName()).thenReturn(NIC_NAME);

    when(hostNicVfsConfig.getNicId()).thenReturn(NIC_ID);
    when(hostNicVfsConfigDao.getByNicId(NIC_ID)).thenReturn(hostNicVfsConfig);
  }

  @Test
  public void getNicByPciDeviceNotParentOfNetDevice() {
    assertNull(networkDeviceHelper.getNicByPciDevice(netDevice));
  }

  @Test
  public void getNicByNetDeviceNoNic() {
    VdsNetworkInterface newNic = new VdsNetworkInterface();
    newNic.setName(netDevice.getNetworkInterfaceName() + "not");
    mockNics(Collections.singletonList(newNic), false);

    assertNull(networkDeviceHelper.getNicByPciDevice(pciDevice));
  }

  @Test
  public void getNicByNetDeviceValid() {
    mockNics(Collections.<VdsNetworkInterface>emptyList(), true);
    assertEquals(nic, networkDeviceHelper.getNicByPciDevice(pciDevice));
  }

  @Test
  public void getNicByNetDeviceWithNonDbDevicesNoNetDevice() {
    mockNics(Collections.<VdsNetworkInterface>emptyList(), true);
    Collection<HostDevice> devices = new ArrayList<>();
    devices.add(pciDevice);

    assertNull(networkDeviceHelper.getNicByPciDevice(pciDevice, devices));
  }

  @Test
  public void isSriovNetworkDeviceNotSriov() {
    commonIsSriovDevice(false);
  }

  @Test
  public void isSriovNetworkDeviceSriov() {
    commonIsSriovDevice(true);
  }

  private void commonIsSriovDevice(boolean isSriov) {
    when(pciDevice.getTotalVirtualFunctions()).thenReturn(isSriov ? TOTAL_NUM_OF_VFS : null);

    assertEquals(isSriov, networkDeviceHelper.isSriovDevice(pciDevice));
  }

  @Test
  public void isNetworkDevicePossitive() {
    assertFalse(networkDeviceHelper.isNetworkDevice(pciDevice));
  }

  @Test
  public void isNetworkDeviceNegtive() {
    assertTrue(networkDeviceHelper.isNetworkDevice(netDevice));
  }

  @Test
  public void updateHostNicVfsConfigWithNumVfsData() {
    commonUpdateHostNicVfsConfigWithNumVfsData(4);
  }

  @Test
  public void updateHostNicVfsConfigWithNumVfsDataZeroVfs() {
    commonUpdateHostNicVfsConfigWithNumVfsData(0);
  }

  private void commonUpdateHostNicVfsConfigWithNumVfsData(int numOfVfs) {
    when(pciDevice.getTotalVirtualFunctions()).thenReturn(TOTAL_NUM_OF_VFS);
    List<HostDevice> vfs = mockVfsOnNetDevice(numOfVfs);
    mockHostDevices(vfs);

    networkDeviceHelper.updateHostNicVfsConfigWithNumVfsData(hostNicVfsConfig);

    verify(hostNicVfsConfig).setMaxNumOfVfs(TOTAL_NUM_OF_VFS);
    verify(hostNicVfsConfig).setNumOfVfs(numOfVfs);
  }

  @Test
  public void getHostNicVfsConfigsWithNumVfsDataByHostId() {
    when(hostNicVfsConfigDao.getAllVfsConfigByHostId(HOST_ID))
        .thenReturn(Collections.singletonList(hostNicVfsConfig));

    when(pciDevice.getTotalVirtualFunctions()).thenReturn(TOTAL_NUM_OF_VFS);
    List<HostDevice> vfs = mockVfsOnNetDevice(2);
    mockHostDevices(vfs);

    List<HostNicVfsConfig> vfsConfigList =
        networkDeviceHelper.getHostNicVfsConfigsWithNumVfsDataByHostId(HOST_ID);

    assertEquals(1, vfsConfigList.size());
    assertEquals(hostNicVfsConfig, vfsConfigList.get(0));

    verify(hostNicVfsConfig).setMaxNumOfVfs(TOTAL_NUM_OF_VFS);
    verify(hostNicVfsConfig).setNumOfVfs(2);
  }

  private List<HostDevice> mockVfsOnNetDevice(int numOfVfs) {
    return mockVfsOnNetDevice(numOfVfs, null);
  }

  private List<HostDevice> mockVfsOnNetDevice(int numOfVfs, Guid vmId) {
    List<HostDevice> vfs = new ArrayList<>();

    for (int i = 0; i < numOfVfs; ++i) {
      HostDevice vfPciDevice = new HostDevice();
      vfPciDevice.setParentPhysicalFunction(pciDevice.getDeviceName());
      vfPciDevice.setDeviceName(String.valueOf(i));
      vfPciDevice.setHostId(HOST_ID);
      vfPciDevice.setVmId(vmId);
      vfs.add(vfPciDevice);
    }

    return vfs;
  }

  private void mockHostDevices(List<HostDevice> extraDevices) {
    List<HostDevice> devices = new ArrayList<>();
    devices.add(pciDevice);
    devices.add(netDevice);
    devices.addAll(extraDevices);

    when(hostDeviceDao.getHostDevicesByHostId(HOST_ID)).thenReturn(devices);
    when(hostDeviceDao.getAll()).thenReturn(devices);
  }

  @Test(expected = UnsupportedOperationException.class)
  public void areAllVfsFreeNotSriovNic() {
    commonIsSriovDevice(false);
    networkDeviceHelper.areAllVfsFree(nic);
  }

  @Test
  public void areAllVfsFreeTrueNoVfs() {
    freeVfCommon(0, 0, 0, 0, 0, 0);
    assertTrue(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeFalseAttachedToVm() {
    freeVfCommon(7, 3, 0, 0, 0, 0);
    assertFalse(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeFalseNoNic() {
    freeVfCommon(6, 0, 1, 0, 0, 0);
    assertFalse(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeFalseHasNetwork() {
    freeVfCommon(2, 0, 0, 3, 0, 0);
    assertFalse(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeFalseHasVlanDevice() {
    freeVfCommon(4, 0, 0, 0, 3, 0);
    assertFalse(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeTrue() {
    freeVfCommon(5, 0, 0, 0, 0, 0);
    assertTrue(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeFalseMix() {
    freeVfCommon(1, 2, 3, 4, 5, 6);
    assertFalse(networkDeviceHelper.areAllVfsFree(nic));
  }

  @Test
  public void areAllVfsFreeFalseHasVfPartOfBond() {
    freeVfCommon(4, 0, 0, 0, 0, 1);
    assertFalse(networkDeviceHelper.areAllVfsFree(nic));
  }

  private List<HostDevice> freeVfCommon(
      int numOfFreeVfs,
      int numOfVfsAttachedToVm,
      int numOfVfsHasNoNic,
      int numOfVfsHasNetworkAttached,
      int numOfVfsHasVlanDeviceAttached,
      int numOfVfsArePartOfBond) {
    networkDeviceHelper =
        spy(new NetworkDeviceHelperImpl(interfaceDao, hostDeviceDao, hostNicVfsConfigDao, vdsDao));

    List<HostDevice> devices = new ArrayList<>();
    List<HostDevice> freeVfs = new ArrayList<>();

    int numOfVfs =
        numOfFreeVfs
            + numOfVfsAttachedToVm
            + numOfVfsHasNoNic
            + numOfVfsHasNetworkAttached
            + numOfVfsHasVlanDeviceAttached
            + numOfVfsArePartOfBond;
    List<HostDevice> vfs = mockVfsOnNetDevice(numOfVfs);
    List<VdsNetworkInterface> nics = new ArrayList<>();
    devices.addAll(vfs);

    for (HostDevice vfPciDevice : vfs) {
      HostDevice vfNetDevice = mockNetworkDeviceForPciDevice(vfPciDevice);
      devices.add(vfNetDevice);

      if (numOfVfsHasNoNic != 0) {
        --numOfVfsHasNoNic;
      } else {
        VdsNetworkInterface vfNic = mockNicForNetDevice(vfNetDevice);
        nics.add(vfNic);
        if (numOfVfsAttachedToVm != 0) {
          --numOfVfsAttachedToVm;
          vfPciDevice.setVmId(Guid.newGuid());
        } else if (numOfVfsHasNetworkAttached != 0) {
          --numOfVfsHasNetworkAttached;
          vfNic.setNetworkName("netName");
        } else if (numOfVfsHasVlanDeviceAttached != 0) {
          --numOfVfsHasVlanDeviceAttached;
          doReturn(true).when(networkDeviceHelper).isVlanDeviceAttached(vfNic);
        } else if (numOfVfsArePartOfBond != 0) {
          --numOfVfsArePartOfBond;
          vfNic.setBondName("bondName");
        } else {
          doReturn(false).when(networkDeviceHelper).isVlanDeviceAttached(vfNic);
          freeVfs.add(vfPciDevice);
        }
      }
    }

    mockHostDevices(devices);
    mockNics(nics, true);

    return freeVfs;
  }

  @Test(expected = UnsupportedOperationException.class)
  public void getFreeVfNotSriovNic() {
    commonIsSriovDevice(false);
    networkDeviceHelper.getFreeVf(nic, null);
  }

  @Test
  public void getFreeVfNoVfs() {
    freeVfCommon(0, 0, 0, 0, 0, 0);
    assertNull(networkDeviceHelper.getFreeVf(nic, null));
  }

  @Test
  public void getFreeVfNoFreeVf() {
    freeVfCommon(0, 1, 2, 3, 4, 5);
    assertNull(networkDeviceHelper.getFreeVf(nic, null));
  }

  @Test
  public void getFreeVfOneFreeVf() {
    List<HostDevice> freeVfs = freeVfCommon(1, 4, 3, 2, 1, 1);
    assertEquals(1, freeVfs.size());
    assertTrue(freeVfs.contains(networkDeviceHelper.getFreeVf(nic, null)));
  }

  @Test
  public void getFreeVfMoreThanOneFreeVf() {
    List<HostDevice> freeVfs = freeVfCommon(5, 2, 2, 2, 2, 2);
    assertEquals(5, freeVfs.size());
    assertTrue(freeVfs.contains(networkDeviceHelper.getFreeVf(nic, null)));
  }

  @Test
  public void getFreeVfWithExcludedVfs() {
    List<HostDevice> freeVfs = freeVfCommon(5, 2, 2, 2, 2, 2);
    assertEquals(5, freeVfs.size());
    List<HostDevice> excludedVfs = new ArrayList<>();
    excludedVfs.add(freeVfs.get(0));
    excludedVfs.add(freeVfs.get(1));
    freeVfs.removeAll(excludedVfs);

    List<String> excludedVfsNames =
        LinqUtils.transformToList(
            excludedVfs,
            new Function<HostDevice, String>() {

              @Override
              public String eval(HostDevice excludedVf) {
                return excludedVf.getDeviceName();
              }
            });

    assertTrue(freeVfs.contains(networkDeviceHelper.getFreeVf(nic, excludedVfsNames)));
  }

  @Test
  public void isNonNetworkDeviceNetworkFree() {
    HostDevice device = new HostDevice();
    device.setHostId(HOST_ID);
    device.setDeviceName(PCI_DEVICE_NAME_2);

    assertTrue(networkDeviceHelper.isDeviceNetworkFree(device));
  }

  @Test
  public void noNicDeviceNonNetworkFree() {
    freeVfCommon(0, 0, 1, 0, 0, 0);
    HostDevice hostDevice = getSingleMockedNonFreeDevice();
    assertFalse(networkDeviceHelper.isDeviceNetworkFree(hostDevice));
  }

  @Test
  public void isNetworkDeviceNonNetworkFree() {
    freeVfCommon(0, 0, 0, 1, 0, 0);
    HostDevice hostDevice = getSingleMockedNonFreeDevice();
    assertFalse(networkDeviceHelper.isDeviceNetworkFree(hostDevice));
  }

  @Test
  public void isVlanDeviceNonNetworkFree() {
    freeVfCommon(0, 0, 0, 0, 1, 0);
    HostDevice hostDevice = getSingleMockedNonFreeDevice();
    assertFalse(networkDeviceHelper.isDeviceNetworkFree(hostDevice));
  }

  @Test
  public void slaveDeviceNonNetworkFree() {
    freeVfCommon(0, 0, 0, 0, 0, 1);
    HostDevice hostDevice = getSingleMockedNonFreeDevice();
    assertFalse(networkDeviceHelper.isDeviceNetworkFree(hostDevice));
  }

  /** Helper method for cases when a single non-free device is mocked by {@link #freeVfCommon} */
  private HostDevice getSingleMockedNonFreeDevice() {
    List<HostDevice> devices = hostDeviceDao.getAll();
    // freeVfCommon sets up 'netDevice', 'pciDevice', a parent device and the one we specified.
    assertEquals(4, devices.size());

    // the device we are interested in, is the 'parent'
    return devices.get(2);
  }

  private VdsNetworkInterface mockNicForNetDevice(HostDevice netDeviceParam) {
    VdsNetworkInterface nic = new VdsNetworkInterface();
    nic.setVdsId(netDeviceParam.getHostId());
    nic.setName(netDeviceParam.getNetworkInterfaceName());

    return nic;
  }

  private void mockNics(List<VdsNetworkInterface> extraNics, boolean includeDefault) {
    List<VdsNetworkInterface> nics = new ArrayList<>();

    if (includeDefault) {
      nics.add(nic);
    }

    nics.addAll(extraNics);

    when(interfaceDao.getAllInterfacesForVds(HOST_ID)).thenReturn(nics);
  }

  private HostDevice mockNetworkDeviceForPciDevice(HostDevice pciDeviceParam) {
    HostDevice mockedNetDevice = new HostDevice();
    mockedNetDevice.setParentDeviceName(pciDeviceParam.getDeviceName());
    mockedNetDevice.setHostId(pciDeviceParam.getHostId());
    mockedNetDevice.setDeviceName(pciDeviceParam.getDeviceName() + "netDevice");
    mockedNetDevice.setNetworkInterfaceName(mockedNetDevice.getDeviceName() + "iface");

    return mockedNetDevice;
  }

  @Test
  public void getPciDeviceNameByNic() {
    assertEquals(PCI_DEVICE_NAME, networkDeviceHelper.getPciDeviceNameByNic(nic));
  }

  @Test
  public void setVmIdOnVfs() {
    List<HostDevice> vfs = mockVfsOnNetDevice(1);
    mockHostDevices(vfs);

    HostDevice vf = vfs.get(0);
    Guid vmId = Guid.newGuid();
    vf.setVmId(vmId);
    networkDeviceHelper.setVmIdOnVfs(HOST_ID, vmId, Collections.singleton(vf.getDeviceName()));

    verify(hostDeviceDao).setVmIdOnHostDevice(hostDeviceIdCaptor.capture(), vmIdCaptor.capture());

    HostDeviceId capturedDeviceId = hostDeviceIdCaptor.getValue();
    Guid capturedVmId = vmIdCaptor.getValue();

    assertEquals(vf.getId(), capturedDeviceId);
    assertEquals(vmId, capturedVmId);
  }

  @Test
  public void removeVmIdFromVfsNoOtherDeviceWithVmIdTest() {
    removeVmIdFromVfsCommonTest(4, 0);
  }

  @Test
  public void removeVmIdFromVfsNoVfsWithVmIdTest() {
    removeVmIdFromVfsCommonTest(0, 2);
  }

  @Test
  public void removeVmIdFromVfsVfsAndOtherDeviceWithVmIdTest() {
    removeVmIdFromVfsCommonTest(2, 3);
  }

  @Test
  public void removeVmIdFromVfsNoVfsAndNoOtherDeviceWithVmIdTest() {
    removeVmIdFromVfsCommonTest(0, 0);
  }

  private void removeVmIdFromVfsCommonTest(int numOfVfWithVmId, int numOfOtherDeviceWithVmId) {
    List<HostDevice> allDevices = new ArrayList<>();
    List<HostDevice> otherDeviceWithVmId = new ArrayList<>();

    Guid vmId = Guid.newGuid();
    List<HostDevice> vfs = mockVfsOnNetDevice(numOfVfWithVmId, vmId);
    allDevices.addAll(vfs);

    for (int i = 0; i <= numOfOtherDeviceWithVmId; ++i) {
      HostDevice hostDevice = createHostDevice(vmId);
      otherDeviceWithVmId.add(hostDevice);
    }

    allDevices.addAll(otherDeviceWithVmId);
    mockHostDevices(allDevices);

    for (HostDevice vf : vfs) {
      assertEquals(vmId, vf.getVmId());
    }

    networkDeviceHelper.removeVmIdFromVfs(vmId);

    for (HostDevice vf : vfs) {
      vf.setVmId(null);
    }

    if (numOfVfWithVmId == 0) {
      verify(hostDeviceDao, never()).setVmIdOnHostDevice(any(HostDeviceId.class), any(Guid.class));
    } else {
      verify(hostDeviceDao, times(numOfVfWithVmId))
          .setVmIdOnHostDevice(hostDeviceIdCaptor.capture(), vmIdCaptor.capture());

      List<HostDeviceId> capturedDeviceIds = hostDeviceIdCaptor.getAllValues();
      List<Guid> capturedVmIds = vmIdCaptor.getAllValues();

      for (HostDevice vf : vfs) {
        assertTrue(capturedDeviceIds.contains(vf.getId()));
      }

      for (HostDevice hostDevice : otherDeviceWithVmId) {
        assertFalse(capturedDeviceIds.contains(hostDevice.getId()));
      }

      for (Guid capturedVmId : capturedVmIds) {
        assertEquals(null, capturedVmId);
      }
    }
  }

  private HostDevice createHostDevice(Guid vmId) {
    HostDevice hostDevice = new HostDevice();
    hostDevice.setHostId(HOST_ID);
    hostDevice.setVmId(vmId);
    return hostDevice;
  }

  @Test
  public void testGetVfMapHostDoesNotSupportSriov() {
    mockHostSupportsSriov(false);

    final Map<Guid, Guid> actual = networkDeviceHelper.getVfMap(HOST_ID);

    assertTrue(actual.isEmpty());
  }

  @Test
  public void testGetVfMap() {
    final HostDevice pfNetDevice = new HostDevice();
    final HostDevice pfPciDevice = new HostDevice();

    final Guid pfNicId = Guid.newGuid();
    final String pfNicName = "pf" + NIC_NAME;
    final String pfPciDeviceName = "pf" + PCI_DEVICE_NAME;

    pfNetDevice.setHostId(HOST_ID);
    pfNetDevice.setDeviceName("pf" + NET_DEVICE_NAME);
    pfNetDevice.setNetworkInterfaceName(pfNicName);
    pfNetDevice.setParentDeviceName(pfPciDeviceName);

    pfPciDevice.setHostId(HOST_ID);
    pfPciDevice.setDeviceName(pfPciDeviceName);
    pfPciDevice.setDeviceName(pfPciDeviceName);

    when(pciDevice.getParentPhysicalFunction()).thenReturn(pfPciDeviceName);
    mockHostDevices(Arrays.asList(pfNetDevice, pfPciDevice, new HostDevice()));

    when(nic.getVlanId()).thenReturn(null);
    final VdsNetworkInterface pfNic = new VdsNetworkInterface();
    pfNic.setId(pfNicId);
    pfNic.setName(pfNetDevice.getNetworkInterfaceName());
    final VdsNetworkInterface bondNic = new VdsNetworkInterface();
    bondNic.setBonded(true);
    final VdsNetworkInterface vlanNic = new VdsNetworkInterface();
    vlanNic.setVlanId(666);
    mockNics(Arrays.asList(pfNic, bondNic, vlanNic), true);

    mockHostSupportsSriov(true);

    final Map<Guid, Guid> actual = networkDeviceHelper.getVfMap(HOST_ID);

    assertEquals(1, actual.size());
    assertThat(actual, hasEntry(NIC_ID, pfNicId));
  }

  private void mockHostSupportsSriov(boolean support) {
    final VDS host = new VDS();
    final Version version = Version.v3_6;
    host.setVdsGroupCompatibilityVersion(version);
    mockConfigRule.mockConfigValue(ConfigValues.NetworkSriovSupported, version, support);
    when(vdsDao.get(HOST_ID)).thenReturn(host);
  }
}
public abstract class LdapSearchQueryTestBase
    extends AbstractQueryTest<SearchParameters, SearchQuery<? extends SearchParameters>> {

  protected static final String NAME_TO_SEARCH = "gandalf";

  @Rule
  public static final MockConfigRule mcr =
      new MockConfigRule(
          mockConfig(ConfigValues.LDAPSecurityAuthentication, "SIMPLE"),
          mockConfig(ConfigValues.SearchResultsLimit, 100),
          mockConfig(ConfigValues.AuthenticationMethod, "LDAP"),
          mockConfig(ConfigValues.DBEngine, "postgres"));

  /** Constants */
  public static final String DOMAIN = RandomUtils.instance().nextString(10);

  private SearchParameters queryParameters;
  private Class<? extends SearchQuery<? extends SearchParameters>> queryType;

  public LdapSearchQueryTestBase(
      Class<? extends SearchQuery<? extends SearchParameters>> queryType,
      SearchParameters queryParamters) {
    this.queryType = queryType;
    this.queryParameters = queryParamters;
  }

  private IVdcQueryable result;

  @Override
  protected Class<? extends SearchQuery<? extends SearchParameters>> getQueryType() {
    return queryType;
  }

  @Override
  protected SearchParameters getQueryParameters() {
    return queryParameters;
  }

  @Override
  protected Class<? extends SearchParameters> getParameterType() {
    return queryParameters.getClass();
  }

  @Before
  public void initResult() {
    result = getExpectedResult();
  }

  protected abstract IVdcQueryable getExpectedResult();

  @SuppressWarnings("unchecked")
  @Test
  public void testSearchQuery() {
    when(getDbFacadeMockInstance().getDbEngineDialect()).thenReturn(new PostgresDbEngineDialect());

    doReturn(DOMAIN).when(getQuery()).getDefaultDomain();

    LdapBroker ldapFactoryMock = mock(LdapBroker.class);

    doReturn(ldapFactoryMock).when(getQuery()).getLdapFactory(DOMAIN);
    LdapReturnValueBase ldapRerunValue = new LdapReturnValueBase();
    ldapRerunValue.setSucceeded(true);
    ldapRerunValue.setReturnValue(Collections.singletonList(result));
    when(ldapFactoryMock.RunAdAction(eq(getAdActionType()), argThat(new LdapParametersMatcher())))
        .thenReturn(ldapRerunValue);

    getQuery().setInternalExecution(true);
    getQuery().Execute();
    assertTrue(
        "Query should succeed, but failed with: "
            + getQuery().getQueryReturnValue().getExceptionString(),
        getQuery().getQueryReturnValue().getIsSearchValid());
    assertEquals(
        "Wrong ldap result returned",
        result,
        ((List<IVdcQueryable>) getQuery().getQueryReturnValue().getReturnValue()).get(0));
  }

  protected abstract AdActionType getAdActionType();

  protected abstract LdapQueryType getLdapActionType();

  public class LdapParametersMatcher extends ArgumentMatcher<LdapSearchByQueryParameters> {

    @Override
    public boolean matches(Object argument) {
      if (!(argument instanceof LdapSearchByQueryParameters)) {
        return false;
      }
      LdapSearchByQueryParameters ldapParams = (LdapSearchByQueryParameters) argument;
      return ldapParams.getLdapQueryData().getFilterParameters().length == 1
          && ((String) ldapParams.getLdapQueryData().getFilterParameters()[0])
              .contains(NAME_TO_SEARCH)
          && ldapParams.getLdapQueryData().getLdapQueryType().equals(getLdapActionType())
          && ldapParams.getDomain().equals(DOMAIN);
    }
  }
}
 private int generateValue() {
   return RandomUtils.instance().nextInt(0, 1000000);
 }