본문으로 바로가기
반응형

하둡을 실행할때, 콘솔에서 추가 옵션을 줄수 있습니다.

또한 콘솔에서 추가한 옵션을 코드상에서 받아서 읽어서 사용할 수도 있습니다.


콘솔에서 입력된 옵션을 분석하기 위해 org.apache.hadoop.util 클래스에서 GenericOptionParser를 제공합니다.

또한 실행을 도와주기 위해 Tool 인터페이스와 Tool을 상속받아 override한 run() 함수를 실행해 주는 ToolRunner 헬퍼 클래스를 제공합니다.


이글은 "시작하세요! 하둡 프로그래밍"을 참고하였습니다

대부분의 내용이 생략되고 정리된 내용이므로 자세한 내용은 꼭 책을 구입하여 확인하시기 바랍니다. 


GenericOptionParser 제공 옵션

-conf <파일명>: 해당 파일명을 환경설정에 있는 리소스 정보에 추가합니다.
-D <옵션값>: 환경설정 파일에 새로운 값을 설정
-fs <Namenode host: port> : 네임노드를 새로 설정
-jt <JobTasker host: port> : 잡트래커 새로 설정
-files <파일1, 파일2,...> : 로컬에 있는 파일을 hfds로 복사
-libjars <Jar파일1, jar파일2,...> : 로컬의 jar 파일을 hdfs로 복사 후 맵리듀스 태크스의 classpaht에 추가
-archives <archive파일1, archive파일2....> :로컬의 아카이브 파일을 hdfs에 복사후 압축해제


콘솔 명령어 옵션 읽기

예제로 콘솔 명령어에 추가적인 옵션을 설정후 해당 옵션을 mapper에서 가져다가 쓰도록 구성하겠습니다.


hadoop으로 하기와 같은 명령어를 실행합니다.

$ hadoop jar a.jar com.hadoop.test.DelayCount -D workType=departure input output

a.jar 를 실행하며, main 함수가 있는 package 경로는 com.hadoop.test.DelayCount 입니다.

추가 옵션으로 workType을 설정하고 값은 "departure"을 줬습니다.

읽어들일 파일 소스폴더는 input, 결과를 넣을 폴더는 output 입니다.


먼저 mapper 코드 입니다.

public class DelayCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
  // 작업 구분
  private String workType;
  // map 출력값
  private final static IntWritable outputValue = new IntWritable(1);
  // map 출력키
  private Text outputKey = new Text();

  @Override
  public void setup(Context context) throws IOException, InterruptedException {
    workType = context.getConfiguration().get("workType");
  }

  public void map(LongWritable key, Text value, Context context)
    throws IOException, InterruptedException {

    AirlinePerformanceParser parser = new AirlinePerformanceParser(value);

    // 출발 지연 데이터 출력
    if (workType.equals("departure")) {
      if (parser.getDepartureDelayTime() > 0) {
        // 출력키 설정
        outputKey.set(parser.getYear() + "," + parser.getMonth());
        // 출력 데이터 생성
        context.write(outputKey, outputValue);
      }
    // 도착 지연 데이터 출력
    } else if (workType.equals("arrival")) {
      if (parser.getArriveDelayTime() > 0) {
        // 출력키 설정
        outputKey.set(parser.getYear() + "," + parser.getMonth());
        // 출력 데이터 생성
        context.write(outputKey, outputValue);
      }
    }
  }
}


setup은 Mapper가 생성될때 한번만 호출 됩니다.

간단하게 setup() 함수에서 configuration() 함수를 이용하여 콘솔에서 입력된 옵션값을 읽습니다.

workType = context.getConfiguration().get("workType");

workType의 값으로 text를 사용했기 때문에 get() 함수로 값을 얻어왔습니다.

만약 int 나 boolean이라면 getInt(), getBoolean() 등으로 값을 얻어올 수 있습니다.


옵션에서 읽은 값을 받아와 멤버변수에 저장한후 코드에서 분기를 위해 사용하였습니다.


Main함수 구현

public class DelayCount extends Configured implements Tool {

  public static void main(String[] args) throws Exception {
    // Tool 인터페이스 실행
    int res = ToolRunner.run(new Configuration(), new DelayCount(), args);
    for (int i =0; i < args.length ; i++) {
      System.out.println("args1[" + i + "]= " + args[i]);
    }
    System.out.println("MR-Job Result:" + res);
  }

  public int run(String[] args) throws Exception {
    for (int i =0; i < args.length ; i++) {
      System.out.println("args2[" + i + "]= " + args[i]);
    }
 
    // 입출력 데이터 경로 확인
    if (otherArgs.length != 2) {
      System.err.println("Usage: DelayCount  ");
      System.exit(2);
    }
    // Job 이름 설정
    Job job = new Job(getConf(), "DelayCount");

    // 입출력 데이터 경로 설정
    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
    
    ... // 기타 Job 설정들...
}


환경정보를 제어할 수 있도록 Configured 클래스를 상속받고, 사용자 정의 옵션을 정의할 수 있도록 tool 인터페이스를 구현합니다.

main 함수에서 args를 출력하면 총 네개가 찍히지만 run 함수에서 받은 args param은 두개의 값만 가지고 있습니다.


이는 ToolRunner의 run() 함수에서 아래와 같이 처리하고 있기 때문입니다.

public static int run(Configuration conf, Tool tool, String[] args) throws Exception {
        if (conf == null) {
            conf = new Configuration();
        }

        GenericOptionsParser parser = new GenericOptionsParser(conf, args);
        tool.setConf(conf);
        String[] toolArgs = parser.getRemainingArgs();
        return tool.run(toolArgs);
    }


GenericOptionParser의 getRemainingArgs()를 호출하면 기본 옵션이 붙은 argument는 전부 제외하고 추가한 "input"  "output" 값만 넘어옵니다.

참고로 main의 args에는 "-D" , "worktype=departure", "input" , "output" 네게가 넘어옵니다.

반응형