Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mac address save on the basis of ipv4address WAPI #576

Merged
merged 1 commit into from Nov 16, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -416,6 +416,13 @@ public ResponseEntity<Void> createHostnameIPMapping(AssetIPMapping mapping) {
HttpMethod.POST, postEntity, Void.class);
}

public ResponseEntity<Void> updateHostnameIPMapping(AssetIPMapping mapping) {
HttpEntity<Object> postEntity =
new HttpEntity<Object>(mapping, buildHeaders());
return this.restTemplate.exchange(getAPIServiceEndpoint() + HostNameIPMapping,
HttpMethod.PUT, postEntity, Void.class);
}

public ResponseEntity<Asset> getAssetByName(String name){
return this.restTemplate.exchange(
getAPIServiceEndpoint() + String.format(GetAssetByName, name), HttpMethod.GET,
Expand Down
Expand Up @@ -15,6 +15,7 @@
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
Expand Down Expand Up @@ -583,13 +584,17 @@ public void updateHostNameIPMapping(@RequestBody AssetIPMapping mapping) {
}
AssetIPMapping oldMapping = oldMappingOptional.get();
String assetName = mapping.getAssetname();
if(oldMapping.getAssetname().equals(assetName)) {
return;
String macAddress = mapping.getMacAddress();
if(StringUtils.equals(oldMapping.getAssetname(), assetName)) {
if (StringUtils.equals(macAddress, oldMapping.getMacAddress())) {
return;
}
}
if(!assetService.isAssetNameValidate(assetName)) {
throw new WormholeRequestException(HttpStatus.INTERNAL_SERVER_ERROR,"Can't find any asset with the name : " + mapping.getAssetname(),null);
}
oldMapping.setAssetname(mapping.getAssetname());
oldMapping.setMacAddress(mapping.getMacAddress());
assetIPMappingRepository.save(oldMapping);
}

Expand Down
Expand Up @@ -633,7 +633,8 @@ public void getHostNameByIPExample() throws Exception {
FieldDescriptor[] fieldpath = new FieldDescriptor[] {
fieldWithPath("id").description("ID of the AssetIPMapping, created by flowgate"),
fieldWithPath("ip").description("IP of AssetIPMapping."),
fieldWithPath("assetname").description("name of asset.") };
fieldWithPath("macAddress").description("macAddress of IP."),
fieldWithPath("assetname").description("name of asset."), };
this.mockMvc.perform(get("/v1/assets/mapping/hostnameip/ip/" + mapping1.getIp()))
.andExpect(status().isOk())
.andDo(document("assets-getHostNameByIP-example",
Expand Down Expand Up @@ -1221,13 +1222,15 @@ public void createHostNameIPMappingExample() throws Exception {
AssetIPMapping assetipmapping = createAssetIPMapping();
assetipmapping.setAssetname(server.getAssetName());
assetipmapping.setIp("192.168.0.1");
assetipmapping.setMacAddress("50:00:56:ge:64:62");
this.mockMvc
.perform(post("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(assetipmapping)))
.andExpect(status().isCreated())
.andDo(document("assets-createHostNameIPMapping-example", requestFields(
fieldWithPath("id").description("ID of the asset, created by flowgate"),
fieldWithPath("ip").description("ip of hostname"),
fieldWithPath("macAddress").description("macAddress of IP"),
fieldWithPath("assetname").description(
"The name of the asset in the third part DCIM/CMDB systems. Usually it will be a unique identifier of an asset"))));
assetipmapping = assetIPMappingRepository.findById(assetipmapping.getId()).get();
Expand All @@ -1243,6 +1246,7 @@ public void createHostNameAndIPMappingFailureExample() throws Exception {
AssetIPMapping mapping = new AssetIPMapping();
mapping.setAssetname("cloud-sha1-esx2");
mapping.setIp("10.15");
mapping.setMacAddress("00:50:56:be:60:62");
MvcResult result = this.mockMvc
.perform(post("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(mapping)))
Expand All @@ -1266,6 +1270,7 @@ public void createHostNameAndIPMappingFailureExample2() throws Exception {
AssetIPMapping mapping = createAssetIPMapping();
mapping.setAssetname("cloud-sha1-esx8");
mapping.setIp("192.168.0.1");
mapping.setMacAddress("50:00:56:ge:64:62");
expectedEx.expect(WormholeRequestException.class);
expectedEx.expectMessage("Can't find any asset with the name : " + mapping.getAssetname());
MvcResult result = this.mockMvc
Expand All @@ -1282,6 +1287,7 @@ public void createHostNameAndIPMappingFailureExample2() throws Exception {
public void deleteAssetIPAndNameMappingExample() throws Exception {
AssetIPMapping assetipmapping = createAssetIPMapping();
assetipmapping.setAssetname("cloud-server");
assetipmapping.setMacAddress("00:50:56:be:60:62");
assetipmapping = assetIPMappingRepository.save(assetipmapping);
this.mockMvc.perform(delete("/v1/assets/mapping/hostnameip/" + assetipmapping.getId()))
.andExpect(status().isOk()).andDo(document("assets-deleteAssetIPAndNameMapping-example"));
Expand All @@ -1308,21 +1314,64 @@ public void updateHostNameIPMappingExample() throws Exception {
AssetIPMapping newAssetIPMapping = createAssetIPMapping();
newAssetIPMapping.setAssetname(server1.getAssetName());
newAssetIPMapping.setId(assetipmapping.getId());
newAssetIPMapping.setMacAddress("00:50:56:be:60:62");
newAssetIPMapping.setIp("192.168.0.1");
this.mockMvc
.perform(post("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.perform(put("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newAssetIPMapping)))
.andExpect(status().isCreated())
.andExpect(status().isOk())
.andDo(document("assets-updateHostNameIPMapping-example", requestFields(
fieldWithPath("id").description("ID of the asset, created by flowgate"),
fieldWithPath("ip").description("ip of hostname"),
fieldWithPath("macAddress").description("macAddress of IP"),
fieldWithPath("assetname").description(
"The name of the asset in the third part DCIM/CMDB systems. Usually it will be a unique identifier of an asset"))));
assetipmapping = assetIPMappingRepository.findById(assetipmapping.getId()).get();
assetRepository.deleteById(server.getId());
assetRepository.deleteById(server1.getId());
assetIPMappingRepository.deleteById(assetipmapping.getId());
TestCase.assertEquals(server1.getAssetName(), assetipmapping.getAssetname());
TestCase.assertEquals("00:50:56:be:60:62", assetipmapping.getMacAddress());
}

@Test
public void updateHostNameIPMappingMacIsNullExample() throws Exception {
SetOperations<String,String> setOperations = Mockito.mock(SetOperations.class);
when(template.hasKey(anyString())).thenReturn(false);
when(template.opsForSet()).thenReturn(setOperations);
when(setOperations.add(anyString(), any())).thenReturn(1l);
Asset server = createAsset();
server.setCategory(AssetCategory.Server);
server.setAssetName("cloud-sha1-esx2");
server = assetRepository.save(server);
Asset server1 = createAsset();
server1.setCategory(AssetCategory.Server);
server1.setAssetName("cloud-sha1-esx8");
server1 = assetRepository.save(server1);
AssetIPMapping assetipmapping = createAssetIPMapping();
assetipmapping.setAssetname(server.getAssetName());
assetipmapping = assetIPMappingRepository.save(assetipmapping);

AssetIPMapping newAssetIPMapping = createAssetIPMapping();
newAssetIPMapping.setAssetname(server1.getAssetName());
newAssetIPMapping.setId(assetipmapping.getId());
newAssetIPMapping.setMacAddress(null);
this.mockMvc
.perform(put("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newAssetIPMapping)))
.andExpect(status().isOk())
.andDo(document("assets-updateHostNameIPMapping-example", requestFields(
fieldWithPath("id").description("ID of the asset, created by flowgate"),
fieldWithPath("ip").description("ip of hostname"),
fieldWithPath("macAddress").description("macAddress of IP"),
fieldWithPath("assetname").description(
"The name of the asset in the third part DCIM/CMDB systems. Usually it will be a unique identifier of an asset"))));
assetipmapping = assetIPMappingRepository.findById(assetipmapping.getId()).get();
assetRepository.deleteById(server.getId());
assetRepository.deleteById(server1.getId());
assetIPMappingRepository.deleteById(assetipmapping.getId());
TestCase.assertEquals(server1.getAssetName(), assetipmapping.getAssetname());
TestCase.assertNull(assetipmapping.getMacAddress());
}

@Test
Expand All @@ -1349,7 +1398,7 @@ public void updateHostNameIPMappingFailureExample() throws Exception {
expectedEx.expect(WormholeRequestException.class);
expectedEx.expectMessage("Can't find any asset with the name : " + newAssetIPMapping.getAssetname());
MvcResult result = this.mockMvc
.perform(post("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.perform(put("/v1/assets/mapping/hostnameip").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(newAssetIPMapping)))
.andExpect(status().is5xxServerError())
.andReturn();
Expand All @@ -1371,6 +1420,7 @@ public void getHostNameIPMappingByPage() throws Exception {
.andExpect(status().isOk())
.andExpect(jsonPath("$..totalPages").value(1))
.andExpect(jsonPath("$..content[0].ip").value(assetipmapping.getIp()))
.andExpect(jsonPath("$..content[0].macAddress").value(assetipmapping.getMacAddress()))
.andExpect(jsonPath("$..content[0].assetname").value(assetipmapping.getAssetname()))
.andDo(document("assets-getHostNameIPMappingByPage-example",
responseFields(subsectionWithPath("content").description("AssetIPMapping's array."),
Expand Down Expand Up @@ -2283,6 +2333,7 @@ AssetIPMapping createAssetIPMapping() {
AssetIPMapping assetipmapping = new AssetIPMapping();
assetipmapping.setId(UUID.randomUUID().toString());
assetipmapping.setAssetname("assetname");
assetipmapping.setMacAddress("00:50:56:be:60:62");
assetipmapping.setIp("127.0.0.1");
return assetipmapping;
}
Expand Down
Expand Up @@ -12,6 +12,7 @@ public class AssetIPMapping implements BaseDocument {
private String id;
private String ip;
private String assetname;
private String macAddress;
public String getId() {
return id;
}
Expand All @@ -30,6 +31,10 @@ public String getAssetname() {
public void setAssetname(String assetname) {
this.assetname = assetname;
}


public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
}
5 changes: 5 additions & 0 deletions infoblox-worker/pom.xml
Expand Up @@ -68,6 +68,11 @@
<artifactId>javax.servlet-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
</dependencies>

<build>
Expand Down
Expand Up @@ -7,12 +7,12 @@
import java.net.ConnectException;
import java.util.List;

import com.vmware.flowgate.infobloxworker.model.InfoBloxIPInfoResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
Expand Down Expand Up @@ -63,10 +63,10 @@ public void executeAsync(EventMessage eventMessage) {
continue;
}
InfobloxClient client = new InfobloxClient(infoblox);
List<String> hostNames = null;
List<InfoBloxIPInfoResult> infoBloxIPInfoResults = null;
IntegrationStatus integrationStatus = infoblox.getIntegrationStatus();
try {
hostNames = client.queryHostNamesByIP(message);
infoBloxIPInfoResults = client.queryHostNamesByIP(message);
}catch(ResourceAccessException e) {
if(e.getCause().getCause() instanceof ConnectException) {
checkAndUpdateIntegrationStatus(infoblox, e.getCause().getCause().getMessage());
Expand All @@ -89,28 +89,33 @@ public void executeAsync(EventMessage eventMessage) {
updateIntegrationStatus(infoblox);
}

if (hostNames != null && !hostNames.isEmpty()) {
for (String hostname : hostNames) {
if (infoBloxIPInfoResults != null && !infoBloxIPInfoResults.isEmpty()) {
for (InfoBloxIPInfoResult infoBloxIPInfoResult : infoBloxIPInfoResults) {
try {
ResponseEntity<Asset> asset = wormholeAPIClient.getAssetByName(hostname);
Asset asset = wormholeAPIClient.getAssetByName(infoBloxIPInfoResult.getHostName()).getBody();
if (asset == null) {
logger.info(String.format("hostname (%s) no found!", hostname));
logger.info(String.format("hostname (%s) no found!", infoBloxIPInfoResult.getHostName()));
continue;
}
} catch (HttpClientErrorException e) {
logger.error(String.format("Error when searching %s", hostname), e);
logger.error(String.format("Error when searching %s", infoBloxIPInfoResult.getHostName()), e);
continue;
}
AssetIPMapping tempMapping = new AssetIPMapping();
tempMapping.setAssetname(hostname);
tempMapping.setAssetname(infoBloxIPInfoResult.getHostName());
tempMapping.setMacAddress(infoBloxIPInfoResult.getMacAddress());
tempMapping.setIp(message);

AssetIPMapping[] mappings =
wormholeAPIClient.getHostnameIPMappingByIP(message).getBody();
boolean isNewMapping = true;
if (null != mappings && mappings.length > 0) {
for (AssetIPMapping mapping : mappings) {
if (hostname.equals(mapping.getAssetname())) {
if (tempMapping.getAssetname().equals(mapping.getAssetname())) {
if (!StringUtils.equals(mapping.getMacAddress(), tempMapping.getMacAddress())) {
mapping.setMacAddress(tempMapping.getMacAddress());
wormholeAPIClient.updateHostnameIPMapping(mapping);
}
isNewMapping = false;
break;
}
Expand All @@ -119,15 +124,15 @@ public void executeAsync(EventMessage eventMessage) {
if (isNewMapping) {
wormholeAPIClient.createHostnameIPMapping(tempMapping);
}
logger.info(String.format("Find hostname %s for ip %s", hostname, message));
logger.info(String.format("Find hostname %s for ip %s", infoBloxIPInfoResult.getHostName(), message));
return;
}
}
}
logger.info(String.format("Cannot find the hostname for IP: %s", message));
}

public void checkAndUpdateIntegrationStatus(FacilitySoftwareConfig infoblox,String message) {
private void checkAndUpdateIntegrationStatus(FacilitySoftwareConfig infoblox,String message) {
IntegrationStatus integrationStatus = infoblox.getIntegrationStatus();
if(integrationStatus == null) {
integrationStatus = new IntegrationStatus();
Expand Down
@@ -0,0 +1,73 @@
package com.vmware.flowgate.infobloxworker.model;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

public class InfoBloxIPInfoResult implements Serializable {

private String hostName;
private String ipAddress;
private String macAddress;

public InfoBloxIPInfoResult() {
}

public static InfoBloxIPInfoResult build(String hostName, Infoblox infoblox) {
InfoBloxIPInfoResult infoBloxIPInfoResult = new InfoBloxIPInfoResult();
final String ipAddress = infoblox.getIpAddress();
final String macAddress;
final String hostNameWithoutZone;
if (StringUtils.isNotBlank(infoblox.getMacAddress())) {
macAddress = infoblox.getMacAddress();
} else if (infoblox.getDiscoveredData() != null && StringUtils.isNotBlank(infoblox.getDiscoveredData().getMacAddress())) {
macAddress = infoblox.getDiscoveredData().getMacAddress();
} else {
macAddress = null;
}
int index = hostName.indexOf(".");
if (index > 0) {
hostNameWithoutZone = hostName.substring(0, index);
} else {
hostNameWithoutZone = hostName;
}

infoBloxIPInfoResult.setIpAddress(ipAddress);
infoBloxIPInfoResult.setMacAddress(macAddress);
infoBloxIPInfoResult.setHostName(hostNameWithoutZone);
return infoBloxIPInfoResult;
}

public String getHostName() {
return hostName;
}

public void setHostName(String hostName) {
this.hostName = hostName;
}

public String getIpAddress() {
return ipAddress;
}

public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}

public String getMacAddress() {
return macAddress;
}

public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}

@Override
public String toString() {
return "InfoBloxResult{" +
"hostName='" + hostName + '\'' +
", ipAddress='" + ipAddress + '\'' +
", macAddress='" + macAddress + '\'' +
'}';
}
}