기본 콘텐츠로 건너뛰기

탄력받은 김에 socketcluster 호스팅 서비스인 baasil.io 도 써보았다.

한달 무료 플랜이 있어서 광속가입.
나는야 시스템 어드민이기 때문에 유저따윈 얼마든지 만들 수 있다.

철자가 좀 헷깔린다. baasil.io다. 다소 웹페이지가 엉성한 느낌은 있다.
이런건 망하기 전에 잽싸게 빨대 꽂는 것이 인지상정.

아마도 대부분 유료를 겁내고 자신의 계정이 한달짜리 트라이얼로 소모되는게 아까우실거라고 생각하여 대신 가입해봄 -_-)v

가입 후 Email validation을 하고 나면
어서와. 소켓클러스터는 처음이지?

매우매우매우 심플하다.
Baasil.io manages your real-time infrastructure for you without compromising on flexibility. We provide you with a highly scalable, open source boilerplate (SCC) which you can modify as you like and then deploy to your own Kubernetes environment/cluster using a single command. The boilerplate we provide is designed to scale seamlessly across up to 1000 machines/hosts.
For the standard plan, Baasil.io gives you an isolated environment on a shared Rancher control panel. This setup is ideal if you have a relatively small number of machines (e.g. 1 to 20 hosts in your cluster) and are happy to look after your cluster using Rancher. If you would like to support more than 20 machines, want a completely hands-off experience when it comes to your infrastructure, or want your own dedicated Rancher control panel - We can make it happen with our flexible enterprise plan. If you would like to updgrade to the enterprise plan, you can contact us here.
You need to link your Baasil.io account to a valid GitHub account here before you can create your Rancher environment/cluster.
라고 한다.
Rancher라는 걸 쓰려면 깃허브 계정과 연동하라고 하는데 일단 패스
Try It을 보니
서비스키!! 키를 내놓으라!

오호. 서비스 키라는 걸 제공. 클라이언트 사이드에서 사용할 수 있다.
근데 크롬에서 개발자 콘솔 여는 단축키는 Cmd + Shift + J on OSX 아니야. Cmd + Option + J 라구!
<script src="https://baasil.io/socketcluster.js"></script>
요렇게 클라이언트에 붙이고
var socket = socketCluster.connect({
    query: {
      serviceKey: '섭수키:main'
    },
    channelPrefix: '섭수키:main#',
    hostname: 'service.baasil.io',
    port: 443,
    secure: true
  });
이렇게 접속해서

Subscribe
var myChannel = socket.subscribe('my-channel-name');
Watch
myChannel.watch(function (data) {
    // Handle incoming channel data here. You can set up multiple watchers per channel.
    console.log('myChannel data:', data);
  });
Unwatch
// The handler argument is optional (a function) - If not provided, it will unbind all watchers.
  myChannel.unwatch(handler);
Publish
myChannel.publish({foo: 'This is some JSON data'}, function (err) {
    // Callback to indicate whether or not publish was successful.
  });
Unsubscribe

myChannel.unsubscribe();
Check channel subscription state

myChannel.state // Can be 'unsubscribed', 'subscribed' or 'pending'
Check socket connection state
socket.state // Can be 'open', 'connecting' or 'closed'
Other useful operations...
Get array of watchers
// Get array of functions which are watching that channel.
  myChannel.watchers();
Subscribe again...
// Subscribe to a channel which was previously unsubscribed.
  myChannel.subscribe();
Get channel reference from socket
// This will not create any new subscriptions - Just get a channel reference.
  var myChannel = socket.channel('my-channel-name');
Get list of all subscribed channels
// Returns an array of channel names which are currently subscribed.
  // If the second argument is true, it will include channels which are pending subscription.
  socket.subscriptions('my-channel-name', true);
꿀팁을 마구 대방출.
뭐 이것만 알면 되겠네.
세상 참 좋구만.

