[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-18 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r325992600
 
 

 ##
 File path: 
server/src/test/java/org/apache/iotdb/db/sync/receiver/load/FileLoaderTest.java
 ##
 @@ -0,0 +1,434 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Random;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.StorageGroupProcessor;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.StartupException;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.service.IoTDB;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.EnvironmentUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoaderTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoaderTest.class);
+  private static final String SG_NAME = "root.sg";
+  private static IoTDB daemon;
+  private String dataDir;
+  private FileLoader fileLoader;
+
+  @Before
+  public void setUp()
+  throws IOException, InterruptedException, StartupException, 
DiskSpaceInsufficientException, MetadataErrorException {
+EnvironmentUtils.closeStatMonitor();
+daemon = IoTDB.getInstance();
+daemon.active();
+EnvironmentUtils.envSetUp();
+dataDir = new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile())
+.getParentFile().getAbsolutePath();
+initMetadata();
+  }
+
+  private void initMetadata() throws MetadataErrorException {
+MManager mmanager = MManager.getInstance();
+mmanager.init();
+mmanager.clear();
+mmanager.setStorageLevelToMTree("root.sg0");
+mmanager.setStorageLevelToMTree("root.sg1");
+mmanager.setStorageLevelToMTree("root.sg2");
+  }
+
+  @After
+  public void tearDown() throws InterruptedException, IOException, 
StorageEngineException {
+daemon.stop();
+EnvironmentUtils.cleanEnv();
+  }
+
+  @Test
+  public void loadNewTsfiles() throws IOException, StorageEngineException {
+fileLoader = FileLoader.createFileLoader(getReceiverFolderFile());
+Map> allFileList = new HashMap<>();
+Map> correctSequenceLoadedFileMap = new HashMap<>();
+
+// add some new tsfiles
+Random r = new Random(0);
+long time = System.currentTimeMillis();
+for (int i = 0; i < 3; i++) {
+  for (int j = 0; j < 10; j++) {
+allFileList.putIfAbsent(SG_NAME + i, new ArrayList<>());
+correctSequenceLoadedFileMap.putIfAbsent(SG_NAME + i, new HashSet<>());
+String rand = String.valueOf(r.nextInt(1));
+String fileName =
+getSnapshotFolder() + File.separator + SG_NAME + i + 
File.separator + (time + i * 100
++ j) + IoTDBConstant.FILE_NAME_SEPARATOR + rand
++ IoTDBConstant.FILE_NAME_SEPARATOR + "0.tsfile";
+File syncFile = new File(fileName);
+File dataFile = new File(
+
syncFile.getParentFile().getParentFile().getParentFile().getParentFile()
+.getParentFile(), IoTDBConstant.SEQUENCE_FLODER_NAME
++ File.separatorChar + syncFile.getParentFile().getName() + 
File.separatorChar
++ syncFile.getName());
+correctSequenceLoadedFileMap.get(SG_NAME + 
i).add(dataFile.getAbsolutePath());
+allFileList.get(SG_NAME + i).add(syncFile);
+if (!syncFile.getParentFile().exists()) {
+   

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-18 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r325992475
 
 

 ##
 File path: 
server/src/test/java/org/apache/iotdb/db/sync/receiver/load/FileLoaderTest.java
 ##
 @@ -0,0 +1,434 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Random;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.StorageGroupProcessor;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.StartupException;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.service.IoTDB;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.EnvironmentUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoaderTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoaderTest.class);
+  private static final String SG_NAME = "root.sg";
+  private static IoTDB daemon;
+  private String dataDir;
+  private FileLoader fileLoader;
+
+  @Before
+  public void setUp()
+  throws IOException, InterruptedException, StartupException, 
DiskSpaceInsufficientException, MetadataErrorException {
+EnvironmentUtils.closeStatMonitor();
+daemon = IoTDB.getInstance();
+daemon.active();
+EnvironmentUtils.envSetUp();
+dataDir = new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile())
+.getParentFile().getAbsolutePath();
+initMetadata();
+  }
+
+  private void initMetadata() throws MetadataErrorException {
+MManager mmanager = MManager.getInstance();
+mmanager.init();
+mmanager.clear();
+mmanager.setStorageLevelToMTree("root.sg0");
+mmanager.setStorageLevelToMTree("root.sg1");
+mmanager.setStorageLevelToMTree("root.sg2");
+  }
+
+  @After
+  public void tearDown() throws InterruptedException, IOException, 
StorageEngineException {
+daemon.stop();
+EnvironmentUtils.cleanEnv();
+  }
+
+  @Test
+  public void loadNewTsfiles() throws IOException, StorageEngineException {
+fileLoader = FileLoader.createFileLoader(getReceiverFolderFile());
+Map> allFileList = new HashMap<>();
+Map> correctSequenceLoadedFileMap = new HashMap<>();
+
+// add some new tsfiles
+Random r = new Random(0);
+long time = System.currentTimeMillis();
+for (int i = 0; i < 3; i++) {
+  for (int j = 0; j < 10; j++) {
+allFileList.putIfAbsent(SG_NAME + i, new ArrayList<>());
+correctSequenceLoadedFileMap.putIfAbsent(SG_NAME + i, new HashSet<>());
+String rand = String.valueOf(r.nextInt(1));
+String fileName =
+getSnapshotFolder() + File.separator + SG_NAME + i + 
File.separator + (time + i * 100
++ j) + IoTDBConstant.FILE_NAME_SEPARATOR + rand
++ IoTDBConstant.FILE_NAME_SEPARATOR + "0.tsfile";
+File syncFile = new File(fileName);
+File dataFile = new File(
+
syncFile.getParentFile().getParentFile().getParentFile().getParentFile()
+.getParentFile(), IoTDBConstant.SEQUENCE_FLODER_NAME
++ File.separatorChar + syncFile.getParentFile().getName() + 
File.separatorChar
++ syncFile.getName());
+correctSequenceLoadedFileMap.get(SG_NAME + 
i).add(dataFile.getAbsolutePath());
+allFileList.get(SG_NAME + i).add(syncFile);
+if (!syncFile.getParentFile().exists()) {
+   

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321134058
 
 

 ##
 File path: docs/Documentation-CHN/UserGuide/9-System Tools/1-Sync.md
 ##
 @@ -207,33 +184,19 @@
 
 

-  参数名: iotdb_schema_directory
+  参数名: sync_storage_groups


   描述
-  同步发送端的IoTDB schema文件的绝对路径,例如$IOTDB_HOME 
/data/system/schema/mlog.txt(若用户未手动设置schema元数据的路径,则该路径为默认路径),该参数默认不生效,用户有需求时进行手动设置
+  进行同步的存储组列表,存储组间用逗号分隔;若列表设置为空表示同步所有存储组,默认为空
 
 Review comment:
   Will the default ones include system SGs like the statistic ones?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321148650
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321550822
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
+}
+  }
+
+  // update latest time map
+  updateLatestTimeMap(newTsFileResource);
+} catch (TsFileProcessorException | DiskSpaceInsufficientException e) {
+  logger.error("Failed to append the tsfile {} to storage group processor 
{}.",
+  newTsFile.getAbsolutePath(), newTsFile.getParentFile().getName());
+  throw new TsFileProcessorException(e);
+} finally {
+  mergeLock.writeLock().unlock();
+  writeUnlock();
+}
+  }
+
+  /**
+   * Update latest time in latestTimeForEachDevice and 
latestFlushedTimeForEachDevice.
+   *
+   * @UsedBy sync module
+   */
+  private void updateLatestTimeMap(TsFileResource newTsFileResource) {
+for (Entry entry : 
newTsFileResource.getEndTimeMap().entrySet()) {
+  String device = entry.getKey();
+  long endTime = newTsFileResource.getEndTimeMap().get(device);
+  if (!latestTimeForEachDevice.containsKey(device)
+  || latestTimeForEachDevice.get(device) < endTime) {
+latestTimeForEachDevice.put(device, endTime);
+  }
+  if (!latestFlushedTimeForEachDevice.containsKey(device)
+  || latestFlushedTimeForEachDevice.get(device) < endTime) {
+latestFlushedTimeForEachDevice.put(device, endTime);
+  }
+}
+  }
+
+  /**
+   * Execute the loading process by the type.
+   *
+   * @param type load type: 1 sequence tsfile ; 2 unsequence tsfile
+   * @param tsFile tsfile to be loaded
+   * @param tsFileResource tsfile resource to be loaded
+   * @param index the index in sequenceFileList/unSequenceFileList
+   * @UsedBy sync module
+   */
+  private void loadTsFileByType(int type, File tsFile, TsFileResource 
tsFileResource, int index)
+  throws TsFileProcessorException, DiskSpaceInsufficientException {
+File targetFile;
+if (type == -1) {
+  targetFile =
+  new 
File(DirectoryManager.getInstance().getNextFolderForUnSequenceFile(),
+  tsFile.getParentFile().getName() + File.separatorChar + 
tsFile.getName());
+  tsFileResource.setFile(targetFile);
+  unSequenceFileList.add(index, tsFileResource);
+  logger
+  .info("Load tsfile in unsequence list, move file from {} to {}", 
tsFile.getAbsolutePath(),
+  targetFile.getAbsolutePath());
+} else {
+  targetFile =
+  new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile(),
+  tsFile.getParentFile().getName() + File.separatorChar + 
getFileNameForLoadingFile(
+  tsFile.getName(), index));
+  tsFileResource.setFile(targetFile);
+  sequenceFileList.add(index, tsFileResource);
+  logger.info("Load tsfile in sequence list, move file from {} to {}", 
tsFile.getAbsolutePath(),
+  targetFile.getAbsolutePath());
+}
+
+// move file from sync dir to data dir
+if (!targetFile.getParentFile().exists()) {
+  targetFile.getParentFile().mkdirs();
+}
+if (tsFile.exists() && !targetFile.exists()) {
+  try {
+FileUtils.moveFile(tsFile, targetFile);
+  } catch (IOException e) {
+throw new TsFileProcessorException(String.format(
+"File renaming failed when loading tsfile. Origin: %s, Target: %s",
+tsFile.getAbsolutePath(), targetFile.getAbsolutePath()));
+  }
+}
+if (new File(tsFile.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists() && !new File(
+targetFile.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists()) {
+  try {
+

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r322520511
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/transfer/SyncServiceImpl.java
 ##
 @@ -0,0 +1,343 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.transfer;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.iotdb.db.concurrent.ThreadName;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.PathErrorException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.metadata.MetadataConstant;
+import org.apache.iotdb.db.metadata.MetadataOperationType;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogAnalyzer;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogger;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.FilePathUtils;
+import org.apache.iotdb.db.utils.SyncUtils;
+import org.apache.iotdb.service.sync.thrift.ResultStatus;
+import org.apache.iotdb.service.sync.thrift.SyncService;
+import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncServiceImpl implements SyncService.Iface {
+
+  private static final Logger logger = 
LoggerFactory.getLogger(SyncServiceImpl.class);
+
+  private IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
+
+  private ThreadLocal syncFolderPath = new ThreadLocal<>();
+
+  private ThreadLocal currentSG = new ThreadLocal<>();
+
+  private ThreadLocal syncLog = new ThreadLocal<>();
+
+  private ThreadLocal senderName = new ThreadLocal<>();
+
+  private ThreadLocal currentFile = new ThreadLocal<>();
+
+  private ThreadLocal currentFileWriter = new ThreadLocal<>();
+
+  private ThreadLocal messageDigest = new ThreadLocal<>();
+
+  /**
+   * Verify IP address of sender
+   */
+  @Override
+  public ResultStatus check(String ipAddress, String uuid) {
+Thread.currentThread().setName(ThreadName.SYNC_SERVER.getName());
+if (SyncUtils.verifyIPSegment(config.getIpWhiteList(), ipAddress)) {
+  senderName.set(ipAddress + SyncConstant.SYNC_DIR_NAME_SEPARATOR + uuid);
+  if (checkRecovery()) {
+logger.info("Start to sync with sender {}", senderName.get());
+return getSuccessResult();
+  } else {
+return getErrorResult("Receiver is processing data from previous sync 
tasks");
+  }
+} else {
+  return getErrorResult(
+  "Sender IP is not in the white list of receiver IP and 
synchronization tasks are not allowed.");
+}
+  }
+
+  private boolean checkRecovery() {
+try {
+  if (currentFileWriter.get() != null && currentFileWriter.get().isOpen()) 
{
+currentFileWriter.get().close();
+  }
+  if (syncLog.get() != null) {
+syncLog.get().close();
+  }
+  return SyncReceiverLogAnalyzer.getInstance().recover(senderName.get());
+} catch (IOException e) {
+  logger.error("Check recovery state fail", e);
+  return false;
+}
+  }
+
+  @Override
+  public R

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323533459
 
 

 ##
 File path: 
server/src/test/java/org/apache/iotdb/db/sync/receiver/recover/SyncReceiverLogAnalyzerTest.java
 ##
 @@ -0,0 +1,205 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.recover;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.StorageGroupProcessor;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.StartupException;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.service.IoTDB;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderTest;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.EnvironmentUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncReceiverLogAnalyzerTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoaderTest.class);
+  private static final String SG_NAME = "root.sg";
+  private static IoTDB daemon;
+  private String dataDir;
+  private FileLoader fileLoader;
+  private SyncReceiverLogAnalyzer logAnalyze;
+  private SyncReceiverLogger receiverLogger;
+
+  @Before
+  public void setUp()
+  throws IOException, InterruptedException, StartupException, 
DiskSpaceInsufficientException, MetadataErrorException {
+EnvironmentUtils.closeStatMonitor();
+daemon = IoTDB.getInstance();
+daemon.active();
+EnvironmentUtils.envSetUp();
+dataDir = new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile())
+.getParentFile().getAbsolutePath();
+logAnalyze = SyncReceiverLogAnalyzer.getInstance();
+initMetadata();
+  }
+
+  private void initMetadata() throws MetadataErrorException {
+MManager mmanager = MManager.getInstance();
+mmanager.init();
+mmanager.clear();
+mmanager.setStorageLevelToMTree("root.sg0");
+mmanager.setStorageLevelToMTree("root.sg1");
+mmanager.setStorageLevelToMTree("root.sg2");
+  }
+
+  @After
+  public void tearDown() throws InterruptedException, IOException, 
StorageEngineException {
+daemon.stop();
+EnvironmentUtils.cleanEnv();
+  }
+
+  @Test
+  public void recover() throws IOException, StorageEngineException {
+receiverLogger = new SyncReceiverLogger(
+new File(getReceiverFolderFile(), SyncConstant.SYNC_LOG_NAME));
+fileLoader = FileLoader.createFileLoader(getReceiverFolderFile());
+Map> allFileList = new HashMap<>();
+Map> correctSequenceLoadedFileMap = new HashMap<>();
+
+// add some new tsfiles
 
 Review comment:
   Can you extract the following codes as a method? They seem alike.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321137183
 
 

 ##
 File path: docs/Documentation/UserGuide/9-System Tools/1-Sync.md
 ##
 @@ -231,26 +206,31 @@ The parameters of the sync sender are configured in a 
separate configuration fil
 
 

-  parameter: iotdb_bufferWrite_directory
+  parameter: sync_storage_groups


-  Description
-  The absolute path of the buffer write data (tsfile file) directory 
of the IoTDB at the sender, such as: $IOTDB_HOME/data/data/settled (if the user 
does not set the data path manually, the path is the default path of IoTDB 
engine). This parameter is not valid by default, and is set manually when the 
user needs it. This parameter needs to be guaranteed to belong to the same 
IoTDB as the parameter iotdb_schema_directory.
+  Description
+  This parameter represents storage groups that participate in the 
synchronization task, which distinguishes each storage group by comma.If the 
list is empty, it means that all storage groups participate in 
synchronization.By default, it is empty list.
 
 Review comment:
   I am not sure whether "distinguishes" fits here...
   "comma.If" ->"comma. If” and “synchronization.By”
   “it is empty list” -> "it is an empty list" or "it is empty"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323107545
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/manage/SyncFileManager.java
 ##
 @@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.manage;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.engine.merge.task.MergeTask;
+import org.apache.iotdb.db.engine.modification.ModificationFile;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.sync.sender.conf.SyncSenderDescriptor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncFileManager implements ISyncFileManager {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncFileManager.class);
+
+  /**
+   * All storage groups on the disk where the current sync task is executed
+   */
+  private Set allSG;
 
 Review comment:
   Maybe "allSGs"?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321550562
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
+}
+  }
+
+  // update latest time map
+  updateLatestTimeMap(newTsFileResource);
+} catch (TsFileProcessorException | DiskSpaceInsufficientException e) {
+  logger.error("Failed to append the tsfile {} to storage group processor 
{}.",
+  newTsFile.getAbsolutePath(), newTsFile.getParentFile().getName());
+  throw new TsFileProcessorException(e);
+} finally {
+  mergeLock.writeLock().unlock();
+  writeUnlock();
+}
+  }
+
+  /**
+   * Update latest time in latestTimeForEachDevice and 
latestFlushedTimeForEachDevice.
+   *
+   * @UsedBy sync module
+   */
+  private void updateLatestTimeMap(TsFileResource newTsFileResource) {
+for (Entry entry : 
newTsFileResource.getEndTimeMap().entrySet()) {
+  String device = entry.getKey();
+  long endTime = newTsFileResource.getEndTimeMap().get(device);
+  if (!latestTimeForEachDevice.containsKey(device)
+  || latestTimeForEachDevice.get(device) < endTime) {
+latestTimeForEachDevice.put(device, endTime);
+  }
+  if (!latestFlushedTimeForEachDevice.containsKey(device)
+  || latestFlushedTimeForEachDevice.get(device) < endTime) {
+latestFlushedTimeForEachDevice.put(device, endTime);
+  }
+}
+  }
+
+  /**
+   * Execute the loading process by the type.
+   *
+   * @param type load type: 1 sequence tsfile ; 2 unsequence tsfile
+   * @param tsFile tsfile to be loaded
+   * @param tsFileResource tsfile resource to be loaded
+   * @param index the index in sequenceFileList/unSequenceFileList
+   * @UsedBy sync module
+   */
+  private void loadTsFileByType(int type, File tsFile, TsFileResource 
tsFileResource, int index)
+  throws TsFileProcessorException, DiskSpaceInsufficientException {
+File targetFile;
+if (type == -1) {
+  targetFile =
+  new 
File(DirectoryManager.getInstance().getNextFolderForUnSequenceFile(),
+  tsFile.getParentFile().getName() + File.separatorChar + 
tsFile.getName());
+  tsFileResource.setFile(targetFile);
+  unSequenceFileList.add(index, tsFileResource);
+  logger
+  .info("Load tsfile in unsequence list, move file from {} to {}", 
tsFile.getAbsolutePath(),
+  targetFile.getAbsolutePath());
+} else {
+  targetFile =
+  new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile(),
+  tsFile.getParentFile().getName() + File.separatorChar + 
getFileNameForLoadingFile(
+  tsFile.getName(), index));
+  tsFileResource.setFile(targetFile);
+  sequenceFileList.add(index, tsFileResource);
+  logger.info("Load tsfile in sequence list, move file from {} to {}", 
tsFile.getAbsolutePath(),
+  targetFile.getAbsolutePath());
+}
+
+// move file from sync dir to data dir
+if (!targetFile.getParentFile().exists()) {
+  targetFile.getParentFile().mkdirs();
+}
+if (tsFile.exists() && !targetFile.exists()) {
+  try {
+FileUtils.moveFile(tsFile, targetFile);
+  } catch (IOException e) {
+throw new TsFileProcessorException(String.format(
+"File renaming failed when loading tsfile. Origin: %s, Target: %s",
+tsFile.getAbsolutePath(), targetFile.getAbsolutePath()));
+  }
+}
+if (new File(tsFile.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists() && !new File(
+targetFile.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists()) {
 
 Review comment:
   

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323112673
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/manage/SyncFileManager.java
 ##
 @@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.manage;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.engine.merge.task.MergeTask;
+import org.apache.iotdb.db.engine.modification.ModificationFile;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.sync.sender.conf.SyncSenderDescriptor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncFileManager implements ISyncFileManager {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncFileManager.class);
+
+  /**
+   * All storage groups on the disk where the current sync task is executed
+   */
+  private Set allSG;
+
+  /**
+   * Key is storage group, value is the set of current sealed tsfile in the 
storage group.
+   */
+  private Map> currentSealedLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the set of last local tsfiles in the 
storage group, which don't
+   * contains those tsfiles which are not synced successfully.
+   */
+  private Map> lastLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the valid set of deleted tsfiles which 
need to be synced to
+   * receiver end in the storage group.
+   */
+  private Map> deletedFilesMap;
+
+  /**
+   * Key is storage group, value is the valid set of new tsfiles which need to 
be synced to receiver
+   * end in the storage group.
+   */
+  private Map> toBeSyncedFilesMap;
+
+  private SyncFileManager() {
+
+  }
+
+  public static final SyncFileManager getInstance() {
+return SyncFileManagerHolder.INSTANCE;
+  }
+
+  @Override
+  public void getCurrentLocalFiles(String dataDir) {
+LOGGER.info("Start to get current local files in data folder {}", dataDir);
+
+currentSealedLocalFilesMap = new HashMap<>();
+// get all files in data dir sequence folder
+Map> currentAllLocalFiles = new HashMap<>();
+if (!new File(dataDir + File.separatorChar + 
IoTDBConstant.SEQUENCE_FLODER_NAME).exists()) {
+  return;
+}
+File[] allSGFolders = new File(
+dataDir + File.separatorChar + IoTDBConstant.SEQUENCE_FLODER_NAME)
+.listFiles();
+for (File sgFolder : allSGFolders) {
+  allSG.add(sgFolder.getName());
+  currentAllLocalFiles.putIfAbsent(sgFolder.getName(), new HashSet<>());
+  if (sgFolder.listFiles() != null) {
+Arrays.stream(sgFolder.listFiles())
 
 Review comment:
   Maybe you do not have to listFiles() twice.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321548921
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
+}
+  }
+
+  // update latest time map
+  updateLatestTimeMap(newTsFileResource);
+} catch (TsFileProcessorException | DiskSpaceInsufficientException e) {
+  logger.error("Failed to append the tsfile {} to storage group processor 
{}.",
+  newTsFile.getAbsolutePath(), newTsFile.getParentFile().getName());
+  throw new TsFileProcessorException(e);
+} finally {
+  mergeLock.writeLock().unlock();
+  writeUnlock();
+}
+  }
+
+  /**
+   * Update latest time in latestTimeForEachDevice and 
latestFlushedTimeForEachDevice.
+   *
+   * @UsedBy sync module
+   */
+  private void updateLatestTimeMap(TsFileResource newTsFileResource) {
+for (Entry entry : 
newTsFileResource.getEndTimeMap().entrySet()) {
+  String device = entry.getKey();
+  long endTime = newTsFileResource.getEndTimeMap().get(device);
+  if (!latestTimeForEachDevice.containsKey(device)
+  || latestTimeForEachDevice.get(device) < endTime) {
+latestTimeForEachDevice.put(device, endTime);
+  }
+  if (!latestFlushedTimeForEachDevice.containsKey(device)
+  || latestFlushedTimeForEachDevice.get(device) < endTime) {
+latestFlushedTimeForEachDevice.put(device, endTime);
+  }
+}
+  }
+
+  /**
+   * Execute the loading process by the type.
+   *
+   * @param type load type: 1 sequence tsfile ; 2 unsequence tsfile
 
 Review comment:
   You seem to be using -1 and 1 instead of 1 and 2.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323096815
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/conf/SyncConstant.java
 ##
 @@ -16,33 +16,48 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.apache.iotdb.db.sync.conf;
+package org.apache.iotdb.db.sync.sender.conf;
 
-public class Constans {
+public class SyncConstant {
 
-  private Constans() {
+  private SyncConstant() {
   }
 
   public static final String CONFIG_NAME = "iotdb-sync-client.properties";
-  public static final String SYNC_CLIENT = "sync-client";
-  public static final String SYNC_SERVER = "sync-server";
 
-  public static final String LOCK_FILE_NAME = "sync-lock";
-  public static final String UUID_FILE_NAME = "uuid.txt";
-  public static final String LAST_LOCAL_FILE_NAME = "last_local_files.txt";
-  public static final String DATA_SNAPSHOT_NAME = "data-snapshot";
+  public static final String SYNC_SENDER = "sync-sender";
+
+  public static final String SYNC_RECEIVER = "sync-receiver";
 
-  public static final String BACK_UP_DIRECTORY_NAME = "backup";
+  public static final String MESSAGE_DIGIT_NAME = "MD5";
+
+  public static final String SYNC_DIR_NAME_SEPARATOR = "_";
 
   /**
-   * Split data file , block size at each transmission
+   * Split data file, block size at each transmission
**/
   public static final int DATA_CHUNK_SIZE = 64 * 1024 * 1024;
 
+  // sender section
+
+  public static final String LOCK_FILE_NAME = "sync_lock";
+
+  public static final String UUID_FILE_NAME = "uuid.txt";
+
+  public static final String SCHEMA_POS_FILE_NAME = "sync_schema_pos";
+
+  public static final String LAST_LOCAL_FILE_NAME = "last_local_files.txt";
+
+  public static final String CURRENT_LOCAL_FILE_NAME = 
"current_local_files.txt";
+
+  public static final String DATA_SNAPSHOT_NAME = "snapshot";
+
+  public static final String SYNC_LOG_NAME = "sync.log";
+
   /**
-   * Max try when syncing the same file to receiver fails.
+   * Maximum try when syncing the same file to receiver fails.
*/
-  public static final int MAX_SYNC_FILE_TRY = 10;
+  public static final int MAX_SYNC_FILE_TRY = 5;
 
 Review comment:
   Can you make this a config? More retries may be needed depending on the 
network environment.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321666911
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/transfer/SyncServiceImpl.java
 ##
 @@ -0,0 +1,343 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.transfer;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.iotdb.db.concurrent.ThreadName;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.PathErrorException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.metadata.MetadataConstant;
+import org.apache.iotdb.db.metadata.MetadataOperationType;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogAnalyzer;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogger;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.FilePathUtils;
+import org.apache.iotdb.db.utils.SyncUtils;
+import org.apache.iotdb.service.sync.thrift.ResultStatus;
+import org.apache.iotdb.service.sync.thrift.SyncService;
+import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncServiceImpl implements SyncService.Iface {
+
+  private static final Logger logger = 
LoggerFactory.getLogger(SyncServiceImpl.class);
+
+  private IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
+
+  private ThreadLocal syncFolderPath = new ThreadLocal<>();
+
+  private ThreadLocal currentSG = new ThreadLocal<>();
+
+  private ThreadLocal syncLog = new ThreadLocal<>();
+
+  private ThreadLocal senderName = new ThreadLocal<>();
+
+  private ThreadLocal currentFile = new ThreadLocal<>();
+
+  private ThreadLocal currentFileWriter = new ThreadLocal<>();
+
+  private ThreadLocal messageDigest = new ThreadLocal<>();
+
+  /**
+   * Verify IP address of sender
+   */
+  @Override
+  public ResultStatus check(String ipAddress, String uuid) {
+Thread.currentThread().setName(ThreadName.SYNC_SERVER.getName());
+if (SyncUtils.verifyIPSegment(config.getIpWhiteList(), ipAddress)) {
+  senderName.set(ipAddress + SyncConstant.SYNC_DIR_NAME_SEPARATOR + uuid);
+  if (checkRecovery()) {
+logger.info("Start to sync with sender {}", senderName.get());
+return getSuccessResult();
+  } else {
+return getErrorResult("Receiver is processing data from previous sync 
tasks");
+  }
+} else {
+  return getErrorResult(
+  "Sender IP is not in the white list of receiver IP and 
synchronization tasks are not allowed.");
+}
+  }
+
+  private boolean checkRecovery() {
+try {
+  if (currentFileWriter.get() != null && currentFileWriter.get().isOpen()) 
{
+currentFileWriter.get().close();
+  }
+  if (syncLog.get() != null) {
+syncLog.get().close();
+  }
+  return SyncReceiverLogAnalyzer.getInstance().recover(senderName.get());
+} catch (IOException e) {
+  logger.error("Check recovery state fail", e);
+  return false;
+}
+  }
+
+  @Override
+  public R

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321594259
 
 

 ##
 File path: server/src/main/java/org/apache/iotdb/db/sync/package-info.java
 ##
 @@ -0,0 +1,39 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * 
+ * Package Sync is a suite tool that periodically uploads persistent tsfiles 
from the sender disk to
+ * the receiver and loads them. With merge module, synchronous update of 
write, update and delete
+ * operations can be synced.
+ *
+ * On the sender side of the sync, the sync module is a separate process, 
independent of the IoTDB
+ * process. It can be started and closed through a separate script.
+ *
+ * On the receiver side of the sync, the sync module is embedded in the engine 
of IoTDB and is in
+ * the same process with IoTDB. The receiver module listens for a separate 
port. Before using it, it
 
 Review comment:
   "listens for" -> "listens to"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323120237
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/recover/ISyncSenderLogger.java
 ##
 @@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.recover;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * This interface is used to log progress in the process of synchronization 
tasks. If the
+ * synchronization tasks are completed normally and there are no exceptions, 
the log records will be
+ * deleted; otherwise, the status can be restored according to the log at the 
start of each task. It
+ * ensures the correctness of synchronization module when system crash or 
network abnormality
+ * occur.
 
 Review comment:
   "when system crash or network abnormality occur" ->"when system crashed or 
network abnormality occurred"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323108658
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/manage/SyncFileManager.java
 ##
 @@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.manage;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.engine.merge.task.MergeTask;
+import org.apache.iotdb.db.engine.modification.ModificationFile;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.sync.sender.conf.SyncSenderDescriptor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncFileManager implements ISyncFileManager {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncFileManager.class);
+
+  /**
+   * All storage groups on the disk where the current sync task is executed
+   */
+  private Set allSG;
+
+  /**
+   * Key is storage group, value is the set of current sealed tsfile in the 
storage group.
 
 Review comment:
   “current sealed tsfile” -> "current sealed tsfiles"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r32311
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/manage/SyncFileManager.java
 ##
 @@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.manage;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.engine.merge.task.MergeTask;
+import org.apache.iotdb.db.engine.modification.ModificationFile;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.sync.sender.conf.SyncSenderDescriptor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncFileManager implements ISyncFileManager {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncFileManager.class);
+
+  /**
+   * All storage groups on the disk where the current sync task is executed
+   */
+  private Set allSG;
+
+  /**
+   * Key is storage group, value is the set of current sealed tsfile in the 
storage group.
+   */
+  private Map> currentSealedLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the set of last local tsfiles in the 
storage group, which don't
+   * contains those tsfiles which are not synced successfully.
+   */
+  private Map> lastLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the valid set of deleted tsfiles which 
need to be synced to
+   * receiver end in the storage group.
+   */
+  private Map> deletedFilesMap;
+
+  /**
+   * Key is storage group, value is the valid set of new tsfiles which need to 
be synced to receiver
+   * end in the storage group.
+   */
+  private Map> toBeSyncedFilesMap;
+
+  private SyncFileManager() {
+
+  }
+
+  public static final SyncFileManager getInstance() {
+return SyncFileManagerHolder.INSTANCE;
+  }
+
+  @Override
+  public void getCurrentLocalFiles(String dataDir) {
+LOGGER.info("Start to get current local files in data folder {}", dataDir);
+
+currentSealedLocalFilesMap = new HashMap<>();
+// get all files in data dir sequence folder
+Map> currentAllLocalFiles = new HashMap<>();
+if (!new File(dataDir + File.separatorChar + 
IoTDBConstant.SEQUENCE_FLODER_NAME).exists()) {
+  return;
+}
+File[] allSGFolders = new File(
+dataDir + File.separatorChar + IoTDBConstant.SEQUENCE_FLODER_NAME)
+.listFiles();
+for (File sgFolder : allSGFolders) {
+  allSG.add(sgFolder.getName());
+  currentAllLocalFiles.putIfAbsent(sgFolder.getName(), new HashSet<>());
+  if (sgFolder.listFiles() != null) {
+Arrays.stream(sgFolder.listFiles())
+.forEach(file -> currentAllLocalFiles.get(sgFolder.getName())
+.add(new File(sgFolder.getAbsolutePath(), file.getName(;
+  }
+}
+
+// get sealed tsfiles
+for (Entry> entry : currentAllLocalFiles.entrySet()) {
+  String sgName = entry.getKey();
+  currentSealedLocalFilesMap.putIfAbsent(sgName, new HashSet<>());
+  for (File file : entry.getValue()) {
+if (file.getName().endsWith(ModificationFile.FILE_SUFFIX) || 
file.getName()
+.endsWith(TsFileResource.RESOURCE_SUFFIX) || file.getName()
+.endsWith(MergeTask.MERGE_SUFFIX)) {
+  continue;
+}
 
 Review comment:
   How about `if (!file.getName().endsWith(TSFILE_SUFFIX))`.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321666334
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/transfer/SyncServiceImpl.java
 ##
 @@ -0,0 +1,343 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.transfer;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.iotdb.db.concurrent.ThreadName;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.PathErrorException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.metadata.MetadataConstant;
+import org.apache.iotdb.db.metadata.MetadataOperationType;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogAnalyzer;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogger;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.FilePathUtils;
+import org.apache.iotdb.db.utils.SyncUtils;
+import org.apache.iotdb.service.sync.thrift.ResultStatus;
+import org.apache.iotdb.service.sync.thrift.SyncService;
+import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncServiceImpl implements SyncService.Iface {
+
+  private static final Logger logger = 
LoggerFactory.getLogger(SyncServiceImpl.class);
+
+  private IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
+
+  private ThreadLocal syncFolderPath = new ThreadLocal<>();
+
+  private ThreadLocal currentSG = new ThreadLocal<>();
+
+  private ThreadLocal syncLog = new ThreadLocal<>();
+
+  private ThreadLocal senderName = new ThreadLocal<>();
+
+  private ThreadLocal currentFile = new ThreadLocal<>();
+
+  private ThreadLocal currentFileWriter = new ThreadLocal<>();
+
+  private ThreadLocal messageDigest = new ThreadLocal<>();
+
+  /**
+   * Verify IP address of sender
+   */
+  @Override
+  public ResultStatus check(String ipAddress, String uuid) {
+Thread.currentThread().setName(ThreadName.SYNC_SERVER.getName());
+if (SyncUtils.verifyIPSegment(config.getIpWhiteList(), ipAddress)) {
+  senderName.set(ipAddress + SyncConstant.SYNC_DIR_NAME_SEPARATOR + uuid);
+  if (checkRecovery()) {
+logger.info("Start to sync with sender {}", senderName.get());
+return getSuccessResult();
+  } else {
+return getErrorResult("Receiver is processing data from previous sync 
tasks");
+  }
+} else {
+  return getErrorResult(
+  "Sender IP is not in the white list of receiver IP and 
synchronization tasks are not allowed.");
+}
+  }
+
+  private boolean checkRecovery() {
+try {
+  if (currentFileWriter.get() != null && currentFileWriter.get().isOpen()) 
{
+currentFileWriter.get().close();
+  }
+  if (syncLog.get() != null) {
+syncLog.get().close();
+  }
+  return SyncReceiverLogAnalyzer.getInstance().recover(senderName.get());
+} catch (IOException e) {
+  logger.error("Check recovery state fail", e);
+  return false;
+}
+  }
+
+  @Override
+  public R

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321593830
 
 

 ##
 File path: server/src/main/java/org/apache/iotdb/db/sync/package-info.java
 ##
 @@ -0,0 +1,39 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/**
+ * 
+ * Package Sync is a suite tool that periodically uploads persistent tsfiles 
from the sender disk to
+ * the receiver and loads them. With merge module, synchronous update of 
write, update and delete
+ * operations can be synced.
+ *
+ * On the sender side of the sync, the sync module is a separate process, 
independent of the IoTDB
+ * process. It can be started and closed through a separate script.
 
 Review comment:
   "through a separate script" -> "through separate scripts"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321610170
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/FileLoader.java
 ##
 @@ -0,0 +1,227 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more 
contributor license
+ * agreements.  See the NOTICE file distributed with this work for additional 
information regarding
+ * copyright ownership.  The ASF licenses this file to you under the Apache 
License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with the 
License.  You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software 
distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
KIND, either express
+ * or implied.  See the License for the specific language governing 
permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.exception.TsFileProcessorException;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.tsfile.file.metadata.ChunkGroupMetaData;
+import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
+import org.apache.iotdb.tsfile.file.metadata.TsDeviceMetadata;
+import org.apache.iotdb.tsfile.file.metadata.TsDeviceMetadataIndex;
+import org.apache.iotdb.tsfile.file.metadata.TsFileMetaData;
+import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoader implements IFileLoader {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoader.class);
+
+  private static final int WAIT_TIME = 100;
+
+  private String syncFolderPath;
+
+  private String senderName;
+
+  private BlockingQueue queue = new LinkedBlockingQueue<>();
+
+  private LoadLogger loadLog;
+
+  private LoadType curType = LoadType.NONE;
+
+  private volatile boolean endSync = false;
+
+  private FileLoader(String senderName, String syncFolderPath) throws 
IOException {
+this.senderName = senderName;
+this.syncFolderPath = syncFolderPath;
+this.loadLog = new LoadLogger(new File(syncFolderPath, 
SyncConstant.LOAD_LOG_NAME));
+FileLoaderManager.getInstance().addFileLoader(senderName, this);
+FileLoaderManager.getInstance().addLoadTaskRunner(loadTaskRunner);
+  }
+
+  public static FileLoader createFileLoader(String senderName, String 
syncFolderPath)
+  throws IOException {
+return new FileLoader(senderName, syncFolderPath);
+  }
+
+  public static FileLoader createFileLoader(File syncFolder)
+  throws IOException {
+return new FileLoader(syncFolder.getName(), syncFolder.getAbsolutePath());
+  }
+
+  private Runnable loadTaskRunner = () -> {
+try {
+  while (true) {
+if (queue.isEmpty() && endSync) {
+  cleanUp();
+  break;
+}
+LoadTask loadTask = queue.poll(WAIT_TIME, TimeUnit.MILLISECONDS);
+if (loadTask != null) {
+  try {
+handleLoadTask(loadTask);
+  } catch (Exception e) {
+LOGGER.error("Can not load task {}", loadTask, e);
+  }
+}
+  }
+} catch (InterruptedException e) {
+  LOGGER.error("Can not handle load task", e);
+}
+  };
+
+  @Override
+  public void addDeletedFileName(File deletedFile) {
+queue.add(new LoadTask(deletedFile, LoadType.DELETE));
+  }
+
+  @Override
+  public void addTsfile(File tsfile) {
+queue.add(new LoadTask(tsfile, LoadType.ADD));
+  }
+
+  @Override
+  public void endSync() {
+if (!endSync && 
FileLoaderManager.getInstance().containsFileLoader(senderName)) {
+  this.endSync = true;
+}
+  }
+
+  @Override
+  public void handleLoadTask(LoadTask task) throws IOException {
+switch (task.type) {
+  case ADD:
+loadNewTsfile(task.file);
+break;
+  case DELETE:
+loadDeletedFile(task.file);
+break;
+  default:
+LOGGER.error("Wrong load task type {}", task.type);
+}
+  }
+
+  private void loadNewTsfile(File newTsFile) throws IOException {
+if (curType != LoadType.ADD) {
+  loadLog.startLoadTsFiles();
+  curType = LoadType.ADD;
+}
+if (!newTsFile.exists()) {
+  LOGGER.info("Tsfile {} doesn't exist.", newTsFile.getAbs

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321595551
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/FileLoader.java
 ##
 @@ -0,0 +1,227 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more 
contributor license
+ * agreements.  See the NOTICE file distributed with this work for additional 
information regarding
+ * copyright ownership.  The ASF licenses this file to you under the Apache 
License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with the 
License.  You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software 
distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
KIND, either express
+ * or implied.  See the License for the specific language governing 
permissions and limitations
+ * under the License.
+ */
 
 Review comment:
   The format of the license seems a bit strange.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321592142
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
+}
+  }
+
+  // update latest time map
+  updateLatestTimeMap(newTsFileResource);
+} catch (TsFileProcessorException | DiskSpaceInsufficientException e) {
+  logger.error("Failed to append the tsfile {} to storage group processor 
{}.",
+  newTsFile.getAbsolutePath(), newTsFile.getParentFile().getName());
+  throw new TsFileProcessorException(e);
+} finally {
+  mergeLock.writeLock().unlock();
+  writeUnlock();
+}
+  }
+
+  /**
+   * Update latest time in latestTimeForEachDevice and 
latestFlushedTimeForEachDevice.
+   *
+   * @UsedBy sync module
+   */
+  private void updateLatestTimeMap(TsFileResource newTsFileResource) {
+for (Entry entry : 
newTsFileResource.getEndTimeMap().entrySet()) {
+  String device = entry.getKey();
+  long endTime = newTsFileResource.getEndTimeMap().get(device);
+  if (!latestTimeForEachDevice.containsKey(device)
+  || latestTimeForEachDevice.get(device) < endTime) {
+latestTimeForEachDevice.put(device, endTime);
+  }
+  if (!latestFlushedTimeForEachDevice.containsKey(device)
+  || latestFlushedTimeForEachDevice.get(device) < endTime) {
+latestFlushedTimeForEachDevice.put(device, endTime);
+  }
+}
+  }
+
+  /**
+   * Execute the loading process by the type.
+   *
+   * @param type load type: 1 sequence tsfile ; 2 unsequence tsfile
+   * @param tsFile tsfile to be loaded
+   * @param tsFileResource tsfile resource to be loaded
+   * @param index the index in sequenceFileList/unSequenceFileList
+   * @UsedBy sync module
+   */
+  private void loadTsFileByType(int type, File tsFile, TsFileResource 
tsFileResource, int index)
+  throws TsFileProcessorException, DiskSpaceInsufficientException {
+File targetFile;
+if (type == -1) {
+  targetFile =
+  new 
File(DirectoryManager.getInstance().getNextFolderForUnSequenceFile(),
+  tsFile.getParentFile().getName() + File.separatorChar + 
tsFile.getName());
+  tsFileResource.setFile(targetFile);
+  unSequenceFileList.add(index, tsFileResource);
+  logger
+  .info("Load tsfile in unsequence list, move file from {} to {}", 
tsFile.getAbsolutePath(),
+  targetFile.getAbsolutePath());
+} else {
+  targetFile =
+  new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile(),
+  tsFile.getParentFile().getName() + File.separatorChar + 
getFileNameForLoadingFile(
+  tsFile.getName(), index));
+  tsFileResource.setFile(targetFile);
+  sequenceFileList.add(index, tsFileResource);
+  logger.info("Load tsfile in sequence list, move file from {} to {}", 
tsFile.getAbsolutePath(),
+  targetFile.getAbsolutePath());
+}
+
+// move file from sync dir to data dir
+if (!targetFile.getParentFile().exists()) {
+  targetFile.getParentFile().mkdirs();
+}
+if (tsFile.exists() && !targetFile.exists()) {
+  try {
+FileUtils.moveFile(tsFile, targetFile);
+  } catch (IOException e) {
+throw new TsFileProcessorException(String.format(
+"File renaming failed when loading tsfile. Origin: %s, Target: %s",
+tsFile.getAbsolutePath(), targetFile.getAbsolutePath()));
+  }
+}
+if (new File(tsFile.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists() && !new File(
+targetFile.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists()) {
+  try {
+

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321549285
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
+}
+  }
+
+  // update latest time map
+  updateLatestTimeMap(newTsFileResource);
+} catch (TsFileProcessorException | DiskSpaceInsufficientException e) {
+  logger.error("Failed to append the tsfile {} to storage group processor 
{}.",
+  newTsFile.getAbsolutePath(), newTsFile.getParentFile().getName());
+  throw new TsFileProcessorException(e);
+} finally {
+  mergeLock.writeLock().unlock();
+  writeUnlock();
+}
+  }
+
+  /**
+   * Update latest time in latestTimeForEachDevice and 
latestFlushedTimeForEachDevice.
+   *
+   * @UsedBy sync module
+   */
+  private void updateLatestTimeMap(TsFileResource newTsFileResource) {
+for (Entry entry : 
newTsFileResource.getEndTimeMap().entrySet()) {
+  String device = entry.getKey();
+  long endTime = newTsFileResource.getEndTimeMap().get(device);
+  if (!latestTimeForEachDevice.containsKey(device)
+  || latestTimeForEachDevice.get(device) < endTime) {
+latestTimeForEachDevice.put(device, endTime);
+  }
+  if (!latestFlushedTimeForEachDevice.containsKey(device)
+  || latestFlushedTimeForEachDevice.get(device) < endTime) {
+latestFlushedTimeForEachDevice.put(device, endTime);
+  }
+}
+  }
+
+  /**
+   * Execute the loading process by the type.
+   *
+   * @param type load type: 1 sequence tsfile ; 2 unsequence tsfile
+   * @param tsFile tsfile to be loaded
+   * @param tsFileResource tsfile resource to be loaded
+   * @param index the index in sequenceFileList/unSequenceFileList
+   * @UsedBy sync module
+   */
+  private void loadTsFileByType(int type, File tsFile, TsFileResource 
tsFileResource, int index)
 
 Review comment:
   I wonder if it is necessary to pass the parameter `tsFile`, since 
`TsFileResource` contains a file itself.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323116633
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/manage/SyncFileManager.java
 ##
 @@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.manage;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.engine.merge.task.MergeTask;
+import org.apache.iotdb.db.engine.modification.ModificationFile;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.sync.sender.conf.SyncSenderDescriptor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncFileManager implements ISyncFileManager {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncFileManager.class);
+
+  /**
+   * All storage groups on the disk where the current sync task is executed
+   */
+  private Set allSG;
+
+  /**
+   * Key is storage group, value is the set of current sealed tsfile in the 
storage group.
+   */
+  private Map> currentSealedLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the set of last local tsfiles in the 
storage group, which don't
+   * contains those tsfiles which are not synced successfully.
+   */
+  private Map> lastLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the valid set of deleted tsfiles which 
need to be synced to
+   * receiver end in the storage group.
+   */
+  private Map> deletedFilesMap;
+
+  /**
+   * Key is storage group, value is the valid set of new tsfiles which need to 
be synced to receiver
+   * end in the storage group.
+   */
+  private Map> toBeSyncedFilesMap;
+
+  private SyncFileManager() {
+
+  }
+
+  public static final SyncFileManager getInstance() {
+return SyncFileManagerHolder.INSTANCE;
+  }
+
+  @Override
+  public void getCurrentLocalFiles(String dataDir) {
+LOGGER.info("Start to get current local files in data folder {}", dataDir);
+
+currentSealedLocalFilesMap = new HashMap<>();
+// get all files in data dir sequence folder
+Map> currentAllLocalFiles = new HashMap<>();
+if (!new File(dataDir + File.separatorChar + 
IoTDBConstant.SEQUENCE_FLODER_NAME).exists()) {
+  return;
+}
+File[] allSGFolders = new File(
+dataDir + File.separatorChar + IoTDBConstant.SEQUENCE_FLODER_NAME)
+.listFiles();
+for (File sgFolder : allSGFolders) {
+  allSG.add(sgFolder.getName());
+  currentAllLocalFiles.putIfAbsent(sgFolder.getName(), new HashSet<>());
+  if (sgFolder.listFiles() != null) {
+Arrays.stream(sgFolder.listFiles())
+.forEach(file -> currentAllLocalFiles.get(sgFolder.getName())
+.add(new File(sgFolder.getAbsolutePath(), file.getName(;
+  }
+}
+
+// get sealed tsfiles
+for (Entry> entry : currentAllLocalFiles.entrySet()) {
+  String sgName = entry.getKey();
+  currentSealedLocalFilesMap.putIfAbsent(sgName, new HashSet<>());
+  for (File file : entry.getValue()) {
+if (file.getName().endsWith(ModificationFile.FILE_SUFFIX) || 
file.getName()
+.endsWith(TsFileResource.RESOURCE_SUFFIX) || file.getName()
+.endsWith(MergeTask.MERGE_SUFFIX)) {
+  continue;
+}
+if (new File(file.getAbsolutePath() + 
TsFileResource.RESOURCE_SUFFIX).exists() && !new File(
+file.getAbsolutePath() + ModificationFile.FILE_SUFFIX).exists() && 
!new File(
+file.getAbsolutePath() + MergeTask.MERGE_SUFFIX).exists()) {
+  currentSealedLocalFilesMap.get(sgName).add(file);
+}
+  }
+}
+  }
+
+  @Override
+  public void getLastLocalFiles(File lastLocalFileInfo) throws IOException {
+LOGGER.info("Start to get last local files from last local file info {}",
+lastLocalFileIn

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321617664
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/LoadType.java
 ##
 @@ -0,0 +1,23 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+public enum LoadType {
+DELETE, ADD, NONE
 
 Review comment:
   What does NONE mean?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321134058
 
 

 ##
 File path: docs/Documentation-CHN/UserGuide/9-System Tools/1-Sync.md
 ##
 @@ -207,33 +184,19 @@
 
 

-  参数名: iotdb_schema_directory
+  参数名: sync_storage_groups


   描述
-  同步发送端的IoTDB schema文件的绝对路径,例如$IOTDB_HOME 
/data/system/schema/mlog.txt(若用户未手动设置schema元数据的路径,则该路径为默认路径),该参数默认不生效,用户有需求时进行手动设置
+  进行同步的存储组列表,存储组间用逗号分隔;若列表设置为空表示同步所有存储组,默认为空
 
 Review comment:
   Will this include system SGs like the statistic ones?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321157573
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
+}
+  }
+
+  // update latest time map
+  updateLatestTimeMap(newTsFileResource);
+} catch (TsFileProcessorException | DiskSpaceInsufficientException e) {
+  logger.error("Failed to append the tsfile {} to storage group processor 
{}.",
+  newTsFile.getAbsolutePath(), newTsFile.getParentFile().getName());
+  throw new TsFileProcessorException(e);
 
 Review comment:
   If a DiskSpaceInsufficientException is risen, it might be better to set the 
read only flag.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323131514
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/transfer/IDataTransferManager.java
 ##
 @@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.transfer;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Set;
+import org.apache.iotdb.db.exception.SyncConnectionException;
+import org.apache.thrift.TException;
+
+/**
+ * This interface is used to realize the data transmission part of 
synchronization task, and is also
+ * the most important part of synchronization task. By screening out all 
transmission files to be
+ * synchronized in SyncFileManager, these files are 
synchronized to the receiving end
+ * to complete the synchronization task.
+ */
+public interface IDataTransferManager {
+
+  void init();
+
+  /**
+   * Establish a connection to receiver end.
+   */
+  void establishConnection(String serverIp, int serverPort) throws 
SyncConnectionException;
+
+  /**
+   * Confirm identity, the receiver will check whether the sender has 
synchronization privileges.
+   */
+  void confirmIdentity() throws SyncConnectionException, IOException;
+
+  /**
+   * Sync schema file to receiver before all data to be synced.
+   */
+  void syncSchema() throws SyncConnectionException, TException;
+
+  /**
+   * For deleted files in a storage group, sync them to receiver side and load 
these data in
+   * receiver.
 
 Review comment:
   Is it necessary to load data of deleted files?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321613509
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/IFileLoader.java
 ##
 @@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader.LoadTask;
+
+/**
+ * This interface is used to load files, including deleted files and new 
tsfiles. The
+ * producer-consumer model is used to load files. A background consumer thread 
is used to load
+ * files. There is a queue recording task. After receiving a file, the 
receiver adds a task to the
 
 Review comment:
   "task" -> "tasks"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r322520129
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/transfer/SyncServiceImpl.java
 ##
 @@ -0,0 +1,343 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.transfer;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.iotdb.db.concurrent.ThreadName;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.PathErrorException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.metadata.MetadataConstant;
+import org.apache.iotdb.db.metadata.MetadataOperationType;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogAnalyzer;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogger;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.FilePathUtils;
+import org.apache.iotdb.db.utils.SyncUtils;
+import org.apache.iotdb.service.sync.thrift.ResultStatus;
+import org.apache.iotdb.service.sync.thrift.SyncService;
+import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncServiceImpl implements SyncService.Iface {
+
+  private static final Logger logger = 
LoggerFactory.getLogger(SyncServiceImpl.class);
+
+  private IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
+
+  private ThreadLocal syncFolderPath = new ThreadLocal<>();
+
+  private ThreadLocal currentSG = new ThreadLocal<>();
+
+  private ThreadLocal syncLog = new ThreadLocal<>();
+
+  private ThreadLocal senderName = new ThreadLocal<>();
+
+  private ThreadLocal currentFile = new ThreadLocal<>();
+
+  private ThreadLocal currentFileWriter = new ThreadLocal<>();
+
+  private ThreadLocal messageDigest = new ThreadLocal<>();
+
+  /**
+   * Verify IP address of sender
+   */
+  @Override
+  public ResultStatus check(String ipAddress, String uuid) {
+Thread.currentThread().setName(ThreadName.SYNC_SERVER.getName());
+if (SyncUtils.verifyIPSegment(config.getIpWhiteList(), ipAddress)) {
+  senderName.set(ipAddress + SyncConstant.SYNC_DIR_NAME_SEPARATOR + uuid);
+  if (checkRecovery()) {
+logger.info("Start to sync with sender {}", senderName.get());
+return getSuccessResult();
+  } else {
+return getErrorResult("Receiver is processing data from previous sync 
tasks");
+  }
+} else {
+  return getErrorResult(
+  "Sender IP is not in the white list of receiver IP and 
synchronization tasks are not allowed.");
+}
+  }
+
+  private boolean checkRecovery() {
+try {
+  if (currentFileWriter.get() != null && currentFileWriter.get().isOpen()) 
{
+currentFileWriter.get().close();
+  }
+  if (syncLog.get() != null) {
+syncLog.get().close();
+  }
+  return SyncReceiverLogAnalyzer.getInstance().recover(senderName.get());
+} catch (IOException e) {
+  logger.error("Check recovery state fail", e);
+  return false;
+}
+  }
+
+  @Override
+  public R

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321599919
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/FileLoader.java
 ##
 @@ -0,0 +1,227 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more 
contributor license
+ * agreements.  See the NOTICE file distributed with this work for additional 
information regarding
+ * copyright ownership.  The ASF licenses this file to you under the Apache 
License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with the 
License.  You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software 
distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
KIND, either express
+ * or implied.  See the License for the specific language governing 
permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.exception.TsFileProcessorException;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.tsfile.file.metadata.ChunkGroupMetaData;
+import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
+import org.apache.iotdb.tsfile.file.metadata.TsDeviceMetadata;
+import org.apache.iotdb.tsfile.file.metadata.TsDeviceMetadataIndex;
+import org.apache.iotdb.tsfile.file.metadata.TsFileMetaData;
+import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoader implements IFileLoader {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoader.class);
+
+  private static final int WAIT_TIME = 100;
+
+  private String syncFolderPath;
+
+  private String senderName;
+
+  private BlockingQueue queue = new LinkedBlockingQueue<>();
+
+  private LoadLogger loadLog;
+
+  private LoadType curType = LoadType.NONE;
+
+  private volatile boolean endSync = false;
+
+  private FileLoader(String senderName, String syncFolderPath) throws 
IOException {
+this.senderName = senderName;
+this.syncFolderPath = syncFolderPath;
+this.loadLog = new LoadLogger(new File(syncFolderPath, 
SyncConstant.LOAD_LOG_NAME));
+FileLoaderManager.getInstance().addFileLoader(senderName, this);
+FileLoaderManager.getInstance().addLoadTaskRunner(loadTaskRunner);
+  }
+
+  public static FileLoader createFileLoader(String senderName, String 
syncFolderPath)
+  throws IOException {
+return new FileLoader(senderName, syncFolderPath);
+  }
+
+  public static FileLoader createFileLoader(File syncFolder)
+  throws IOException {
+return new FileLoader(syncFolder.getName(), syncFolder.getAbsolutePath());
+  }
+
+  private Runnable loadTaskRunner = () -> {
+try {
+  while (true) {
+if (queue.isEmpty() && endSync) {
+  cleanUp();
+  break;
+}
+LoadTask loadTask = queue.poll(WAIT_TIME, TimeUnit.MILLISECONDS);
+if (loadTask != null) {
+  try {
+handleLoadTask(loadTask);
+  } catch (Exception e) {
+LOGGER.error("Can not load task {}", loadTask, e);
+  }
+}
+  }
+} catch (InterruptedException e) {
+  LOGGER.error("Can not handle load task", e);
+}
+  };
+
+  @Override
+  public void addDeletedFileName(File deletedFile) {
+queue.add(new LoadTask(deletedFile, LoadType.DELETE));
+  }
+
+  @Override
+  public void addTsfile(File tsfile) {
+queue.add(new LoadTask(tsfile, LoadType.ADD));
+  }
+
+  @Override
+  public void endSync() {
+if (!endSync && 
FileLoaderManager.getInstance().containsFileLoader(senderName)) {
+  this.endSync = true;
+}
+  }
+
+  @Override
+  public void handleLoadTask(LoadTask task) throws IOException {
+switch (task.type) {
+  case ADD:
+loadNewTsfile(task.file);
+break;
+  case DELETE:
+loadDeletedFile(task.file);
+break;
+  default:
+LOGGER.error("Wrong load task type {}", task.type);
+}
+  }
+
+  private void loadNewTsfile(File newTsFile) throws IOException {
+if (curType != LoadType.ADD) {
+  loadLog.startLoadTsFiles();
+  curType = LoadType.ADD;
+}
+if (!newTsFile.exists()) {
+  LOGGER.info("Tsfile {} doesn't exist.", newTsFile.getAbs

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321614222
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/IFileLoader.java
 ##
 @@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader.LoadTask;
+
+/**
+ * This interface is used to load files, including deleted files and new 
tsfiles. The
+ * producer-consumer model is used to load files. A background consumer thread 
is used to load
+ * files. There is a queue recording task. After receiving a file, the 
receiver adds a task to the
+ * queue. When all files are loaded and the synchronization task is completed, 
the thread is
+ * closed.
+ */
+public interface IFileLoader {
 
 Review comment:
   If you create an interface, you should use it wherever possible (declare the 
variables using interface classes instead of concrete classes), or this 
abstraction will become pointless.
   Check other interfaces for the same problem.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321619322
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/recover/SyncReceiverLogAnalyzer.java
 ##
 @@ -0,0 +1,147 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.recover;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import org.apache.commons.io.FileUtils;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.load.LoadLogger;
+import org.apache.iotdb.db.sync.receiver.load.LoadType;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.FilePathUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncReceiverLogAnalyzer implements ISyncReceiverLogAnalyzer {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncReceiverLogAnalyzer.class);
+
+  private SyncReceiverLogAnalyzer() {
+
+  }
+
+  public static SyncReceiverLogAnalyzer getInstance() {
+return SyncReceiverLogAnalyzerHolder.INSTANCE;
+  }
+
+  @Override
+  public void recoverAll() throws IOException {
+String[] dataDirs = 
IoTDBDescriptor.getInstance().getConfig().getDataDirs();
+LOGGER.info("Start to recover all sync state for sync receiver.");
+for (String dataDir : dataDirs) {
+  if (!new File(FilePathUtils.regularizePath(dataDir) + 
SyncConstant.SYNC_RECEIVER).exists()) {
+continue;
+  }
+  for (File syncFolder : new File(
+  FilePathUtils.regularizePath(dataDir) + SyncConstant.SYNC_RECEIVER)
+  .listFiles()) {
+recover(syncFolder);
+  }
+}
+LOGGER.info("Finish to recover all sync state for sync receiver.");
 
 Review comment:
   "state" -> "states"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323109252
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/sender/manage/SyncFileManager.java
 ##
 @@ -0,0 +1,192 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.sender.manage;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.engine.merge.task.MergeTask;
+import org.apache.iotdb.db.engine.modification.ModificationFile;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.sync.sender.conf.SyncSenderDescriptor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncFileManager implements ISyncFileManager {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(SyncFileManager.class);
+
+  /**
+   * All storage groups on the disk where the current sync task is executed
+   */
+  private Set allSG;
+
+  /**
+   * Key is storage group, value is the set of current sealed tsfile in the 
storage group.
+   */
+  private Map> currentSealedLocalFilesMap;
+
+  /**
+   * Key is storage group, value is the set of last local tsfiles in the 
storage group, which don't
+   * contains those tsfiles which are not synced successfully.
 
 Review comment:
   "don't contains" -> "doesn't contain"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323140872
 
 

 ##
 File path: 
server/src/test/java/org/apache/iotdb/db/sync/receiver/load/FileLoaderTest.java
 ##
 @@ -0,0 +1,434 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Random;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.StorageGroupProcessor;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.StartupException;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.service.IoTDB;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.EnvironmentUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoaderTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoaderTest.class);
+  private static final String SG_NAME = "root.sg";
+  private static IoTDB daemon;
+  private String dataDir;
+  private FileLoader fileLoader;
+
+  @Before
+  public void setUp()
+  throws IOException, InterruptedException, StartupException, 
DiskSpaceInsufficientException, MetadataErrorException {
+EnvironmentUtils.closeStatMonitor();
+daemon = IoTDB.getInstance();
+daemon.active();
+EnvironmentUtils.envSetUp();
+dataDir = new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile())
+.getParentFile().getAbsolutePath();
+initMetadata();
+  }
+
+  private void initMetadata() throws MetadataErrorException {
+MManager mmanager = MManager.getInstance();
+mmanager.init();
+mmanager.clear();
+mmanager.setStorageLevelToMTree("root.sg0");
+mmanager.setStorageLevelToMTree("root.sg1");
+mmanager.setStorageLevelToMTree("root.sg2");
+  }
+
+  @After
+  public void tearDown() throws InterruptedException, IOException, 
StorageEngineException {
+daemon.stop();
+EnvironmentUtils.cleanEnv();
+  }
+
+  @Test
+  public void loadNewTsfiles() throws IOException, StorageEngineException {
+fileLoader = FileLoader.createFileLoader(getReceiverFolderFile());
+Map> allFileList = new HashMap<>();
+Map> correctSequenceLoadedFileMap = new HashMap<>();
+
+// add some new tsfiles
+Random r = new Random(0);
+long time = System.currentTimeMillis();
+for (int i = 0; i < 3; i++) {
+  for (int j = 0; j < 10; j++) {
+allFileList.putIfAbsent(SG_NAME + i, new ArrayList<>());
+correctSequenceLoadedFileMap.putIfAbsent(SG_NAME + i, new HashSet<>());
+String rand = String.valueOf(r.nextInt(1));
+String fileName =
+getSnapshotFolder() + File.separator + SG_NAME + i + 
File.separator + (time + i * 100
++ j) + IoTDBConstant.FILE_NAME_SEPARATOR + rand
++ IoTDBConstant.FILE_NAME_SEPARATOR + "0.tsfile";
+File syncFile = new File(fileName);
+File dataFile = new File(
+
syncFile.getParentFile().getParentFile().getParentFile().getParentFile()
+.getParentFile(), IoTDBConstant.SEQUENCE_FLODER_NAME
++ File.separatorChar + syncFile.getParentFile().getName() + 
File.separatorChar
++ syncFile.getName());
+correctSequenceLoadedFileMap.get(SG_NAME + 
i).add(dataFile.getAbsolutePath());
+allFileList.get(SG_NAME + i).add(syncFile);
+if (!syncFile.getParentFile().exists()) {
+   

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r323524256
 
 

 ##
 File path: 
server/src/test/java/org/apache/iotdb/db/sync/receiver/load/FileLoaderTest.java
 ##
 @@ -0,0 +1,434 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Random;
+import java.util.Set;
+import org.apache.iotdb.db.conf.IoTDBConstant;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.StorageGroupProcessor;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.StartupException;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.service.IoTDB;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.EnvironmentUtils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoaderTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoaderTest.class);
+  private static final String SG_NAME = "root.sg";
+  private static IoTDB daemon;
+  private String dataDir;
+  private FileLoader fileLoader;
+
+  @Before
+  public void setUp()
+  throws IOException, InterruptedException, StartupException, 
DiskSpaceInsufficientException, MetadataErrorException {
+EnvironmentUtils.closeStatMonitor();
+daemon = IoTDB.getInstance();
+daemon.active();
+EnvironmentUtils.envSetUp();
+dataDir = new 
File(DirectoryManager.getInstance().getNextFolderForSequenceFile())
+.getParentFile().getAbsolutePath();
+initMetadata();
+  }
+
+  private void initMetadata() throws MetadataErrorException {
+MManager mmanager = MManager.getInstance();
+mmanager.init();
+mmanager.clear();
+mmanager.setStorageLevelToMTree("root.sg0");
+mmanager.setStorageLevelToMTree("root.sg1");
+mmanager.setStorageLevelToMTree("root.sg2");
+  }
+
+  @After
+  public void tearDown() throws InterruptedException, IOException, 
StorageEngineException {
+daemon.stop();
+EnvironmentUtils.cleanEnv();
+  }
+
+  @Test
+  public void loadNewTsfiles() throws IOException, StorageEngineException {
+fileLoader = FileLoader.createFileLoader(getReceiverFolderFile());
+Map> allFileList = new HashMap<>();
+Map> correctSequenceLoadedFileMap = new HashMap<>();
+
+// add some new tsfiles
+Random r = new Random(0);
+long time = System.currentTimeMillis();
+for (int i = 0; i < 3; i++) {
+  for (int j = 0; j < 10; j++) {
+allFileList.putIfAbsent(SG_NAME + i, new ArrayList<>());
+correctSequenceLoadedFileMap.putIfAbsent(SG_NAME + i, new HashSet<>());
+String rand = String.valueOf(r.nextInt(1));
+String fileName =
+getSnapshotFolder() + File.separator + SG_NAME + i + 
File.separator + (time + i * 100
++ j) + IoTDBConstant.FILE_NAME_SEPARATOR + rand
++ IoTDBConstant.FILE_NAME_SEPARATOR + "0.tsfile";
+File syncFile = new File(fileName);
+File dataFile = new File(
+
syncFile.getParentFile().getParentFile().getParentFile().getParentFile()
+.getParentFile(), IoTDBConstant.SEQUENCE_FLODER_NAME
++ File.separatorChar + syncFile.getParentFile().getName() + 
File.separatorChar
++ syncFile.getName());
+correctSequenceLoadedFileMap.get(SG_NAME + 
i).add(dataFile.getAbsolutePath());
+allFileList.get(SG_NAME + i).add(syncFile);
+if (!syncFile.getParentFile().exists()) {
+   

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321154160
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
+  } else {
+if (subsequentIndex != sequenceFileList.size()) {
+  loadTsFileByType(1, newTsFile, newTsFileResource, subsequentIndex);
+} else {
+  if (preIndex != -1) {
+loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
+  } else {
+loadTsFileByType(1, newTsFile, newTsFileResource, 
sequenceFileList.size());
+  }
 
 Review comment:
   I thought
   ```
   if (subsequentIndex == sequenceFileList.size() && preIndex != -1) {
   loadTsFileByType(1, newTsFile, newTsFileResource, preIndex + 1);
   } else {
   loadTsFileByType(1, newTsFile, newTsFileResource, 
subsequentIndex);
   }
   ```
   may reduce one if-else?


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321139138
 
 

 ##
 File path: server/src/main/java/org/apache/iotdb/db/conf/IoTDBConstant.java
 ##
 @@ -65,4 +65,9 @@ private IoTDBConstant() {
   public static final String USER = "User";
   public static final String PRIVILEGE = "Privilege";
 
+  // data folder name
+  public static final String SEQUENCE_FLODER_NAME = "sequence";
+  public static final String UNSEQUENCE_FLODER_NAME = "unsequence";
+  public static final String FILE_NAME_SEPARATOR = "-";
 
 Review comment:
   Better use `TSFILE_NAME_SEPARATOR`, since we have other files which may have 
their own separators.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321152866
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/engine/storagegroup/StorageGroupProcessor.java
 ##
 @@ -950,11 +960,272 @@ protected void mergeEndAction(List 
seqFiles, List endTime2) {
+  subsequenceCnt++;
+} else if (startTime2 > endTime1) {
+  preCnt++;
+} else {
+  isOverlap = true;
+  break outer;
+}
+  }
+}
+if (preCnt != 0 && subsequenceCnt != 0) {
+  isOverlap = true;
+  break;
+}
+if (preCnt == 0 && subsequenceCnt != 0) {
+  subsequentIndex = i;
+  break;
+}
+if (preCnt != 0 && subsequenceCnt == 0) {
+  preIndex = i;
+}
+  }
+
+  // loading tsfile by type
+  if (isOverlap) {
+loadTsFileByType(-1, newTsFile, newTsFileResource, 
unSequenceFileList.size());
 
 Review comment:
   Could you replace the "1" and "-1” with a named constant like 
LOAD_UNSEQUENCE and LOAD_SEQUENCE. Or you can just write two methods and call 
them respectively.


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321609413
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/FileLoader.java
 ##
 @@ -0,0 +1,227 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more 
contributor license
+ * agreements.  See the NOTICE file distributed with this work for additional 
information regarding
+ * copyright ownership.  The ASF licenses this file to you under the Apache 
License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with the 
License.  You may obtain
+ * a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software 
distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
KIND, either express
+ * or implied.  See the License for the specific language governing 
permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.apache.iotdb.db.engine.StorageEngine;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.StorageEngineException;
+import org.apache.iotdb.db.exception.TsFileProcessorException;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.tsfile.file.metadata.ChunkGroupMetaData;
+import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
+import org.apache.iotdb.tsfile.file.metadata.TsDeviceMetadata;
+import org.apache.iotdb.tsfile.file.metadata.TsDeviceMetadataIndex;
+import org.apache.iotdb.tsfile.file.metadata.TsFileMetaData;
+import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class FileLoader implements IFileLoader {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(FileLoader.class);
+
+  private static final int WAIT_TIME = 100;
+
+  private String syncFolderPath;
+
+  private String senderName;
+
+  private BlockingQueue queue = new LinkedBlockingQueue<>();
+
+  private LoadLogger loadLog;
+
+  private LoadType curType = LoadType.NONE;
+
+  private volatile boolean endSync = false;
+
+  private FileLoader(String senderName, String syncFolderPath) throws 
IOException {
+this.senderName = senderName;
+this.syncFolderPath = syncFolderPath;
+this.loadLog = new LoadLogger(new File(syncFolderPath, 
SyncConstant.LOAD_LOG_NAME));
+FileLoaderManager.getInstance().addFileLoader(senderName, this);
+FileLoaderManager.getInstance().addLoadTaskRunner(loadTaskRunner);
+  }
+
+  public static FileLoader createFileLoader(String senderName, String 
syncFolderPath)
+  throws IOException {
+return new FileLoader(senderName, syncFolderPath);
+  }
+
+  public static FileLoader createFileLoader(File syncFolder)
+  throws IOException {
+return new FileLoader(syncFolder.getName(), syncFolder.getAbsolutePath());
+  }
+
+  private Runnable loadTaskRunner = () -> {
+try {
+  while (true) {
+if (queue.isEmpty() && endSync) {
+  cleanUp();
+  break;
+}
+LoadTask loadTask = queue.poll(WAIT_TIME, TimeUnit.MILLISECONDS);
+if (loadTask != null) {
+  try {
+handleLoadTask(loadTask);
+  } catch (Exception e) {
+LOGGER.error("Can not load task {}", loadTask, e);
+  }
+}
+  }
+} catch (InterruptedException e) {
+  LOGGER.error("Can not handle load task", e);
+}
+  };
+
+  @Override
+  public void addDeletedFileName(File deletedFile) {
+queue.add(new LoadTask(deletedFile, LoadType.DELETE));
+  }
+
+  @Override
+  public void addTsfile(File tsfile) {
+queue.add(new LoadTask(tsfile, LoadType.ADD));
+  }
+
+  @Override
+  public void endSync() {
+if (!endSync && 
FileLoaderManager.getInstance().containsFileLoader(senderName)) {
+  this.endSync = true;
+}
+  }
+
+  @Override
+  public void handleLoadTask(LoadTask task) throws IOException {
+switch (task.type) {
+  case ADD:
+loadNewTsfile(task.file);
+break;
+  case DELETE:
+loadDeletedFile(task.file);
+break;
+  default:
+LOGGER.error("Wrong load task type {}", task.type);
+}
+  }
+
+  private void loadNewTsfile(File newTsFile) throws IOException {
+if (curType != LoadType.ADD) {
+  loadLog.startLoadTsFiles();
+  curType = LoadType.ADD;
+}
+if (!newTsFile.exists()) {
+  LOGGER.info("Tsfile {} doesn't exist.", newTsFile.getAbs

[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321616674
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/load/ILoadLogger.java
 ##
 @@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.load;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * This interface is used to log progress in the process of loading deleted 
files and new tsfiles.
+ * If the loading tasks are completed normally and there are no exceptions, 
the log records will be
+ * deleted; otherwise, the status can be restored according to the log at the 
start of each task. It
+ * ensures the correctness of synchronization module when system crash or 
network abnormality
+ * occur.
 
 Review comment:
   "system crash" -> "system crashed"
"occur" -> "occured"


This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services


[GitHub] [incubator-iotdb] jt2594838 commented on a change in pull request #372: [IOTDB-198]Reimplementation sync module

2019-09-11 Thread GitBox
jt2594838 commented on a change in pull request #372: 
[IOTDB-198]Reimplementation sync module
URL: https://github.com/apache/incubator-iotdb/pull/372#discussion_r321667507
 
 

 ##
 File path: 
server/src/main/java/org/apache/iotdb/db/sync/receiver/transfer/SyncServiceImpl.java
 ##
 @@ -0,0 +1,343 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.iotdb.db.sync.receiver.transfer;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.iotdb.db.concurrent.ThreadName;
+import org.apache.iotdb.db.conf.IoTDBConfig;
+import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.conf.directories.DirectoryManager;
+import org.apache.iotdb.db.engine.storagegroup.TsFileResource;
+import org.apache.iotdb.db.exception.DiskSpaceInsufficientException;
+import org.apache.iotdb.db.exception.MetadataErrorException;
+import org.apache.iotdb.db.exception.PathErrorException;
+import org.apache.iotdb.db.metadata.MManager;
+import org.apache.iotdb.db.metadata.MetadataConstant;
+import org.apache.iotdb.db.metadata.MetadataOperationType;
+import org.apache.iotdb.db.sync.receiver.load.FileLoader;
+import org.apache.iotdb.db.sync.receiver.load.FileLoaderManager;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogAnalyzer;
+import org.apache.iotdb.db.sync.receiver.recover.SyncReceiverLogger;
+import org.apache.iotdb.db.sync.sender.conf.SyncConstant;
+import org.apache.iotdb.db.utils.FilePathUtils;
+import org.apache.iotdb.db.utils.SyncUtils;
+import org.apache.iotdb.service.sync.thrift.ResultStatus;
+import org.apache.iotdb.service.sync.thrift.SyncService;
+import org.apache.iotdb.tsfile.file.metadata.enums.CompressionType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class SyncServiceImpl implements SyncService.Iface {
+
+  private static final Logger logger = 
LoggerFactory.getLogger(SyncServiceImpl.class);
+
+  private IoTDBConfig config = IoTDBDescriptor.getInstance().getConfig();
+
+  private ThreadLocal syncFolderPath = new ThreadLocal<>();
+
+  private ThreadLocal currentSG = new ThreadLocal<>();
+
+  private ThreadLocal syncLog = new ThreadLocal<>();
+
+  private ThreadLocal senderName = new ThreadLocal<>();
+
+  private ThreadLocal currentFile = new ThreadLocal<>();
+
+  private ThreadLocal currentFileWriter = new ThreadLocal<>();
+
+  private ThreadLocal messageDigest = new ThreadLocal<>();
+
+  /**
+   * Verify IP address of sender
+   */
+  @Override
+  public ResultStatus check(String ipAddress, String uuid) {
+Thread.currentThread().setName(ThreadName.SYNC_SERVER.getName());
+if (SyncUtils.verifyIPSegment(config.getIpWhiteList(), ipAddress)) {
+  senderName.set(ipAddress + SyncConstant.SYNC_DIR_NAME_SEPARATOR + uuid);
+  if (checkRecovery()) {
+logger.info("Start to sync with sender {}", senderName.get());
+return getSuccessResult();
+  } else {
+return getErrorResult("Receiver is processing data from previous sync 
tasks");
+  }
+} else {
+  return getErrorResult(
+  "Sender IP is not in the white list of receiver IP and 
synchronization tasks are not allowed.");
+}
+  }
+
+  private boolean checkRecovery() {
+try {
+  if (currentFileWriter.get() != null && currentFileWriter.get().isOpen()) 
{
+currentFileWriter.get().close();
+  }
+  if (syncLog.get() != null) {
+syncLog.get().close();
+  }
+  return SyncReceiverLogAnalyzer.getInstance().recover(senderName.get());
+} catch (IOException e) {
+  logger.error("Check recovery state fail", e);
+  return false;
+}
+  }
+
+  @Override
+  public R