'All Category'에 해당되는 글 500건

  1. 2015.04.14 gethostbyname
  2. 2015.04.13 c에서 c++파일 하나 불러쓰기
  3. 2015.04.09 원격 자동접속 shell script 및 SCP 1
  4. 2015.04.02 key
  5. 2015.04.02 closure
  6. 2015.04.01 eclipse js 환경
  7. 2015.03.31 HTML5
  8. 2015.03.30 native <-> web페이지간 연결
  9. 2015.03.30 android + phoneGap
  10. 2015.03.27 Scrum
  11. 2015.03.27 SIGINT 와 Trap
  12. 2015.03.27 Shared Memory
  13. 2015.03.18 screen 명령어, nohup명령어
  14. 2015.03.17 volatile 키워드 vs synchronized
  15. 2015.03.12 자동화 테스트 툴
  16. 2015.03.11 core 할당
  17. 2015.03.11 Shell script 예제.
  18. 2015.03.06 mongoDB 기본쿼리.
  19. 2015.02.28 hdfs 실행 및 report
  20. 2015.02.28 sudo apt-get, rpm
  21. 2015.02.26 Hadoop
  22. 2015.02.26 openstack + KVM 가상화
  23. 2015.02.17 IMS Registration
  24. 2015.02.04 javascript 상속
  25. 2015.02.04 ajax
  26. 2015.01.21 jdk1.7 Executor, fork/join
  27. 2015.01.16 nio (jdk1.4 ) Selector jdk1.6-SelectorProvider
  28. 2015.01.16 jdk1.5 제너릭, Concurrent, 어노테이션, enum, JMX
  29. 2015.01.16 nio (jdk1.4)
  30. 2015.01.15 Maven run

gethostbyname

Linux/Linux:c개발 2015. 4. 14. 09:46

<함수 prototype>

struct hostent *gethostbyname(const char *name);

int gethostbyname_r(const char *name,
               struct hostent *ret, char *buf, size_t buflen,
               struct hostent **result, int *h_errnop);


두 함수 모두 return type은 hostent  struct 이다.


<struct hostent 구조 >

struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */ 

==> 아래쪽에 in_addr구조체의 s_addr 변수 참조. 같은 형태임. 0xff01ffff의 네트웍바이트(순서대로) 형태(255.1.255.255)

} #define h_addr h_addr_list[0] /* for backward compatibility */ The members of the hostent structure are:


h_addrtype The type of address; always AF_INET or AF_INET6 at present. h_length The length of the address in bytes. h_addr_list An array of pointers to network addresses for the host (in net- HOST_NOT_FOUND The specified host is unknown. NO_ADDRESS or NO_DATA The requested name is valid but does not have an IP address. NO_RECOVERY A non-recoverable name server error occurred. TRY_AGAIN A temporary error occurred on an authoritative name server. Try again later.



<그 외 network관련 struct들 >

           struct sockaddr_in {
               sa_family_t    sin_family; /* address family: AF_INET */
               in_port_t      sin_port;   /* port in network byte order */
               struct in_addr sin_addr;   /* internet address */
           };

           /* Internet address. */
           struct in_addr {
               uint32_t       s_addr;     /* address in network byte order */  
           };

0xffffffff의 네트웍바이트 형태.=255.255.255.255


<in_addr_t  inet_addr(hostname) 함수> 이름을 0xffffffff (255.255.255.255 효과) 형태로 변환리턴.


리턴type:  typedef uint32_t in_addr_t;   

INADDR_NONE= -1 (255.255.255.255)을 리턴하는 경우. 약간문제가 될때도 있으나 거의 괜찮음.




Posted by yongary
,

c++하나를 불러쓰는 경우

 

wrapping layer를 만들어서,

c언어에서 불러쓰면 된다.

 

예) c++파일 안에서

 

extern "C" {

MyClass* myclass_new()

{

return new MyClass();

}

..몇개 함수 더 매핑.

}

이렇게만 하면,

main. c파일안에서 아래와 같이 호출이 가능하다.

 

struct MyClass *m = myclass_new();

 

 

 

그리고  build시에는 특히 c빌드시(혹은 최종 link시에)

gcc main.c -lstdc++  추가 필요....

 

 

 

참고 blog: http://ospace.tistory.com/215 

Posted by yongary
,

아주 유용하게 쓰고 있는 자동접속 script.