그 다음은 https://docs.baasil.io/ 를 보고 CLI 도 설치해본다.
npm install -g baasil
설치 끗.
하나 만들어 봐야지. 그전에 docker가 있어야 하니 꼭 체크하고.
baasil create jwaujijangjiji 
해보니
Creating app structure...
[Success] Baasil.io app '/Users/spectrum/Documents/js/_app/jwaujijangjiji' was setup successfully.
끗.
node.js 가 그렇지 뭐;
실행해보자.
$ cd jwaujijangjiji
$ baasil run
Unable to find image 'socketcluster/socketcluster:v5.1.2' locally
v5.1.2: Pulling from socketcluster/socketcluster
5c90d4a2d1a8: Pull complete
ab30c63719b1: Pull complete
29d0bc1e8c52: Pull complete
f222342d2902: Pull complete
27808f091869: Pull complete
a5f3825caa0a: Pull complete
Digest: sha256:d466ab21339117e03aad3f97583cdb3320a4520f3d515f8dd6c1bfd19dba1c75
Status: Downloaded newer image for socketcluster/socketcluster:v5.1.2
2c597396d46e4c60348b5abfea8bc95bf099b1be0f9c9313c21859ff386d481e
[Success] App 'baasil01' is running at http://localhost:8000
docker 리파지터리에서 socketcluster 이미지를 땡겨온 다음 8000로 실행한다.
아주 좋아!
baasil --help
Usage: baasil [options] [command]
Options:
  -v            Get the version of the current Baasil.io installation
  --help        Get info on how to use this command
  --force       Force all necessary directory modifications without prompts
Commands:
  create <app-name>             Create a new boilerplate SCC app in working directory
  run <path>                    Run app at path inside container on your local machine
  restart <app-path-or-name>    Restart an app with the specified name
  stop <app-path-or-name>       Stop an app with the specified name
  list                          List all running Docker containers on your local machine
  logs <app-path-or-name>       Get logs for the app with the specified name
  deploy <app-path>             Deploy app at path to your Baasil.io cluster
  deploy-update <app-path>      Deploy update to app which was previously deployed
  undeploy <app-path>           Shutdown all core app services running on your cluster
맨드 라인 내용을 보니 대략 이렇다.
필요한 것만 딱 들어있네.
공통인 부분은 죄다 제외하고 서버 사이드엔 worker.js 와 package.json 나머지 client는 public안에 다 몰아놓았다.
안그래도 간단한데 더욱 간단하다.
docker와 kurbernate가 세상을 정말 많이 바꿨구나. 이젠 이런게 아무렇지도 않군.

다짜고짜 deploy 때려보자.
dockerhub 계정을 요구한다.
만들어만들어~
$ baasil deploy
? Enter your DockerHub username: bsio20161210
? Enter your DockerHub password: *********
? Enter the number of workers for each SocketCluster instance (Default: 1): 4
? Enter the number of brokers for each SocketCluster instance (Default: 1):
? Enter the Docker image name without the version tag (Or press enter for default: bsio20161210/
baasil01):
? Enter the Docker version tag for this deployment (Default: v1.0.0):
Sending build context to Docker daemon 228.9 kB
Step 1 : FROM node:6.3.0-slim
6.3.0-slim: Pulling from library/node

worker는 4개!
[Error] Failed to deploy the 'baasil01' app. Command failed: kubectl create -f /Users/spectrum/Documents/js/_app/csjBootstrap/baasil01/kubernetes/scc-broker-deployment.yaml
실패한다.
쩝, github 연동 먼저 해야지.

https://baasil.io/#!/dashboard?main-tab=account 에서 github account 넣어주고
https://baasil.io/#!/dashboard?main-tab=infrastructure 로 돌아오면 Rancher 생성이 활성화 된다.

TADA!
지금부터 대쉬보드인가!
생성생성

좋다. host 생성하자.
이것저것 눌러보자. 음... 잘만들었네.
EC2나 Azure는 쓰지 않는다. Custom으로 ㄱ

잘모르니까 디폴트.
5번에 Copy, paste, and run the command below to register the host with Rancher: 부분 아래에 있는 명령을 복사해서 터미널에 붙여넣자.

Unable to find image 'rancher/agent:v1.0.2' locally
v1.0.2: Pulling from rancher/agent
5a132a7e7af1: Pull complete 
fd2731e4c50c: Pull complete 
28a2f68d1120: Pull complete 
a3ed95caeb02: Pull complete 
7fa4fac65171: Pull complete 
33de63de5fdb: Pull complete 
d00b3b942272: Pull complete 
Digest: sha256:b0b532d1e891534779d0eb1a01a5717ebfff9ac024db4412ead87d834ba92544
Status: Downloaded newer image for rancher/agent:v1.0.2
5cc13082b79f9b58a488c456fdd1500de6b7f9450bd6ab42aa89517088c61336
docker: Error response from daemon: Mounts denied: 
The path /var/lib/rancher
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.
..
오류가 나는데
sudo docker run -d --privileged -v /var/run/docker.sock:/var/run/docker.sock -v /var/lib/rancher:/var/lib/rancher rancher/agent:v1.0.2 https://localhost:8000/v1/scripts/ㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌ:ㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌㅌ
ㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅉㅈ
이런식으로 주소를 localhost기준으로 바꿔주자. 디폴트는 8000번 포트.

