Hadoop

Hadoop 2015. 2. 26. 14:15

Hadoop : MapReduce parallelDB 장점을 모두 지님

               (DB가 스키마onWrite이라면, 하둡은 스키마onRead 이다)

  • HDFS : Data Centric Computing - 데이터 사이즈가 크므로 데이터 있는 곳으로 이동해서 계산함

         : write-Once, read-many,   noUpdate-but-Append.
         :
디폴트는 3개의 replica.(다른 racki) - client 가까운데서 읽음.

         : metaData (NameNode=Master라고 부르며- single관리되므로 중요..) 모두 in-Memory.
         :  dataNode=Slave(
들도 각자의 metaData 보관함.)

-디폴트 128Mega block들로 구성

- CRC32체크로 분산데이타체크함.

- 512byte단위로 checksum관리해서 매번 체크함

 

          ?secodary Name Node?



   - Map & Reduce  utubeREF - 카드로설명

                 : Map-데이터 있는 곳으로 프로그램이 가서 동작하는 개념.

                 : Reduce-계산이 끝나면 다시 분리




youtube소개  REF: 25petaByte까지 저장가능, 4500개 머신까지 동작가능.

                     Pig - 컴파일러

Hive - SQL유사 I/F

HBase - top level apache project   -  메신저 메세지는 object형태로 저장가능 


HCatalog - 메타data서버 (Hive에서 분리되어 나옴)

                             



                      기타) Mahout - 머신 러닝 libray for MapReduce

                                Ambari, Galnglia, Nagios - cluster분석 툴

                                Sqoop - RDB와 I/F 툴

Cascading - 트랜스레이팅 툴 for Pig..?

Oozie - 스케줄러. workflow 코디네이션.. 언제 실행할지 등.

Flume - 스트리밍 input for Hadoop

Protobuf, Avro, Thrift 를 지원. 

Fuse-DFS : os 레벨 access지원. 


      


Posted by yongary
,

가상화는 반가상화(para virtualization)과 전가상화(HVM)으로 나뉜다.

(추가적으로 type1:native,bare-metal 방식과 type2:hosted로 나누기도 하는데,

hostOS가 필요없는 type1: Xen, hostOS가 필요한 type2: KVM 이다 :  REF-NEW  REF-SITE )

 

REF-SITE2(AWS guide)


cloudStack + Xen으로 대표되는 반가상화 방식이 우수했으나, 내가 느낀 약간의 단점은

단점1. Xen의 네트웍 delay, 

단점2. fork시 시간지연 



최근 openstack + KVM의 전가상화가  이것을 극복하는 모습니다.


원래는 전가상화가 Mgmt에서 HW와 guestOS간의 바틀넥이 될 수 있으나,

KVM은 linux자체를 변형해서 만든 hypervisor인 만큼 이 문제가 적어 보인다.



openstack + KVM구성도:

(여기서 VM process는 QEMU 위에 올라가게 된다)




Posted by yongary
,

IMS Registration

IMS 2015. 2. 17. 11:05

단말이 IMS 시스템에서 서버에 등록을 하는 절차.

(VoLTE 통화를 위해서, 단말과 서버간의 사전 절차이다.

VoLTE는 데이타망과 유사한 통화전용LTE망  위에서 통화를 하는 것이므로, VoIP라고 볼 수도 있고,

기존의 CS망에서 통화하던게 발전한 것이므로 일반통화라고 볼 수도 있을 것 같은데.. 

아무래도 기본 통화로 상용되다 보니 VoIP라고 잘 부르진 않는다. )


 

1. 단말이 서버로 ID를 보낸다 (First Regi,  integrity_protected필드=no)


2. 서버(CSCF)에서 401 unAuthorized 응답을 보낸다


3. 단말이 401응답속의 nonce(challenge)필드 값을 이용해서 도전과제를 풀어서 올린다. (Second Regi, integrity_protected필드=yes)


4. 서버(CSCF)에서 200OK를 보낸다.




이 중에서 3번 항목을 살펴보면

단말의 SIM에는 PUID(고유ID: From필드에 사용), PRID(인증용 ID: userName 필드에사용) 및 key, ck(암호키), ik(변조체크 키) 가 있는데

3번의 과정에서는 ck,ik,nonce+ 이것들을 이용해서 계산된 결과가 올라간다.

서버는 이 결과가 원하는 답이 맞을 경우 Regi를 해 주게 된다.  



<인증 방식>

인증 방식에는 aka인증과 md5 인증이 있는데

요즘 단말들이 aka인지 md5인지를 결정하여 올려주는 관계로,  차이만 본다면


aka: 위에 언급한 것처럼 sim을 이용해서 인증.  nonce이용

md5: 좀 더 간단한 인증으로 nonce가 아니고 n-nonce 필드를 이용. 

Posted by yongary
,

javascript 상속

javascript 2015. 2. 4. 21:46

javascript에서의 상속은 일반적인 OO와 다르다.

그 이유는 javascript가 OO 언어가 아니고, 함수(prototype)기반 언어라서 그러하다.


대신, prototype과  prototype.constructor를 치환하는 방법으로 상속이 구현 가능하다.



