2014-12-05 2 views
2

데이터 소스에서 일괄 처리 된 데이터를 수신하고 해당 데이터의 직렬화 된 콘텐츠를 파일 (항상 동일한 파일)에 쓰는 클래스를 운영하고 있습니다. 이를 위해 인스턴스를 생성 할 때 제일 먼저해야 할 일은 해당 파일이 존재하는지 확인하고 그렇지 않다면 생성하는 것입니다. 이것은 문제없이 파일을 만드는 것처럼 보이지만, onOperationsBatchSynchronization 메서드를 사용하여 파일에 직렬화 된 객체를 추가하려고하면 문제가 발생합니다. HDFS에 추가하지 못했습니다.

는 한 클래스의 코드이다

public class HDFSSpaceSynchronizationEndpoint extends SpaceSynchronizationEndpoint { 

    private final static Logger LOG = LoggerFactory.getLogger(HDFSSpaceSynchronizationEndpoint.class); 
    private final String uriToFileToWrite; 
    private final HDFSFileUtil hdfsFileUtil; 

    public HDFSSpaceSynchronizationEndpoint(HDFSFileUtil hdfsFileUtil) { 
     Validate.notNull(hdfsFileUtil); 
     this.hdfsFileUtil = hdfsFileUtil; 
     uriToFileToWrite = hdfsFileUtil.getUriToHdfs() + "/object-container"; 
     createFileIfNeeded(); 
    } 

    private void createFileIfNeeded() { 
     final String methodName = "createFileIfNeeded"; 
     synchronized (this) { 
      try { 
       if (!hdfsFileUtil.fileExistsInCluster(uriToFileToWrite)) { 
        hdfsFileUtil.createFileInCluster(uriToFileToWrite); 
       } 
      } catch (IOException e) { 
       LOG.error(methodName, "", "Error creating the file in the cluster: {}", e); 
      } 
     } 
    } 

    @Override 
    public void onOperationsBatchSynchronization(OperationsBatchData batchData) { 
     final String methodName = "onOperationsBatchSynchronization"; 
     LOG.error(methodName, "", "Batch operation received: {}", batchData.getSourceDetails().getName()); 
     DataSyncOperation[] operations = batchData.getBatchDataItems(); 
     synchronized (this) { 
      for (DataSyncOperation operation : operations) { 
       try { 
        hdfsFileUtil.writeObjectToAFile((Serializable) operation.getDataAsObject(), uriToFileToWrite); 
       } catch (IOException e) { 
        LOG.error(methodName, "", "Error writing the object to a file in the cluster: {}", e); 
       } 
      } 
     } 
    } 
} 

그리고이 공간과 상호 작용을 담당하는 클래스 코드 :

public class HDFSFileUtilImpl implements HDFSFileUtil { 

    private final static Logger LOG = LoggerFactory.getLogger(HDFSFileUtilImpl.class); 
    private final static boolean DELETE_RECURSIVELY = true; 
    private final String uriToHdfs; 
    private final FileSystem fileSystem; 

    public HDFSFileUtilImpl(HDFSConfiguration config, String uriToHdfs, String user) { 
     Validate.notNull(config); 
     Validate.notEmpty(uriToHdfs); 
     Validate.notEmpty(user); 
     this.uriToHdfs = uriToHdfs; 
     try { 
      fileSystem = FileSystem.get(new URI(uriToHdfs), config.getConfiguration(), user); 
     } catch (IOException | URISyntaxException | InterruptedException e) { 
      LOG.error("constructor", "", "HDFSFileUtilImpl constructor failed: {}", e); 
      throw new IllegalStateException(e); 
     } 
    } 

    @Override 
    public String getUriToHdfs() { 
     return uriToHdfs; 
    } 

    @Override 
    public void writeObjectToAFile(Serializable obj, String fileUri) throws IOException { 
     Validate.notNull(obj); 
     Validate.notEmpty(fileUri); 
     FSDataOutputStream out; 
     if (!fileExistsInCluster(fileUri)) { 
      throw new IllegalArgumentException("File with URI: " + fileUri + " does not exist in the cluster"); 
     } 
     out = fileSystem.append(new Path(fileUri)); 
     byte[] objByteArray = getBytesFromObject(obj); 
     out.write(objByteArray); 
     out.close(); 
    } 