전문가가 ssh_stdin 을 개발해 주셔서, 이를 이용해 쓰고 있다.


===================================자동접속 + 작업 SCIRPT ==============

#!/bin/sh



PASSWD="myPasswd!"

curDir=$(pwd)

SSH_STDIN=$curDir/ssh_stdin

sshOption="-T -o StrictHostKeyChecking=no -o ConnectTimeout=1 -o NumberOfPasswordPrompts=1"



SVR_LIST="172.25.49.135 172.25.49.136"


mpList=$(eval echo $SVR_LIST)


for i in $mpList

        do


        echo "---------"$i

        echo $PASSWD | $SSH_STDIN ssh $sshOption "root@"$i "ps -ef|grep redis"

        echo $PASSWD | $SSH_STDIN ssh $sshOption "root@"$i "nstatus"

 

  #scp를 하고 싶을때는 ..  -T옵션 빼고.. $1에 파일이름 줘서.. 아래처럼. 하면 된다.

  echo $PASSWD | $SSH_STDIN scp $sshOption $1 "root@"$i":"$1

        done



=============================ssh_stdin내용=================================

#!/bin/bash


if [ -n "$SSH_ASKPASS_PASSWORD" ]; then

    cat <<< "$SSH_ASKPASS_PASSWORD"

elif [ $# -lt 1 ]; then

    echo "Usage: echo password | $0 <ssh command line options>" >&2

    exit 1

else


read SSH_ASKPASS_PASSWORD


export SSH_ASKPASS=$0

export SSH_ASKPASS_PASSWORD


[ "$DISPLAY" ] || export DISPLAY=dummydisplay:0


# use setsid to detach from tty

# exec setsid "$@" </dev/null

exec setsid "$@"

fi

Posted by yongary
,

key

javascript 2015. 4. 2. 23:07

<key event>

document.onkeydown=checkKey;

function checkKey(e){

  if(e.keyCode=='37'){  //left Key, 38:up, 39:right, 40:down

     alert('left');

  }

}



Posted by yongary
,

closure

javascript 2015. 4. 2. 09:39

클로져에 대해서 나름대로 정리해보면,

아래와 같은 함수에서 MyClass을 outter함수라고 부를때,

내부 함수 (gettitle)가  outter의 지역변수를 계속 사용할 수 있다는 개념.  

(javascript의 initialize비용이 비싸므로, closure를 이용해서 inner함수 안에서 if(!undefined) define을 할 수 있다.)

 ==> Point: 외부함수가 종료된 이후에도 사용할 수 있다.


var that=this 로 해서, this도 많이 사용한다고 한다. 이렇게 안하면 this가 전역변수인 window를 나타낼 수 있기 때문...



function MyClass(_title){

  var title=_title;

  return{   //json스타일 객체를 return.

     getTitle:function() { return title;},

  }

}


g=MyClass('ggg');

m=MyClass('mmm');


alert(g.geTtitle());   //m.getTilte()도 잘 동작.




참조: devbox

      Nonblock

Posted by yongary
,

eclipse js 환경

javascript 2015. 4. 1. 08:31

1. Web, OSGI  를 설치한다. (for Web,  install new software 에서)

  참고사이트: http://fishbear.tistory.com/2


2. JSDT 를 설치. (for JS,  eclipse marketplace 에서)

   - jsdt for jQuery 

   - angularJS eclipse(0.10.0?)

   - jsdt for ExtJS (1.7?)



속성 js Lib에서 jQuery등 추가하고..( ECMA, jQuery, ExtJS..)

$('head').   (점찍고 Ctrl+Enter로 확인)

Posted by yongary
,

HTML5

javascript 2015. 3. 31. 14:55

HTML5는 javascript의 확장판이라고 볼 수 있다.


이 중에서 쓸만한 것들을 나열해보면


1.Geolocation


2.Web Storage


3.IndexedDB + Object Store


4.Application Cache


5.WebSocket


6.File API


7.Drag & Drop 





그 외 5개+1는 천천히 알아보자

Server-Sent Event

Web Workers

WebGL

Selector API

Notifications API

Web SQL DataBase(2009년 중단된듯 )





Posted by yongary
,

1. Web에서 native 호출


 webView.addJavascriptInterface ( new MyNativeAPI(), "MyNativeAPI");


 class MyNativeAPI{

public String whoAmI() {

return "I am Yongary";

}

 }



2. native에서 웹호출

  webView.loadUrl("file://blabla");   //assets/www밑 파일

  webView.loadUrl("http://blabla");   // shouldOverrideUrlLoading 함수를 override해서 폰 default브라우저로 연동하는게 좋음

  webView.loadUrl("javascript:alert('I am from native')");

  

Posted by yongary
,

android + phoneGap

phoneGap 2015. 3. 30. 09:42

(그냥 android WebView를 이용해도 될 것 같은데.. 이부분은 좀 있다 확인하고..)


본 글은 andoid에서 phoneGap의 WebView를 추가하려면..



1. cordova.apache.org*을 다운받아서 android밑에 unzip

2. /framework/cordova-x.x.x.jar 를 만든다.  (  framework에서 run ant jar 하면 됨) 

3. .jar를 /libs 밑으로 복사



4. andoid 프로젝트에 /res/xml/main.xml 같은 layout 파일에 CordovaWebView 추가 


5. andoid 소스에 CordovaInterface implements 구현.




6. Camera이용시에  setActivityResultCallback(CordovaPlugin .. ) 및 startActivityForResult(CordovaPlugin.. ) 추가



7. ThreadPool 추가.  public ExecutorService getThreadPool()  ==> plugins이 thread를 가지기 위함.


8. /assets/www 밑에 HTML들 복사

9. /framework/res/xml 밑에 있는 config.xml을  프로젝트의 /res/xml 밑으로 복사 



원본 링크




Posted by yongary
,

Scrum

IT 2015. 3. 27. 17:21


위키kr :  Scrum(애자일 개발 프로세스)


- 매일15분씩 회의. (어제한일, 오늘한일, 장애상황)


- 스프린트 (한 주기) 관리  ( 30일 +- 1~4주)


- Sprint backlog

  다음 Sprint의 backlog도 미리 준비한다.



==========링크내용===================================

제품 책임자(Product Owner) 
제품 백 로그를 정의하여 우선순위를 정해 준다.

스크럼 마스터(ScrumMaster) 
프로젝트 관리자(코치)

스크럼 마스터는, 일반적인 관리를 수행하는 프로젝트 관리자들과는 달리 팀원을 코칭하고 프로젝트의 문제 상황을 해결하는 역할을 하며, 제품 책임자는 스프린트 목표와 백로그등의 결정에 있어 중심이 되는 상위 관리자로, 제품 책임자가 독단적으로 목표를 결정하지 않고, 고객과 관리자 및 팀원들이 모여서 목표를 정한다.

이런 과정을 거친 뒤, 개발 팀원들이 주도적으로 스프린트 목표를 달성하기 위한 작업을 정해 나가게 된다. 보통, 각 작업들은 4시간에서 16시간 정도 걸리도록 정한다. 물론, 작업을 정하고 할당하는데는 고객이나 제품 책임자와는 상관 없이 팀원 자율로 진행된다. 이와 같은 자율적인 행위를 통해서 팀원들은 의사를 활발하게 주고 받게 되고, 끈끈한 협업체계를 가지게 된다.

Posted by yongary
,

SIGINT 라고 가끔 본 적이 있을 것이다.

이 것은 Interrupt 시그널을 의미한다.



Interrupt (^c)     시그널은 2  

Quit     (^\)    시그널은 3

EOF(or Exit ^D)    시그널은 1


이 중에서 2,3번 시그널이 shell script가 도는 동안에 동작안하게 하고 싶으면..


trap "" 2 3    <- 이렇게 무시를 걸어 놓으면 된다.



trap 2 3 reset  <-shell script종료 후에는

Posted by yongary
,

Shared Memory

Linux/Linux:c개발 2015. 3. 27. 15:33

Linux  c개발시  shm 사용방법.


  shmget  : malloc 처럼 공유메모리 생성


  shmat   : 생성된 공유메모리를 해당 프로세서로 가져옴(첨부-attach)


  shmdt    :  가져온 메모리를 다시 반납. (분리-detach )


  



Posted by yongary
,

Linux를 하다보면, 터미널로 접속해서 프로세스를 실행시키고,

나중에 다시 접속해보면.. 죽어있는 경우가 있다.

- 백그라운드로 실행해도 그러하다..

 ( 백그라운드 실행은 명령어 뒤에 & 추가=>   $shell.sh &  )


이럴경우 

1. nohup으로 실행 :  $nohup shell.sh &


2. screen명령어로 실행.(화면까지 보존)


-------screen 사용법--------------

screen -S 스크린네임.


ctrl+a=>c생성


ctrl+a=>shift+a타이틀변경


ctrl+a=>shift+" 리스트


선택


ctrl+a=>c화면 클리어


ctrl+a=>d 나가기(리스트는 있고, 모드만 종료)


screen -r 모드진입(리스트 출력)


ctrl+a=>shift+" 리스트


ctrl+a=>shift+k 리스트선택 종료.



ctrl+a=>Shift+s 화면 분활 화면

ctrl+a=>tab 으로 화면  이동

ctrl+a=>shift+q 종료


ctr

Posted by yongary
,

volatile 키워드는 멀티thread시에 도움이 된다.

 1. 읽고 쓰기에 대한 원자성. ( byte단위의 원자화는 보장함. alignment는 맞춰줌. 

 2. 컴파일러의 임의 리오더링을 방지.



반면,

synchronized는 블록으로 묶인 부분 혹은 변수를 원자화(makes atomic ) 함.


<Wikipedia singleTon 예제>

public class SingletonDemo {

    private static volatile SingletonDemo instance = null;

    private SingletonDemo() {  } 

    public static SingletonDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonDemo.class){
                if (instance == null) {
                    instance = new SingletonDemo();
                }
            }
        }
        return instance;
    }

}