아으 여기까지 해봤는데 지친다.
local로만 해보고 이미지 떠서 다른데 호스팅 하는게 낫겠어. 귀찮네.

#짐싸자


댓글

이 블로그의 인기 게시물

cURL로 cookie를 다루는 법

http://stackoverflow.com/questions/22252226/passport-local-strategy-and-curl 레거시 소스를 보다보면 인증 관련해서 cookie를 사용하는 경우가 있는데 가령 REST 서버인 경우 curl -H "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" 이렇게 로그인이 성공이 했더라도 curl -H "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이런 식으로 했을 때 쿠키를 사용한다면 당연히 인증 오류가 날 것이다. curl의 --cookie-jar 와 --cookie 옵션을 사용해서 cookie를 저장하고 꺼내쓰자. 각각 옵션 뒤엔 저장하고 꺼내쓸 파일이름을 임의로 지정하면 된다. 위의 과정을 다시 수정해서 적용하면 curl -H --cookie-jar jarfile "Content-Type: application/json" -X POST -d '{"email": "aaa@bbb.com", "pw": "cccc"}' "http://localhost/login" curl -H --cookie jarfile "Content-Type: application/json" -X GET -d '' "http://localhost/accounts/" 이렇게 사용하면

MQTT Broker Mosquitto 설치 후 설정

우분투 기준 $ sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa $ sudo apt-get update 하고 $ sudo apt-get install mosquitto 으로 설치하면 서비스까지 착실하게 올라간다. 설치는 간단한데 사용자를 만들어야한다. /etc/mosquitto/mosquitto.conf 파일에서 권한 설정을 변경하자. allow_anonymous false 를 추가해서 아무나 못들어오게 하자. $ service mosquitto restart 서비스를 재시작. 이제 사용자를 추가하자. mosquitto_passwd <암호파일 경로명> <사용자명> 하면 쉽게 만들 수 있다. # mosquitto_passwd /etc/mosquitto/passwd admin Password:  Reenter password:  암호 넣어준다. 두번 넣어준다. 이제 MQTT 약을 열심히 팔아서 Broker 사글세방 임대업을 하자.

MQTT 접속해제 - LWT(Last will and testament)

통신에서 중요하지만 구현이 까다로운 문제로 "상대방이 예상치 못한 상황으로 인하여 접속이 끊어졌을때"의 처리가 있다. 이것이 까다로운 이유는 상대방이 의도적으로 접속을 종료한 경우는 접속 종료 직전에 자신의 종료 여부를 알리고 나갈 수 있지만 프로그램 오류/네트웍 연결 강제 종료와 같은 의도치 않은 상황에선 자신의 종료를 알릴 수 있는 방법 자체가 없기 때문이다. 그래서 전통적 방식으로는 자신의 생존 여부를 계속 ping을 통해 서버가 물어보고 timeout 시간안에 pong이 안올 경우 서버에서 접속 종료를 인식하는 번거로운 방식을 취하는데 MQTT의 경우 subscribe 시점에서 자신이 접속 종료가 되었을 때 특정 topic으로 지정한 메시지를 보내도록 미리 설정할 수 있다. 이를 LWT(Last will and testament) 라고 한다. 선언을 먼저하고 브로커가 처리하게 하는 방식인 것이다. Last Will And Testament 라는 말 자체도 흥미롭다. 법률용어인데  http://www.investopedia.com/terms/l/last-will-and-testament.asp 대략 내가 죽으면 뒷산 xx평은 작은 아들에게 물려주고 어쩌고 하는 상속 문서 같은 내용이다. 즉, 내가 죽었을(연결이 끊어졌을) 때에 변호사(MQTT Broker - ex. mosquitto/mosca/rabbitMQ등)로 하여금 나의 유언(메시지)를 상속자(해당 토픽에 가입한 subscriber)에게 전달한다라는 의미가 된다. MQTT Client 가 있다면 한번 실습해보자. 여러가지가 있겠지만 다른 글에서처럼  https://www.npmjs.com/package/mqtt  을 사용하도록 한다. npm install mqtt --save 로 설치해도 되고 내 경우는 자주 사용하는 편이어서 npm install -g mqtt 로 전역설치를 했다. 호스트는 무료 제공하고 있는 test.mosquitto.org 를