use of com.bonree.brfs.disknode.client.DiskNodeClient in project BRFS by zhangnianli.
the class FileRecoveryMessageHandler method handleMessage.
@Override
public void handleMessage(BaseMessage baseMessage, ResponseWriter<BaseResponse> writer) {
FileRecoveryMessage message = ProtoStuffUtils.deserialize(baseMessage.getBody(), FileRecoveryMessage.class);
if (message == null) {
LOG.error("decode recover message error");
writer.write(new BaseResponse(ResponseCode.ERROR_PROTOCOL));
return;
}
String filePath = null;
try {
filePath = context.getConcreteFilePath(message.getFilePath());
LOG.info("starting recover file[{}]", filePath);
Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(filePath, false);
if (binding == null) {
writer.write(new BaseResponse(ResponseCode.ERROR));
return;
}
binding.first().position(fileFormater.absoluteOffset(message.getOffset()));
byte[] bytes = null;
for (String stateString : message.getSources()) {
FileObjectSyncState state = SyncStateCodec.fromString(stateString);
Service service = serviceManager.getServiceById(state.getServiceGroup(), state.getServiceId());
if (service == null) {
LOG.error("can not get service with[{}:{}]", state.getServiceGroup(), state.getServiceId());
continue;
}
DiskNodeClient client = null;
try {
LOG.info("get data from{} to recover...", service);
TcpClient<ReadObject, FileContentPart> readClient = clientGroup.createClient(new AsyncFileReaderCreateConfig() {
@Override
public SocketAddress remoteAddress() {
return new InetSocketAddress(service.getHost(), service.getExtraPort());
}
@Override
public int connectTimeoutMillis() {
return 3000;
}
@Override
public int maxPendingRead() {
return 0;
}
}, ForkJoinPool.commonPool());
client = new TcpDiskNodeClient(null, readClient);
long lackBytes = state.getFileLength() - message.getOffset();
CompletableFuture<byte[]> byteFuture = new CompletableFuture<byte[]>();
ByteArrayOutputStream output = new ByteArrayOutputStream();
client.readData(state.getFilePath(), message.getOffset(), (int) lackBytes, new ByteConsumer() {
@Override
public void error(Throwable e) {
byteFuture.completeExceptionally(e);
}
@Override
public void consume(byte[] bytes, boolean endOfConsume) {
try {
output.write(bytes);
if (endOfConsume) {
byteFuture.complete(output.toByteArray());
output.close();
}
} catch (Exception e) {
byteFuture.completeExceptionally(e);
}
}
});
bytes = byteFuture.get();
if (bytes != null) {
LOG.info("read bytes length[{}], require[{}]", bytes.length, lackBytes);
break;
}
} catch (Exception e) {
LOG.error("recover file[{}] error", filePath, e);
} finally {
CloseUtils.closeQuietly(client);
}
}
if (bytes == null) {
writer.write(new BaseResponse(ResponseCode.ERROR));
return;
}
int offset = 0;
int size = 0;
while ((size = FileDecoder.getOffsets(offset, bytes)) > 0) {
LOG.info("rewrite data[offset={}, size={}] to file[{}]", offset, size, filePath);
binding.first().write(bytes, offset, size);
offset += size;
size = 0;
}
if (offset != bytes.length) {
LOG.error("perhaps datas that being recoverd is not correct! get [{}], but recoverd[{}]", bytes.length, offset);
}
writer.write(new BaseResponse(ResponseCode.OK));
} catch (Exception e) {
LOG.error("recover file[{}] error", filePath, e);
writer.write(new BaseResponse(ResponseCode.ERROR));
}
}
use of com.bonree.brfs.disknode.client.DiskNodeClient in project BRFS by zhangnianli.
the class RecoveryMessageHandler method handle.
@Override
public void handle(HttpMessage msg, HandleResultCallback callback) {
HandleResult handleResult = new HandleResult();
String filePath = null;
try {
filePath = context.getConcreteFilePath(msg.getPath());
LOG.info("starting recover file[{}]", filePath);
String lengthParam = msg.getParams().get("length");
if (lengthParam == null) {
handleResult.setSuccess(false);
callback.completed(handleResult);
return;
}
long fileLength = Long.parseLong(msg.getParams().get("length"));
List<String> fullStates = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(msg.getParams().get("fulls"));
Pair<RecordFileWriter, WriteWorker> binding = writerManager.getBinding(filePath, false);
if (binding == null) {
handleResult.setSuccess(false);
callback.completed(handleResult);
return;
}
binding.first().position(fileFormater.absoluteOffset(fileLength));
byte[] bytes = null;
for (String stateString : fullStates) {
FileObjectSyncState state = SyncStateCodec.fromString(stateString);
Service service = serviceManager.getServiceById(state.getServiceGroup(), state.getServiceId());
if (service == null) {
LOG.error("can not get service with[{}:{}]", state.getServiceGroup(), state.getServiceId());
continue;
}
DiskNodeClient client = null;
try {
LOG.info("get data from{} to recover...", service);
client = new HttpDiskNodeClient(service.getHost(), service.getPort());
long lackBytes = state.getFileLength() - fileLength;
CompletableFuture<byte[]> byteFuture = new CompletableFuture<byte[]>();
ByteArrayOutputStream output = new ByteArrayOutputStream();
client.readData(state.getFilePath(), fileLength, (int) lackBytes, new ByteConsumer() {
@Override
public void error(Throwable e) {
byteFuture.completeExceptionally(e);
}
@Override
public void consume(byte[] bytes, boolean endOfConsume) {
try {
output.write(bytes);
if (endOfConsume) {
byteFuture.complete(output.toByteArray());
output.close();
}
} catch (Exception e) {
byteFuture.completeExceptionally(e);
}
}
});
bytes = byteFuture.get();
if (bytes != null) {
LOG.info("read bytes length[{}], require[{}]", bytes.length, lackBytes);
break;
}
} catch (Exception e) {
LOG.error("recover file[{}] error", filePath, e);
} finally {
CloseUtils.closeQuietly(client);
}
}
if (bytes == null) {
handleResult.setSuccess(false);
callback.completed(handleResult);
return;
}
int offset = 0;
int size = 0;
while ((size = FileDecoder.getOffsets(offset, bytes)) > 0) {
LOG.info("rewrite data[offset={}, size={}] to file[{}]", offset, size, filePath);
binding.first().write(bytes, offset, size);
offset += size;
size = 0;
}
if (offset != bytes.length) {
LOG.error("perhaps datas that being recoverd is not correct! get [{}], but recoverd[{}]", bytes.length, offset);
}
handleResult.setSuccess(true);
} catch (Exception e) {
LOG.error("recover file[{}] error", filePath, e);
handleResult.setSuccess(false);
} finally {
callback.completed(handleResult);
}
}
use of com.bonree.brfs.disknode.client.DiskNodeClient in project BRFS by zhangnianli.
the class CopyCountCheck method collectionSnFiles.
/**
* 概述:获取集群对应目录的文件
* @param services
* @param snList
* @return
* @user <a href=mailto:zhucg@bonree.com>朱成岗</a>
*/
public static Map<StorageRegion, List<String>> collectionSnFiles(List<Service> services, List<StorageRegion> snList, final Map<String, Long> snTimes) throws Exception {
Map<StorageRegion, List<String>> snMap = new HashMap<>();
DiskNodeClient client = null;
int reCount;
String snName = null;
String path;
List<String> strs;
long time;
String dirName;
String sid;
ManagerContralFactory mcf = ManagerContralFactory.getInstance();
ServerIDManager sim = mcf.getSim();
CuratorClient zkClient = mcf.getClient();
SecondIDParser parser;
String basePath = mcf.getZkPath().getBaseRoutePath();
int timeout = 10000;
for (Service service : services) {
try {
client = TcpClientUtils.getClient(service.getHost(), service.getPort(), service.getExtraPort(), timeout);
long granule;
for (StorageRegion sn : snList) {
parser = new SecondIDParser(zkClient, sn.getId(), basePath);
parser.updateRoute();
sid = sim.getOtherSecondID(service.getServiceId(), sn.getId());
granule = Duration.parse(sn.getFilePartitionDuration()).toMillis();
reCount = sn.getReplicateNum();
snName = sn.getName();
if (!snTimes.containsKey(snName)) {
LOG.debug("sntime don't contain {}", snName);
continue;
}
time = snTimes.get(snName);
dirName = TimeUtils.timeInterval(time, granule);
for (int i = 1; i <= reCount; i++) {
path = "/" + snName + "/" + i + "/" + dirName;
LOG.debug("path :{}", path);
strs = getFileList(parser, client, path, sid);
if (strs == null || strs.isEmpty()) {
LOG.debug("files is empty {}", path);
continue;
}
LOG.debug("Collection dirName :{},{} size :{}", dirName, path, strs.size());
if (!snMap.containsKey(sn)) {
snMap.put(sn, new ArrayList<>());
}
snMap.get(sn).addAll(strs);
}
}
} catch (Exception e) {
EmailPool emailPool = EmailPool.getInstance();
MailWorker.Builder builder = MailWorker.newBuilder(emailPool.getProgramInfo());
builder.setModel("collect file execute 模块服务发生问题");
builder.setException(e);
builder.setMessage(mcf.getGroupName() + "(" + mcf.getServerId() + ")服务 执行任务时发生问题");
Map<String, String> map = new HashedMap();
map.put("remote ", service.getHost());
map.put("connectTimeout", String.valueOf(timeout));
map.put("sn", StringUtils.isEmpty(snName) ? "" : snName);
if (snTimes != null && !snTimes.isEmpty()) {
map.put("sntime", JSON.toJSONString(snTimes));
}
builder.setVariable(map);
emailPool.sendEmail(builder);
throw e;
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
LOG.error("{}", e);
}
}
}
}
return clearUnLawFiles(snMap);
}
use of com.bonree.brfs.disknode.client.DiskNodeClient in project BRFS by zhangnianli.
the class DataEmitter method emit.
public void emit(byte[] data, FileNode fileNode, WriteCallback callback) {
int[] duplicates = fileNode.getDuplicates();
DiskNodeClient[] clients = new DiskNodeClient[duplicates.length];
for (int i = 0; i < duplicates.length; i++) {
if (!clientCaches.containsKey(duplicates[i])) {
DiskNodeClient client = new HttpDiskNodeClient("localhost", 8080);
clientCaches.put(duplicates[i], client);
}
clients[i] = clientCaches.get(duplicates[i]);
}
for (DiskNodeClient client : clients) {
ResultGather gather = new ResultGather(clients.length, callback);
ListenableFuture<WriteResult> f = execs.submit(new WriteTask(client, fileNode, data));
Futures.addCallback(f, gather, execs);
}
}
use of com.bonree.brfs.disknode.client.DiskNodeClient in project BRFS by zhangnianli.
the class DefaultFileObjectSyncProcessor method doSynchronize.
private boolean doSynchronize(FileNode fileNode, long correctLength, List<FileObjectSyncState> lacks, List<FileObjectSyncState> fulls) {
List<String> fullStates = new ArrayList<String>();
for (FileObjectSyncState state : fulls) {
fullStates.add(SyncStateCodec.toString(state));
}
boolean allSynced = true;
for (FileObjectSyncState state : lacks) {
DiskNodeConnection connection = connectionPool.getConnection(state.getServiceGroup(), state.getServiceId());
if (connection == null) {
LOG.error("can not recover file[{}], because of lack of connection to service[{}, {}]", fileNode.getName(), state.getServiceGroup(), state.getServiceId());
allSynced = false;
continue;
}
DiskNodeClient client = connection.getClient();
if (client == null) {
allSynced = false;
continue;
}
LOG.info("start synchronize file[{}] at data node[{}, {}]", fileNode.getName(), state.getServiceGroup(), state.getServiceId());
if (!client.recover(state.getFilePath(), state.getFileLength(), fullStates)) {
LOG.error("can not synchronize file[{}] at data node[{}, {}]", fileNode.getName(), state.getServiceGroup(), state.getServiceId());
allSynced = false;
}
}
return allSynced;
}
Aggregations