Big Data 개요 강명철 mc.kang08@gmail.com Contents • 빅데이터란? • Hadoop 이해하기 • Hadoop 설치하기 빅데이터란? 2 빅데이터 정의 인터넷 성숙 모바일 확산 데이터의 폭발적 증가 소셜 네트워크 빅데이터 정의 데이터 수집 데이터 가공 시스템 개선 새로운 의미 도출 빅데이터 정의 “서버 한대로 처리할 수 없는 규모의 데이터” “기존의 SW로는 처리할 수 없는 규모의 데이터” : Scale Out “3V (Volume, Velocity, Varity) + Variability “ 웹 검색엔진 데이터 (e.g. 1조 Page * 4KB = 4PB) 검색어 로그 및 클릭 로그 데이터 (e.g. 구글 Flu Trends, 구글 번역) Device 생성 데이터 (스마트 패킷 데이터) 소셜 미디어 데이터 빅데이터 시스템 구성 데이터 수집 데이터 저장 및 처리 워크플로우 처리결과 억세스 시각화 빅데이터 시스템 구성 데이터 수집 Flume Chukwa Kafka 데이터 저장 및 처리 HDFS MapReduce 워크플로우 Cascading Oozie Azkaban Ambrose 처리결과 억세스 RDBMS NoSQL 검색엔진 시각화 Infographics R Pentaho 빅데이터 성공 스토리 Netflix 영화 추천 서비스 (기존 주 1회 -> 일 1호) eBay 쿼리로그 마이닝 (10억건 이상의 사용자 검색데이터) Twitter 대용량 머신 러닝 (1일 3억건 이상의 트윗 분석, 팔로우형태, 정서) 신용 카드사 Fraud Detection Model 수립 빅데이터 주요 회사 Apache Software Foundation Cloudera HotornWorks MapR Gruter NexR HADOOP 이해하기 10 Hadoop 이란? Hadoop 이란? Hadoop 참조모델 • ‘2003 The Google File System • ‘2004 MapReduce : Simplified Data Processing on Large Cluster 더그 커팅 Nutch/Lucene ‘2006 Appache Top 프로젝트로 승격 오픈소스 데이터가 있는 곳으로 코드 이동 스케일 아웃 단순 데이터 모델 오프라인 배치 프로세싱에 최적화 MapReduce Paradigm Scalability Applications UseCases EcoSystems Hadoop 구성 • Distributed file system (HDFS) – Single namespace for entire cluster – Replicates data 3x for fault-tolerance • MapReduce framework – Executes user jobs specified as “map” and “reduce” functions – Manages work distribution & fault-tolerance Hadoop 구성 태스크 트래커 데이터 노드 잡트래커 태스크 트래커 네임노드 데이터 노드 태스크 트래커 데이터 노드 Hadoop Distributed File System HDFS Server Name node HDFS Client Application Local file system Block size: 2K Data Nodes 하부 운영체제의 파일 시스템 그대로 사용 Fault Tolerance Write Once Read Many Block size: 128M Replicated Hadoop Distributed File System HDFS Server Master node blockmap HDFS Client heartbeat Application Local file system Block size: 2K Name Nodes Block size: 128M Replicated 21 MapReduce MapReduce MapReduce 데이터가 있는 서버로 코드 전송 Key/Value 데이터 셋 Shared Nothing 아키텍처 오프라인 배치 처리에 적합 MapReduce 병렬도가 매우 높은 단순 작업 로그분석 머신러닝 (Clustering, Classification 등) 리얼타임 데이터 스트림 처리 반복 실행이 많이 필요한 작업들 MapReduce 구현 시 네트워크 데이터 전송량이 너무 큰 경우 HADOOP 설치하기 27 Hadoop 설치 실습 환경: CentOS 6.3 서버 환경 확인 인코딩 방식 확인 확인 : echo $LANG 결과 : ko_KR.utf8 이어야 함 인코딩 방식 변경 편집 : vi /etc/sysconfig/i18n 내용 : LANG=“ko_KR.utf8” 인코딩 방식 반영 source /etc/sysconfig/i18n Hadoop 설치 자바 설치 : JDK 1.6 이상 권장 Hadoop : 1.0.4 Yum install java-1.6.0-openjdk Download Hadoop Wget http://archive.apache.org/dist/hadoop/core/hadoop-1.0.4/hadoop-1.0.4.tar.gz Tar xvfz hadoop-1.0.3.tar.gz Vi ~/.bashrc export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk.x86_64 export PATH=$PATH:$JAVA_HOME/bin export HADOOP_HOME=/home/mckang/hadoop-1.0.3 Source ~/.bashrc Hadoop 설치 Standalone Mode 확인 초기 설정 변경 없음 : core-site.xml, mapred-site.xml, hdfs-site.xml WordCount 예제 확인 Cd $HADOOP_HOME ./bin/hadoop jar hadoop-examples*.jar wordcount README.txt ~/wc-output Hadoop 설치 SSH 설정 키페어 생성 Ssh-keygen –t rsa 공개키 배포 Scp ~/.ssh/id_rsa.pub 사용자@데이터노드:/home/사용자 인증키 등록 (각 데이터 노드에서) Cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys (655권한 확인) 확인 Ssh 데이터노드 Hadoop 설치 Pseudo Distributed Mode 확인 네임노드, 2차 네임노드, 데이터노드, 잡 트래커, 태스크 트래커 초기 설정 변경 Core-site.xml <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> <property> <name>hadoop.tmp.dir</name> <value>/home/mckang/hadoop-data</value> </property> </configuration> Hadoop 설치 Pseudo Distributed Mode 확인 네임노드, 2차 네임노드, 데이터노드, 잡 트래커, 태스크 트래커 초기 설정 변경 hdfs-site.xml <configuration> <property> <name>dfs.replication</name> <value>1</value> </property> </configuration> Hadoop 설치 Pseudo Distributed Mode 확인 네임노드, 2차 네임노드, 데이터노드, 잡 트래커, 태스크 트래커 초기 설정 변경 mapred-site.xml <configuration> <property> <name>mapred.job.tracker</name> <value>localhost:9001</value> </property> </configuration> Hadoop 설치 Pseudo Distributed Mode 확인 2차 네임노드 확인 Cat masters 데이터노드 확인 Cat slaves HDFS 포맷 Hadoop namenode 실행 Start-all.sh jps -format Hadoop 설치 Pseudo Distributed Mode 확인 잡트래커 : http://localhost:50030 네임노드 : http://localhost:50070 Hadoop 설치 Pseudo Distributed Mode 확인 파일 업로드 Hadoop fs -put README.txt /README.txt WordCount 예제 수행 Hadoop jar hadoop-examples-*.jar wordcount /README.txt /wc_output 결과 확인 Hadoop fs -cat /wc_output/p* HDFS COMMAND 38 HDFS Hadoop fs -{command} ls 디렉토리 출력 lsr 하위디렉토리 포함 출력 du 파일 사용량 출력 dus 전체 합계 파일 사용량 출력 cat 파일 내용 보기 text 압축파일 텍스트 보기 mkdir, cp, mv, rm, rmr put / copyFromLocal , get / copyToLocal, getmerge HDFS 개발환경 셋업 개발도구 다운로드 www.springsource.org/downloads/sts-ggts 메이븐 프로젝트 생성 <dependency> <groupId>org.apache.hadoop</groupId> <artifactId>hadoop-core</artifactId> <version>1.0.4</version> </dependency> HDFS HDFS API 테스트 import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; // 파일 저장 FSDataOutputStream outStream = hdfs.create(path); outStream.writeUTF(args[1]); outStream.close(); // 파일 출력 FSDataInputStream inputStream = hdfs.open(path); String inputString = inputStream.readUTF(); inputStream.close(); public class SingleFileWriteRead { public static void main(String[] args) { // 입력 파라미터 확인 if (args.length != 2) { System.err .println("Usage: SingleFileWriteRead <filename> <contents>"); System.exit(2); } try { // 파일 시스템 제어 객체 생성 Configuration conf = new Configuration(); FileSystem hdfs = FileSystem.get(conf); // 경로 체크 Path path = new Path(args[0]); if (hdfs.exists(path)) { hdfs.delete(path, true); } System.out.println("## inputString:" + inputString); } catch (Exception e) { e.printStackTrace(); } } } MAPREDUCE 42 Map Operation MAP: Input data <key, value> pair web 1 weed 1 green 1 web 1 sun 1 weed 1 moon 1 green 1 land Map Map … Data Collection: split 2 Split the data to Supply multiple processors …… Data Collection: split1 1 sun1 web part 1 moon weed 1 web 1 land green 1web green 1 part sun 1weed web … 1 1 web moon 1green weedKEY 1 VALUEgreen land 1sun green 1 … 1moon part sun 1 KEY1land web moon 1 green 1part land 1 … 1web part 1 green KEY VALUE web 1 … green 1 … 1 KEY VALUE KEY 1 1 1 1 1 1 1 1 1 1 1 1 VALUE 1 1 1 1 1 VALUE Data Collection: split n 43 Reduce Operation MAP: Input data <key, value> pair REDUCE: <key, value> pair <result> Map Data Collection: split n Map Reduce … Data Collection: split 2 Split the data to Supply multiple processors …… Data Collection: split1 Reduce Map Reduce 44 Large scale data splits Map <key, 1> Reducers (say, Count) Parse-hash Count P-0000 , count1 Parse-hash Count P-0001 , count2 Parse-hash Count Parse-hash P-0002 ,count3 45 MapReduce Example in my operating systems class Cat map combine reduce split map combine reduce split map combine reduce split map split part0 part1 Bat Dog Other Words (size: TByte) part2 46 MAPREDUCE PROGRAMMING MODEL 47 MapReduce programming model 1. Determine if the problem is parallelizable and solvable using MapReduce (ex: Is the data WORM?, large data set). 2. Design and implement solution as Mapper classes and Reducer class. 3. Compile the source code with hadoop core. 4. Package the code as jar executable. 5. Configure the application (job) as to the number of mappers and reducers (tasks), input and output streams 6. Load the data (or use it on previously available data) 7. Launch the job and monitor. 8. Check the result. 48 MapReduce Characteristics Very large scale data: peta, exa bytes Write once and read many data: allows for parallelism without mutexes Map and Reduce are the main operations: simple code There are other supporting operations such as combine and partition (out of the scope of this talk). All the map should be completed before reduce operation starts. Map and reduce operations are typically performed by the same physical processor. Number of map tasks and reduce tasks are configurable. Operations are provisioned near the data. Commodity hardware and storage. Runtime takes care of splitting and moving data for operations. Special distributed file system. Example: Hadoop Distributed File System and Hadoop Runtime. 49 Classes of problems “mapreducable” • Benchmark for comparing: Jim Gray’s challenge on dataintensive computing. Ex: “Sort” • Google uses it (we think) for wordcount, adwords, pagerank, indexing data. • Simple algorithms such as grep, text-indexing, reverse indexing • Bayesian classification: data mining domain • Facebook uses it for various operations: demographics • Financial services use it for analytics • Astronomy: Gaussian analysis for locating extra-terrestrial objects. • Expected to play a critical role in semantic web and web3.0 50 Scope of MapReduce Data size: small Pipelined Instruction level Concurrent Thread level Service Object level Indexed File level Mega Block level Virtual System Level Data size: large 51 MapReduce WordCount Driver InputFormat JobClient RecordReader Mapper (MapRunner) Map Task Partitioner (Combiner) Reducer Reduce Task OutputFormat 일반적으로 main 메쏘드에 MapReduce 를 수행하기 위한 driver 코드를 구현합니다. 여기서는 사용자가 커맨드 입력시에 input 과 output 으로 사용할 HDFS 디렉토리를 올바르게 지정했는지를 검사합니다. job 을 만들기 위해 먼저 JobConf 객체를 생성하고 여기에 Job 을 실행하기 위한 클래스를 등록합니다. Driver : JobConf • JobConf 객체에는 MapReduce 작업을 위한 다양한 설정값이 필요합니다. – Mapper/Reducer 로 사용될 클래스의 이름 – input/output 디렉토리 – 기타 옵션들 • 사용자가 지정하지 않은 옵션은 Hadoop 설정파일에 있는 값을 사용하게 됩니다. – core-site.xml, hdfs-site.xml, mapred-site.xml • Hadoop 설정파일에 없는 옵션은 하둡의 디폴트 값을 사용하게 됩니다. Job 에 적절한 이름을 붙입니다. 데이터를 읽을 input 디렉토리 or 파일과 최종 결과 파일들이 저장될 output 디렉토리를 설정합니다. Input Path(s) • FileInputFormat.setInputPath() 에 설정된 path 에 존재하는 모든 파일/디렉토리가 mapper 에 전달됩니다. – 예외 : period(.) 나 underscore(_) 로 시작되는 파일들은 제외 – Globbing 을 지원합니다. • ex) /2010/*/01/* • FileInputFormat.addInputPath() 를 이용하여 여러 Path 를 지정할 수 있습니다. • 특정 파일/디렉토리를 제외하기 위하여 PathFilter 를 구현하여 사용할 수 있습니다. InputFormat • 입력 데이터는 InputFormat 에 의해 가공되어 Mapper 로 전달됩니다. – JobConf 에 설정합니다(setInputFormat) – 입력 데이터를 다수의 InputSplit 으로 나눕니다. • 하나의 Mapper 는 하나의 InputSplit 을 처리합니다. • IputSplit 의 개수가 Map Task 의 개수가 됩니다. – InputSplit 을 읽어서 Key-Value 쌍을 만드는 RecordReader 를 생성합니다. – 디폴트는 TextInputFormat 입니다. • Key : LongWritable (파일 내에서의 offset 값) • value : Text (라인값) OutputFormat • Reducer 에서 가공, 생성된 Key-Value 쌍이 최종적으로 전달됩니다(일반적으로는 HDFS 에 저장) • FileOutputFormat.setOutputPath() 를 이용하여 저장 디렉토리를 지정합니다. • 저장 포맷을 임의로 지정할 수 있습니다. – JobConf 에 설정합니다(setOutputFormat()) – 디폴트는 TextOutputFormat 입니다. • K/V 가 tab 으로 구분된 Plain Text 파일 JobConf 에 Mapper 와 Reducer 로 사용할 클래스 이름을 설정합니다. 이때 Intermediate K/V 타입도 지정해야 합니다. 이 값들은 모두 concreate-class 를 사용해야 합니다. JobClient 의 runJob 메쏘드를 이용하여 실제 MapReduce 작업을 시작합니다. JobClient • 작업을 시작하는 데에는 두가지 방식이 있습니다. – JobClient.runJob() • 작업이 종료될 때 까지 대기합니다. – JobClient.submitJob() • 작업을 의뢰하고 바로 빠져 나옵니다. • JobClient 는 JobConf 의 내용을 참조하여 작업에 필요한 파일들을 생성하고 이들을 HDFS 에 올립니다. – jar 파일 – Job 수행을 위한 XML 파일 – InputFormat 을 이용하여 생성된 Input Split 파일 Mapper 클래스는 보통 편의상 MapReduceBase 클래스를 확장하며, Mapper 인터페이스를 구현해야 합니다. Mapper 인터페이스는 네가지 제네릭 타입을 필요로 하며 이는 인풋(InputFormat 에서 전달된 타입)과 아웃풋(Intermediate K/V 타입)에 대한 Key/Value 타입 입니다. 처음 두개가 인풋 K/V 타입이며 뒤의 두개가 아웃풋의 K/V 타입 입니다. 여기 나온 예제에서는 인풋타입의 키를 사용하지 않으므로 그냥 Object 를 사용했습니다. Mapper • Mapper 의 제네릭 파라메터는 인풋과 아웃풋의 K/V 타입을 정의합니다. – Key 는 WritableComparable 을 구현해야 합니다. – Value 는 Writable 만 구현하면 됩니다. • Writable – 데이터를 인풋 Mapper Reducer 아웃풋으로 옮길 때 serialization/deserialization 하는 방식을 정의합니다. – 최대한 compact 하게 구현합니다. map 함수 밖에 전역 변수로 두개의 객체를 생성하였습니다. 하나는 Text 이고 하나는 IntWritabel 입니다. 이는 매번 객체가 생성되는 오버헤드를 줄이기 위한 것 입니다. map 메쏘드의 시그너쳐는 위와 같습니다. 하나의 KV 쌍과 OutputCollector/Reporter 가 전달됩니다. OutputCollector 에는 제네릭으로 사용자가 생성해야 하는 intermediate KV 타입이 지정되어 있습니다. map 메쏘드에 내에서 InputFormat 에서 전달된 text line 을 java 의 StringTokenizer 를 이용하여 각각의 단어로 나눕니다. 생성된 Key-Value 쌍은 OutputCollector 의 collect 메쏘드를 이용하여 다음 단계로 전달됩니다. 이때 Key 는 항상 WritableComparable 을 구현한 객체여야 합니다. 예제에서 Key 는 단어가 되고 Value 는 1 이라는 값이 됩니다. 전 화면에서 StringTokenizer 를 통해 생성된 단어값들을 전역 변수로 선언된 Text 내에 저장하고 1 이라는 Value 값도 마찬가지로 IntWritable 내에 저장하여 OutputCollector 로 넘깁니다. Reporter • 이번 예제에서는 Reporter 를 사용하지 않았습니다. • Reporter 는 driver 코드에 특정 정보(status/counter) 를 전달하는데 사용할 수 있습니다. – status : setStatus 메쏘드를 이용하며 현재 Task 의 상태를 나타내는 문자열을 지정하여 외부에서 볼 수 있게 합니다. – counter : 특정한 조건에 대한 counter(long) 값을 증가시켜 Job 이 끝난 후 cumulation 된 결과를 볼 수 있게 합니다. – progress : 시간이 많이 걸리는 작업을 하는 경우 TaskTracker 에게 ping 신호를 보내 작업 진행 중임을 알립니다. • Reporter 는 Mapper 가 수행하고 있는 Input Split 에 대한 Reducer 클래스는 보통 편의상 MapReduceBase 클래스를 확장하며, Reducer 인터페이스를 구현해야 합니다. Reducer 인터페이스는 네가지 제네릭 타입을 필요로 하며 이는 인풋(Intermediate K/V 타입)과 아웃풋(OutputFormat 에 정의된 타입)에 대한 Key/Value 타입 입니다. 처음 두개가 인풋 K/V 타입이며 뒤의 두개가 아웃풋의 K/V 타입 입니다. Key 타입은 모두 WritableComparable 을 구현해야 하며 Value 는 Writable 을 구현해야 합니다. 이전 mapper 에서 설명 했듯이 효율성을 위하여 IntWritable 을 생성하여 전역 변수로 선언합니다. reduce 메쏘드는 Key와 동일한 키에 해당하는 Value 들의 iterator 를 인자로 받습니다. 또한 이와 동시에 OutputCollector 와 Reporter 를 전달받습니다. Iterator 의 hasNext() 와 next() 메쏘드를 이용하여 Key 에 해당하는 모든 Value 들을 가져올 수 있다. 예제에서는 단어에 해당하는 count 값을 모두 합산하게 된다. 결과값을 OutputCollector 의 collect 메쏘드를 이용하여 Key-Value 쌍을 OutputFormat 으로 전달한다. 예제의 경우 단어가 나온 총 횟수가 되며 이를 text 파일로 저장하게 된다. Combiner • Mapper 는 일반적으로 많은 양의 중간 데이터를 생성합니다. – 중간 데이터는 네트워크를 경유하여 Reducer 로 전달됩니다. – 이는 많은 네트워크 트래픽을 유발합니다. • Combiner 를 사용하여 중간 데이터를 줄일 수 있는 경우가 있습니다. – “mini-Reducer” 라고 할 수 있습니다. – 하나의 Mapper 에서 생성된 결과에 대해서 (각각) 적용됩니다. – Combiner 를 통해 처리된 결과가 Reducer 로 전달됩니다. • Combiner 와 Reducer 는 보통 동일한 코드가 사용됩니다. – Input(intermediate) KV 타입과 Output KV 타입이 동일해야 합니다. Driver : Combiner Applied public class WordCount { public static void main(String[] args) throws Exception { if (args.length != 2) { System.out.println("usage: [input] [output]"); System.exit(-1); } JobConf conf = new JobConf(WordCount.class); conf.setJobName("WordCount"); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); conf.setMapperClass(WordMapper.class); conf.setMapOutputKeyClass(Text.class); conf.setMapOutputValueClass(IntWritable.class); conf.setCombinerClass(SumReducer.class); conf.setReducerClass(SumReducer.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); JobClient.runJob(conf); } } Word Count 1 Word Count 1 Top N Top N Top N Top N Top N Word Count 2 Word Count 2 MapReduce Job running on Cluster • In Eclipse, Create conf directory – Project new folder – Create mapred-site.xml in conf 91 Excercise • Add Case Sensitive function to your wordcount job. • Implement Mapper/Reducer separate class, run the MapReduce Job in eclipse and command line. 92