Posted by yongary
,

자동화 테스트 툴

IT 2015. 3. 12. 09:20

TDD : Test Driven Development

=> 웹 자동화 테스트툴- Sellinium.



BDD: Behavior Driven Development

=> Cucumber.

Posted by yongary
,

core 할당

Linux 2015. 3. 11. 14:40

멀티코어 linux에서 코어를 할당하는 방법:


taskset -pc {해당 process를 
기동할 core 번호} process-pid

) taskset -pc 0 {process-pid}




만약 cloud상의 VM상에서

이와 같이 특정 core에 할당한 후에는 해당 VM reboot하여야 하며

isolcpus 옵션grub.conf 파일에 추가되어서 VM이 생성되어야 한다. 


<grub.conf>

# grub.conf generated by anaconda
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE: You have a /boot partition. This means that
# all kernel and initrd paths are relative to /boot/, eg.
# root (hd0,0)
# kernel /vmlinuz-version ro root=/dev/mapper/VolGroup-lv_root
# initrd /initrd-[generic-]version.img
#boot=/dev/xvda
default=1
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.32-431.3.1.el6.x86_64)
root (hd0,0)
kernel /vmlinuz-2.6.32-431.3.1.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd /initramfs-2.6.32-431.3.1.el6.x86_64.img
title CentOS (2.6.32-358.14.1.el6.x86_64)
root (hd0,0)
kernel /vmlinuz-2.6.32-358.14.1.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd /initramfs-2.6.32-358.14.1.el6.x86_64.img
title CentOS (2.6.32-279.2.1.el6.x86_64)
root (hd0,0)
kernel /vmlinuz-2.6.32-279.2.1.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd /initramfs-2.6.32-279.2.1.el6.x86_64.img
title CentOS (2.6.32-279.el6.x86_64)
root (hd0,0)
kernel /vmlinuz-2.6.32-279.el6.x86_64 ro root=/dev/mapper/VolGroup-lv_root rd_NO_LUKS LANG=en_US.UTF-8 rd_NO_MD console=hvc0 KEYTABLE=us rd_LVM_LV=VolGroup/lv_swap SYSFONT=latarcyrheb-sun16 crashkernel=auto rd_LVM_LV=VolGroup/lv_root rd_NO_DM rhgb quiet isolcpus=0
initrd /initramfs-2.6.32-279.el6.x86_64.img