    private byte[] getBytesFromObject(Object obj) throws IOException { 
     byte[] retByteArray = null; 
     // try/catch used only to be able to use "try with resources" feature 
     try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos);) { 
      out.writeObject(obj); 
      retByteArray = bos.toByteArray(); 
     } catch (IOException e) { 
      throw new IOException(e); 
     } 
     return retByteArray; 
    } 

    @Override 
    public void createFileInCluster(String uriOfFile) throws IOException { 
      Validate.notEmpty(uriOfFile); 
      fileSystem.create(new Path(uriOfFile)); 
    } 

    @Override 
    public boolean fileExistsInCluster(String uri) throws IOException { 
     Validate.notEmpty(uri); 
     boolean result = false; 
     result = fileSystem.exists(new Path(uri)); 
     return result; 
    } 

    ... 
} 

데이터 소스는 세 개의 연결을 설립 내 구성 요소와 함께 onOperationsBatchSynchronization 메서드가 동시에 호출되고 있습니다. 그래서 동기화 블록이 사용되지만 로그와 함께 다음과 같은 예외가 발생합니다.

10:09:23.727 ERROR - onOperationsBatchSynchronization 
org.apache.hadoop.ipc.RemoteException: Failed to create file [/object-container] for [DFSClient_NONMAPREDUCE_1587728611_73] for client [127.0.0.1], because this file is already being created by [DFSClient_NONMAPREDUCE_1972611521_106] on [127.0.0.1] 
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.recoverLeaseInternal(FSNamesystem.java:2636) 
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.appendFileInternal(FSNamesystem.java:2462) 
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.appendFileInt(FSNamesystem.java:2700) 
at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.appendFile(FSNamesystem.java:2663) 
at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.append(NameNodeRpcServer.java:559) 
at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolServerSideTranslatorPB.append(ClientNamenodeProtocolServerSideTranslatorPB.java:388) 
at org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos$ClientNamenodeProtocol$2.callBlockingMethod(ClientNamenodeProtocolProtos.java) 
at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:585) 
at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:928) 
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2013) 
at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2009) 
at java.security.AccessController.doPrivileged(Native Method) 
at javax.security.auth.Subject.doAs(Subject.java:415) 
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1614) 
at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2007) 

그래서 여기에서 문제가 될 수있는 것은 무엇입니까? 몇 가지 유닛 테스트 (통합과 유사, 실행중인 Hadoop 설정에 의존하기 때문에) 및 HDFSFileUtilImpl의 모든 메소드가 올바르게 작동하고 예상되는 결과를 제공합니다.

편집 : 클러스터에 동일한 파일을 추가하는 대신 파일을 쓰려고 시도했지만 정상적으로 작동합니다. 그래서 나는 허가 문제를 버릴 것이다.

+0

내가 거기에 생각 때문에하는 자사의 파일 – Mr37037

+0

를 만들 수 없습니다하지만 할 수있는 몇 가지 권한 문제입니다 밝혔다되고 그건

,이 HDFSFileUtilImpl의 방법 createFileInCluster 지금 구현되는 방법입니다 그래도 파일을 만듭니다. 몇 가지 테스트를 수행하면서 파일을 추가하는 대신 파일을 만들려고했는데 문제없이 새 파일을 만들었습니다. 이 – jbarren

답변

1

마지막으로 오류가 제거되었습니다. 분명히 createfilesystem에서 호출 할 때 반환되는 FSDataOutputStream을 닫아야합니다.

@Override 
public void createFileInCluster(String uriOfFile) throws IOException { 
     Validate.notEmpty(uriOfFile); 
     FSDataOutputStream out = fileSystem.create(new Path(uriOfFile)); 
     out.close(); 
} 
+0

에 게시 할 게시물을 편집하여 기존 파일에 실제로 추가합니까? – matanster

+1

아니요,이 코드는 맨 위에 제시된 코드에서 잘못된 점만 지적합니다. 아니요,이 코드는 맨 위에 제시된 코드에서 잘못된 점만 지적합니다. 문제는 파일이 생성 후에 닫히지 않았지만 파일에 추가 된 코드가 초기 코드에서와 동일하다는 것입니다. 'writeObjectToAFile' 메서드를 보겠습니다. – jbarren

+0

사실, Google에서는 hdfsFileUtil의 writeObjectToAFile 메소드에 관해서 아무것도 발견하지 못했습니다. – matanster

관련 문제