<<예제>>

    function AjaxBasic(){

        if ( window.XMLHttpRequest){

            this.xhr = new XMLHttpRequest();

        }else{

            console.log("NO XHR support maybe ~ IE6");

            return;

        }

        this.xhr.onreadystatechange=function(){

            if (ajaxObj.xhr.readyState==4 && ajaxObj.xhr.status==200)

                document.body.innerHTML=ajaxObj.xhr.responseText;

        }

        //// method..  run()

        this.run = function(){ 

            this.xhr.open("GET", "test_data.txt", true);

            this.xhr.send();

        }

    }


    function MyAjax(){

        this.run = function(fileUrl){

            ajaxObj.xhr.open("GET", fileUrl, true);

            ajaxObj.xhr.send();

        }

    }



   ///Inherit =  prototype + constructor

    MyAjax.prototype = new AjaxBasic();

    MyAjax.prototype.constructor = MyAjax();


Posted by yongary
,

ajax

javascript 2015. 2. 4. 21:31

간단한 ajax .


function makeRequest(url)
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);  //true is A of Ajax=Async
    xhr.onreadystatechange = receiveResponse;
    xhr.send();
}
function receiveResponse(e)
{
    if (this.readyState == 4) //4:complete
    {
        if (this.status == 200) //200 ok
        {
            var response = this.responseXML;
            ...
        }
    }
}


웹페이지 버튼 콜백 ajax ( JQuery 경우)  - 아래에서 CDATA는 없어도 됨. 

<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
$(function () {
$('.clear-cache').click(function () {
$.ajax({
type: "POST",
url: "/api/internal/v1/clear_cache/banner",
success: function () {
$('#clearCacheModal').modal('show');
}
});
});
});
/*]]>*/
</script>


Posted by yongary
,

ForkJoinPool 과  ThreadPoolExecutor 이 대표적으로 ExecutorService를 구현한 class 이다.



  => Executor는 여기참고 : 참고2   참고사이트

     Executor<-ExecutorService관계이며,  Excutor가 Runnable를 실행하고,  ExecutorService 에서  shutdown등으로 관리가능.

     
    (이렇게 Factory 형태로도 많이 쓰인다)  

     ExecutorService pool Executors(유틸).newFixedThreadPool (thread num)  returns ExecutorSerivce.

                                             => newFixedThreadPool을 이용한 서버소켓 accept 예제.

     pool.execute ( request ); //Executor   REF

     pool.shutdown() or submit() or blabla; //ExecutorService


    ==> 참고2 사이트: pool.submit (Callable )으로 실행되지만, 실제 Callable.call이 언제실행될지 모르므로
          Executor은 Future를 리턴.   future . get()  : (blocking임)으로 값가져 옴. 


=============ForkJoin Pool==========

ForkJoinPool에 RecursiveAction구현 객체를 invoke 하면


객체의 compute 함수가 실행되면서

compute 내에 구현된 InvokeAll(work1,work2)를 통해 멀티코어를 실행하게 된다.




<<<    Factorial을 이용한 ForkJoinPool 예제 >>


public class TestPool {


public static void main(String[] args){

ForkJoinPool pool = new ForkJoinPool();

long time1 = System.currentTimeMillis();

for(int i=0; i<500000;i++){

MyWork myWork = new MyWork(25);  //25factorial

pool.invoke(myWork);

}

long time2 = System.currentTimeMillis();

System.out.println("Elapse:" + (time2-time1));

}

}


class MyWork extends RecursiveAction{  

int base=0;

int to=1;

long result=1;

//factorial

public MyWork(int base){

this.base = base;

}

//half factorial

public MyWork(int base, int to){

this.base = base;

this.to = to;

}

@Override

protected void compute() {

//////small value Calculate and return

if ( base-to <= 2 ){

System.out.println("END: base,to:" + base +","+to);

for ( int i=base; i >= to; i-- )

result = result*i;

return;

}


       //////large value DIVIDE as 2 works.///////////////

int median = to+ (base-to)/2;

MyWork w1 = new MyWork(base, median+1);

MyWork w2 = new MyWork(median, to);

invokeAll( w1, w2);  //waiting....  then why USE RecursiveTask(which resturns VALUE)

result = w1.result * w2.result;

System.out.println("FINAL RESULT:" + result);

}

}



Posted by yongary
,

<JDK 1.4>


(Selectable)Channel 

    has

Selector

    has

SelectionKey  인데  Selector를 서버채널과 클라이언트 채널에 동시에 등록해 accept와 read동시 수행 가능.




<JDK1.6 >의 

 java.nio.channels.SelectorProvider 는 linux시스템의 epoll을 구현.   select=O(n),  epoll=O(1)

    nio = non-blocking io 임. 


=========Selector 예제===== 서버 thread=====

//nio version