Posted by yongary
,

-F_ 없어도 됨(2210)

echo ${JOB_NAME} | awk -F_ '{print $3}' |xargs -I {} rm -rf /tmp/doxygen/{}; 

 

수많은 프로세스들 한방에 죽이기

ps -ef | grep 키워드 | awk '{print $2}' | xargs -I {} sudo kill {}

 

find . -name "*.js" -print  | xargs grep -n         keywordToFind

                   (filename)           (linenumber)   

 

Posted by yongary
,

$mongo 해서 client접속하면..

>show tables 


  //이 중에서  heart  category(테이블)을

  /user:"kim", pic:1, heart:20, date:'20140303'   이러한 테이블(category)로 가정.  (_id는 자동 삽입됨. _class도 간혹 자동삽입-코드일경우)



> db.heart.find()    -> 전체 record list.


> db.heart.find().sort( {pic:1} )    -> 전체 리스트를 pic필드로 asending 소팅.


> db.heart.find().limit(2)  -> 리스트 중 2개만 출력.   

                             =  db.heart.aggregate({ $limit:2 }) 


> db.heart.distinct("user")   ->  [ "kim", "lee" ]

> db.heart.distinct("user").length   ->   2



> db.heart.aggregate({     $group:{_id:"$pic"}      })  ->  pic필드를 기준으로 그루핑.  ({ => ([{ 이렇게 대괄호 추가가능.(이전버전인듯)


db.heart.aggregate({     $group:{ _id:"$pic", heartSum:{$sum:"$heart"} }      })  -> 각 그룹별로 heartSum산출.


   -->복합 aggregate

> db.heart.aggregate(    

{$group:{ _id:"$pic", heartSum:{$sum:"$heart"} }},

{$sort:{"hearts":1}},

{$limit:2}

)



//일반적인  Query .

db.inventory.find( { type: 'food', price: { $lt: 9.95 } } )



//aggregate에 Query  추가.

db.heart.aggregate(

bla.. bla..    ,

{ $match : { score : { $gt : 70, $lte : 90 } } }

)




///////spring-data-mongo에서 적용시에는

    AggregationOperation match = Aggregation.match(Criteria.where("service").is("EFT").and("source").is("MARKUP"));
    AggregationOperation group = Aggregation.group("card_acceptor").and("amount_sum").sum("amount").and("tran_count").count();
    Aggregation aggregation = newAggregation(match, group);
    AggregationResults<StoreSummary> result = this.mongoTemplate.aggregate(aggregation, "eft_transactions", StoreSummary.class);


Posted by yongary
,

hdfs 실행 및 report

Hadoop 2015. 2. 28. 20:34

<설치 후, 첫 실행. >

sudo /usr/local/hadoop-2.5.0/sbin/start-dfs.sh



<상태 check>

 $hdfs dfsadmin -report 



<웹브라우저에서 확인.>

http://localhost:50070/ 



<HDFS 명령어>

$hdfs dfs -ls /

$hdfs dfs -mkdir /myTest


$hdfs dfs -put test.txt /




<Hadoop 명령어>

$hadoop fs -mkdir /wordCount

$hadoop fs -copyFromLocal wordCount.jar /wordCount

$hadoop fs -ls  



$hadoop jar wordCount.jar wordCount[main class]  /wordCount[folder]  /wordCount/output  [out folder]




Posted by yongary
,

sudo apt-get, rpm

Linux 2015. 2. 28. 17:36

openssh-server를 설치하려고 하니..

    openssh-server : Depends: openssh-client (= 1:6.6p1-2ubuntu1)  이런 에러가 뜬다.


이런 경우 다음방식으로 client를 먼저 설치하면 된다.

sudo apt-get install openssh-client=1:6.6p1-2ubuntu1



그외 sudo apt-get 명령어는


sudo apt-get --reinstall install xx

sudo apt-get remove xx


설치된 놈 조회

/var/cache/apt/archives  여기서 ls로 검색.  ?

  안될때는.. 그냥 sudo  apt-cache search blabla  로...하면 됨.



java여러개 깔아서 하나 선택시에는 

 sudo update-alternatives --config java

 sudo update-alternatives --config javac   이렇게 2번.




<서버에서 조회>

sudo apt-cache search xx

sudo apt-cache show xx


(apt-get 이 잘 안될때는)

sudjo apt-get dist-upgrade : 서버목록 업그레이드

sudo apt-get update    : 목록 index update.

 


.deb 파일을 받아서 직접 설치하는 경우는

sudo dpkg -i *.deb   로 하면된다.   참고: http://egloos.zum.com/mcchae/v/10795420



 

<CentOS>에서는


일반적으로는 $yum install blabla로 하면된다.


rpm패키지 파일을 구했을때는 아래와 같이 한다.


rpm -qa | grep xx  정보조회

rpm -ivh xx.rpm  설치

rpm -e xx 제거


 

Posted by yongary
,

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
,