public void run(){

ServerSocketChannel ssc=null;

try{

        //for SSC

InetSocketAddress addr = new InetSocketAddress(1990);

ssc = ServerSocketChannel.open();

ssc.socket().bind(addr);

//for Selector

Selector selector=Selector.open();

ssc.configureBlocking(false); //make nonBlocking accept()

ssc.register(selector, SelectionKey.OP_ACCEPT);

while (true){ //select for accept While

int numKeys = selector.select(); //select is non Blocking.

if (numKeys > 0){

//System.out.print(" numKeys:" + numKeys); //too much call

Set<SelectionKey> keySet = selector.selectedKeys(); /// Must be selectedKeys.

Iterator<SelectionKey> it = keySet.iterator();

while( it.hasNext()) {

  SelectionKey key = it.next();

  if( (key.readyOps() & SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT){


SocketChannel csc = ((ServerSocketChannel) key.channel()).accept();

csc.configureBlocking(false);

System.out.println("    [Server] Client Connected ------"+csc);

//read Key register

csc.register(selector,  SelectionKey.OP_READ);

it.remove();//delete key

  }else if( (key.readyOps() & SelectionKey.OP_READ)==SelectionKey.OP_READ){

SocketChannel csc =  (SocketChannel) key.channel();

//System.out.println("    [Server]  Client READ Event ------"+csc);

readFromClient(csc);

it.remove();//delete key

     }

           }

         }

        Thread.sleep(10);

       } //while

}catch (Exception e){

    e.printStackTrace();

}finally{

      try{ 

           if(ssc!=null) ssc.close(); 

      }catch (IOException e){}

       }

}//run

Posted by yongary
,

Generics: - casting으로부터의 해방.

List<String>, 

List<?>  ?: any type extends Object

Class<?>  :  (Object).getClass()로 리턴되는 특정 class의 정보 집합.

 

JMX도 추가. (JMX등 JEE 참고사이트 )


java.util.Concurrent

 - Executor가 대표적: 멀티코어 활용.

   그러나, 일반적인 thread프로그래밍 만으로도 (green thread = single thread OS)가

   아닌 이상은 멀티코어가 어느정도 적용된다고 함.



그 외

http://skycris.tistory.com/3   1.5에 추가된

boxing/unboxing,   - int(원시 형)과  Integer간 자동 형변환.

static import, 

annotation 설명

Posted by yongary
,

nio (jdk1.4)

java core 2015. 1. 16. 15:23

레퍼런스:  http://javacan.tistory.com/tag/nio



속도가 향상된 nio(new io)는 기존 java라기 보단 c코드라고 봐야할 것 같다.


DirectBuffer가 속도가 빠르고, IndirectBuffer는 임시용.

Buffer는 보통 Channel(c언어로 된 Stream이라고 보면 될듯) 과 함께 써야 함.



  ByteBuffer buf = ByteBuffer.allocateDirect(8); 

    buf.putByte( (byte)0xAB );

    buf.putShort( (short)0xCDEF ); 


이렇게 하면, buf에 position=3,  limit=8=capacity 이 됨.

buf.rewind : p=0.

buf.clear() :  p=0, l=8 (초기상태)

buf.flip()    :  p=0, limit=3(현재위치)


뭔가 write한 후에는 남은 byte를 맨 앞으로 옮겨주는

buf.compact() 필요.  주로 buf.isRemaining()과 함께 쓰이는 듯.



<<실제 예제>> 

    FileChannel inputChannel = null;

    FileChannel outputChannel = null;

    try {

        FileIntputStream is = new FileInputStream(source);

        FileOutputStream out = new FileOutputStream(dest);

        inputChannel = is.getChannel();

        outputChannel = out.getChannel();        


    } catch(IOException ex) {



    ByteBuffer buffer = ByteBuffer.allocateDirect(512);

    int len ;

    while ( (len = inputChannel.read(buffer)) != -1) {

         buffer.flip(); //뒤쪽 limit을 마킹. 즉 limit=position,  position=0이 됨


        outputChannel.write(buffer); //읽은거 그대로 write.

        buffer.clear(); //p=0, limit=512가 됨.

    }




<<짧은 파일을  RandomAccess -> MappedByteBuffer (Direct임) 로 매핑해서.. 파일의 내용을 꺼꾸로 하기..>>




            RandomAccessFile ra = new RandomAccessFile("/hello.txt","rw"); 

            FileChannel fc = ra.getChannel(); 

                     

            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0, ra.length()); 


   int len = ra.length();


            RandomAccessFile ra = new RandomAccessFile("/hello.txt","rw"); 

            FileChannel fc = ra.getChannel(); 

                        

            //파일을 파일 채널을 이용하여 버퍼에 매핑 합니다.                        

            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0, ra.length()); 

            

            int len2 = (int)ra.length(); 

            

            //파일 자체 내용을 뒤집기 

            for (int i = 0, j = len2 - 1; i < j; i++, j--) 

            { 

                byte b = mbb.get(i); 

                mbb.put(i, mbb.get(j));  //파일의 내용을 순서 바꿉니다. 

                mbb.put(j, b); 

            } 

                        

            fc.close(); 

Posted by yongary
,

Maven run

Spring 2015. 1. 15. 10:07


pom.xml을 이용해서 직접 run하는 command:



컴파일 + 실행:


    mvn compile exec:java -Dexec.mainClass=com.mongodb.SparkHomework




?아래는 jetty 실행.

mvn clean jetty:run


Posted by yongary
,