Fork me on GitHub 第 2 頁 | Jeff Yang

Regressor test with Skflow and Sklearn

Some regressor tests with skflow and sklearn

regressor.py

# -*- coding: utf-8 -*-
import pandas
import numpy as np
import matplotlib.pyplot as plt
from pylab import savefig
from sklearn import datasets, cross_validation, metrics
from sklearn import preprocessing

from sklearn.svm import SVR
from sklearn import ensemble
from sklearn.ensemble import RandomForestRegressor
import skflow
########################################################
# Set data
boston = datasets.load_boston()
X, y = boston.data, boston.target
# Split dataset into train / test
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y,
    test_size=0.1, random_state=42)
scaler = preprocessing.StandardScaler()
X_train = scaler.fit_transform(X_train)
########################################################
# Fit regression model
# 1. SVR 
regressor = SVR(kernel='rbf', C=1000, gamma='auto')
# 2. Gradient Boosting
"""
params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 1,
          'learning_rate': 0.01, 'loss': 'ls'}
regressor = ensemble.GradientBoostingRegressor(**params)
"""
# 3. Random Forest
"""
regressor = RandomForestRegressor(n_estimators=200, min_samples_split=1)
"""
# 4. DNN
"""
regressor = skflow.TensorFlowDNNRegressor(hidden_units=[10, 10, 10],
    steps=20000, learning_rate=0.01, batch_size=13)
"""        
########################################################
# Train and Predict
regressor.fit(X_train, y_train) 
score = metrics.mean_squared_error(regressor.predict(scaler.transform(X_test)), y_test)
X_ty = regressor.predict(X_train)
score1 = metrics.mean_squared_error(X_ty, y_train)

print('Test MSE: {0:f}'.format(score))
print('Train MSE: {0:f}'.format(score1))
########################################################
# Look at the results
"""    
fig,ax = plt.subplots()
ax.scatter(y_train, X_ty)
ax.plot([y_train.min(), y_train.max()], [y_train.min(), y_train.max()], 'k--', lw=4)
ax.set_xlabel('Measured')
ax.set_ylabel('Predicted')
plt.show()  
"""
"""        
savefig('result.png') 
"""
Look at the results

Data preprocessing
pw.csv from Data Set

Date,Time,Global_active_power,Global_reactive_power,Voltage,Global_intensity,Sub_metering_1,
Sub_metering_2,Sub_metering_3
16/12/2006,17:24:00,4.216,0.418,234.840,18.400,0.000,1.000,17.000

data = pandas.read_csv('pw.csv')
X = data[['Date','Time','Global_reactive_power','Voltage','Global_intensity','Sub_metering_1',
'Sub_metering_2','Sub_metering_3']]
y = data['Global_active_power']

D = (pandas.to_datetime(X["Date"], format="%d/%m/%Y"))
X["Month"] = D.apply(lambda x: x.month)
X = X.drop(["Date"], axis=1)

T = (pandas.to_datetime(X["Time"], format="%H:%M:%S"))
X["Hour"] = T.apply(lambda x: x.hour)
X = X.drop(["Time"], axis=1)

Access MySQL with Python

Scan all json files in folder and then update or insert into DB…

Usage

Update or Insert
python3 sm.py
Delete
python3 sm.py d TagID
Query
python3 sm.py q

Config.ini
[JSON_FILES_PATH]
Json_Files_Path = ./json_files/
[DB_CONFIG]
DB_Ip = 10.62.8.10
DB_Usr = root
DB_Pws = 1234
DB_Name = dbName
DB_Table = tableName

/json_files/xx.json
{
“t1”: [
{“TagID”: “th0”, “DevID”: “DevID0”, “ModelIdx”: “0”, “ModelType”: “device_name_0”},
{“TagID”: “th1”, “DevID”: “DevID1”, “ModelIdx”: “1”, “ModelType”: “device_name_1”}
],
“t2”: [
{“TagID”: “th2”, “DevID”: “DevID2”, “ModelIdx”: “2”, “ModelType”: “device_name_2”}
]
}

DB struct
dbName
tableName
TagID varchar(32) Primary Key
DevID varchar(32) Primary Key
ModelIdx int(3)
ModelType varchar(30)
ModelOrder tinyint(3)

sm.py

# -*- coding: utf-8 -*-
import MySQLdb as mdb
import json
import os
import sys
import configparser

SENSORS_MAPPING_PATH = "./json_files/"
DB_IP = '10.62.8.10'
DB_USR = 'root'
DB_PWS = '1234'
DB_NAME = 'dbName'
DB_TABLE = 'tableName'

def CheckDBPrimaryKey():
    con = mdb.connect(DB_IP, DB_USR, DB_PWS, DB_NAME);
    with con:
        cur = con.cursor() 
        cur.execute("""
        SELECT COUNT(1)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = '%s'
        AND TABLE_NAME = '%s'
        AND COLUMN_KEY = 'PRI';"""
        % (DB_NAME, DB_TABLE) )
        con.commit()
        if cur.fetchone()[0]:
            return True
    return False

def UpdateDB(tagID, devID, modelIdx, modelType):    
    con = mdb.connect(DB_IP, DB_USR, DB_PWS, DB_NAME);
    with con:
        cur = con.cursor()  
        cur.execute("""
        INSERT INTO %s (TagID, DevID, ModelIdx, ModelType) VALUES ('%s','%s','%s','%s')                                  
        ON DUPLICATE KEY UPDATE 
        ModelIdx = VALUES(ModelIdx), ModelType = VALUES(ModelType);"""  
        % (DB_TABLE, tagID, devID, modelIdx, modelType) )        
        con.commit()

def ParserFiles():
    files = os.listdir(SENSORS_MAPPING_PATH)
    files_json = [i for i in files if i.endswith('.json')]
    for fj in files_json:
        with open(os.path.join(SENSORS_MAPPING_PATH, fj) , 'r') as jsonData:
            d = json.load(jsonData)         
            for v in d.values():          
                for c in range(len(v)):
                    try:
                        if v[c]['TagID']!="" and v[c]['DevID']!="": 
                            UpdateDB(v[c]['TagID'],v[c]['DevID'],v[c]['ModelIdx'],v[c]['ModelType']) 
                        else:  
                            print('TagID or DevID is None')     
                    except KeyError:
                        print('I got a KeyError')
                        pass
                    except:
                        print('I got a Error') 

def DeleteDB(tagID, devID=None):    
    con = mdb.connect(DB_IP, DB_USR, DB_PWS, DB_NAME);
    with con:
        cur = con.cursor()   
        cur.execute("DELETE FROM  %s WHERE tagID = '%s'" % (DB_TABLE,tagID))
        con.commit() 
        print('Delete %s Finished !!!'%(tagID))

def QueryDB():  
    con = mdb.connect(DB_IP, DB_USR, DB_PWS, DB_NAME);
    with con:
        cur = con.cursor()  
        cur.execute("SELECT * FROM  %s" % (DB_TABLE))
        rows = cur.fetchall()
        for row in rows:
            print(row)

def Main(): 
    global SENSORS_MAPPING_PATH  
    global DB_IP  
    global DB_USR
    global DB_PWS
    global DB_NAME
    global DB_TABLE    
    config = configparser.ConfigParser()
    config.read('Config.ini')
    try:
        SENSORS_MAPPING_PATH = config.get('JSON_FILES_PATH', 'Json_Files_Path') 
        DB_IP = config.get('DB_CONFIG', 'DB_Ip')  
        DB_USR = config.get('DB_CONFIG', 'DB_Usr')
        DB_PWS = config.get('DB_CONFIG', 'DB_Pws')
        DB_NAME = config.get('DB_CONFIG', 'DB_Name')
        DB_TABLE = config.get('DB_CONFIG', 'DB_Table')         
        if len(sys.argv) < 2:
            if CheckDBPrimaryKey():
                ParserFiles()   
            else:
                print('ERROR!!! DB Primary Key NOT FOUND~~')
        else:
            if sys.argv[1] == 'd':         
                DeleteDB(sys.argv[2])           
            if sys.argv[1] == 'q':
                QueryDB()
    except:
        print('ERROR INI!!!' )

if __name__ == '__main__':
    Main()

Phase Stretch Transform

PST or Phase Stretch Transform is an operator that finds features in an image. PST takes an intensity image I as its input, and returns a binary image out of the same size as I, with 1’s where the function finds sharp transitions in I and 0’s elsewhere. https://en.wikipedia.org/wiki/Phase_stretch_transform
PST Source Code

Searched and found a python version of PST.
python PST
Try to run that. Results are as below:

LPF=0.21 , Morph_flag=False

LPF=0.21 , Morph_flag=False

LPF=0.08 , Morph_flag=True

LPF=0.08 , Morph_flag=True

Virtual android phones

Try to create virtual android phones on server.

Ref.: Virtual Smartphone over IP

Some android emulators:

  1. Android-x86
    http://www.android-x86.org/
  2. ARChon Custom Runtime
    http://archon-runtime.github.io/
  3. Official Android SDK Emulator w/HAXM
    http://developer.android.com/sdk/index.html
  4. Android on Intel Architecture
    https://01.org/android-ia
  5. ARC Welder
    https://developer.chrome.com/apps/getstarted_arc

Remote control

Linux Ubuntu 14.04 64bit

Prerequisite:

  1. Android-x86
  2. VirtualBox
  3. Python…

Steps

  1. download android-x86-5.1-rc1.iso
  2. dkpg -i virtualbox-5.0_5.0.12-104815-Ubuntu-trusty_amd64.deb
    Need to enable Intel VT-X or AMD-V in your bios configuration
  3. install android-x86 in virtualbox
  4. cotrol virtualbox on console
    Start VM
    If run as root:
  • sudo -u jeff -H VBoxManage startvm Android
    background mode
  • sudo -u jeff -H VBoxHeadless -s Android -v on -e “TCP/Ports=31000”
    Stop VM
  • sudo -u jeff -H VBoxManage startvm Android

*

finish install

Test

TCP socket

In android-x86 press Alt+F1 entry console mode
netcfg
check ip
ifconfig eth0 xx.xx.xx.xx netmask 255.255.255.0
Alt+F7 GUI mode

1, Server send a message -> Android VM app receive the message

Server
client.py

# -*- coding: utf-8 -*-
import socket 
def Main():
    host = '192.168.42.142'
    port = 10090         
    mySocket = socket.socket()
    mySocket.connect((host,port))        
    message = input(" -> ")         
    while message != 'e':
        mySocket.send(message.encode())            
        message = input(" -> ")                 
    mySocket.close() 
if __name__ == '__main__':
    Main()

Android VM app

SockerService.java

package com.example.user.myapplication;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketService extends IntentService {
    public static final String ACTION_MyIntentService = "com.example.user.myapplication.RESPONSE";
    public static final String ACTION_MyUpdate = "com.example.user.myapplication.UPDATE";
    public static final String EXTRA_KEY_IN = "EXTRA_IN";
    public static final String EXTRA_KEY_OUT = "EXTRA_OUT";
    public static final String EXTRA_KEY_UPDATE = "EXTRA_UPDATE";
    private Context context;
    private String name; 
    private int Port = 10090;
    private ServerSocket server_socket;
    private Socket socket;
    private InputStream in;
    private OutputStream out;
    private BufferedReader reader; 
    private String messgae = null;
    public SocketService() {
        super("SocketService");
        // TODO Auto-generated constructor stub
    }
    public SocketService(Context context, String name) {       
        super("SocketService");
        this.context = context;
        this.name = name;
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        while (true) {
            try {              
                socket = server_socket.accept(); 
                in = socket.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                messgae = reader.readLine();  
                Intent intentResponse = new Intent();
                intentResponse.setAction(ACTION_MyIntentService);
                intentResponse.addCategory(Intent.CATEGORY_DEFAULT);
                intentResponse.putExtra(EXTRA_KEY_OUT, messgae.toString());
                sendBroadcast(intentResponse);
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("service exception", e.getMessage());
            }
        }
    } 
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        try {
            server_socket = new ServerSocket(Port); 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace(); 
        }
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.user.myapplication" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".SocketService" >
        </service>
    </application>
</manifest>

*

run

2, Android VM send a message once finishing satrt -> Server receive the message

~ TODO ~

Use simple-web-vnc

First, get the application window name.

$ xwininfo -root -tree | grep VirtualBox
0x4000001 “VirtualBox”: (“VirtualBox” “VirtualBox”) 10x10+10+10 +10+10
0x1a0000c “Oracle VM VirtualBox Manager”: (“VirtualBox” “VirtualBox”) 975x513+0+0 +765+196
0x420000c “Android [Running] - Oracle VM VirtualBox”: (“VirtualBox” “VirtualBox”) 800x622+0+0 +238+176

Modify code in Simple-web-vnc
server.go

func (conn *connection) appStreaming() { 
    windowName :=  "Android [Running] - Oracle VM VirtualBox" 
    wn := C.CString(windowName)
    conn.appHandle = C.app_create(1024, 0,0, 800, 600, wn);
    ...
}

Notice: Mouse position mapping still has some problems between Android VM and canvas !!!

Demo

Simple web vnc

Try to create a low latency web vnc (no concern network conditions).

It captures the screen or a application window based on Linux (X11) , encodes that into H.264 (FFmpeg libs),
stream it over WebSocket to the browser where it is finally decoded in a H.264 JavaScript software-based library.

Browser sends control commands (mouse commands) to server over WebSocket as well.

Source Code
Simple-web-vnc

Server — H.264 —> Browser (http://serverIP:8888)
Server <— Commands — Browser

Encoder: H.264 (FFmpeg libs)
Protocol: Websocket (Go lib)
Decoder: H.264 (JavaScript H.264)

Build on Ubuntu 14.04 64bit

Demo

IPMI Tools

There are 4 notable ipmi sw tools and here is the compare ipmi tools compare

Usage EX:
Get sensors

  • ipmi-sensors -h 10.250.210.139 -u admin -p password -D LAN_2_0

  • ipmitool -I lanplus -U admin -P password -H 10.250.210.13 sdr list

  • ipmiutil sensor -c -F lan2 -N 10.250.210.13 -U admin -R password

How to build the reusable library of ipmitool…

  1. doenload ipmitool 1.8.15

  2. yum install openssl openssl-devel (For “lanplus : yes”)

  3. cd ipmitool 1.8.15 & CC=gcc4 CFLAGS=-m32 LDFLAGS=-static & ./configure

  4. (make clean) & make & make install

  5. cd src

  6. /bin/sh ../libtool –silent –tag=CC –mode=link gcc -fno-strict-aliasing -Wreturn-type -all-static -o ipmitool.a ipmishell.o ../lib/libipmitool.la plugins/libintf.la

  7. gcc -g -lm -lcrypto ipmitool.c -fPIC -shared -o libicdcipmi.so -L. ipmitool.a -I./ipmitool-1.8.15/include/

Build own libicdcipmi.so using ipmitool.a

ipmitool.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
...
int getSensorsIPMI(char *interface, char *usr, char *pws, char *ip, char *retry, char *getJsonString){
int rc,i;
int argc = 13;
char** argv;
argv = malloc(argc * sizeof(char*));
for (i = 0; i < argc; i += 1)
argv[i] = malloc(32 * sizeof(char));

sprintf(argv[0],"%s", "m.out");
sprintf(argv[1],"%s", "-I");
sprintf(argv[2],"%s", interface);
sprintf(argv[3],"%s", "-U");
sprintf(argv[4],"%s", usr);
sprintf(argv[5],"%s", "-P");
sprintf(argv[6],"%s", pws);
sprintf(argv[7],"%s", "-H");
sprintf(argv[8],"%s", ip);
sprintf(argv[9],"%s", "-R");
sprintf(argv[10],"%s", retry);
sprintf(argv[11],"%s", "sensor");
sprintf(argv[12],"%s", "icdc"); // list

struct ipmi_intf_icdc iii;
memset(&iii, 0, sizeof(struct ipmi_intf_icdc));
ipmi_icdc_mian(argc, argv, ipmitool_cmd_list, NULL, &iii);

for (i = 0; i < argc; i += 1)
free(argv[i]);
free(argv);

return rc;
}
...

8.cp libicdcipmi.so /usr/lib & ldconfig

9.go build icdc_ipmi.go

icdc_ipmi.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
#cgo LDFLAGS: -L/usr/lib/ -licdcipmi
#cgo CFLAGS: -I./
#include <stdio.h>
#include <stdlib.h>
#include "ipmitool.h"
*/

import "C"
import (
"os"
"fmt"
"runtime"
"unsafe"
)

func getSensorsIPMI() {
drvtyp := C.CString("lanplus")
nod := C.CString("10.250.210.13")
usr := C.CString("ad")
psw := C.CString( "pd")
retry := C.CString( "1")
var getJson [8192]byte
ret := C.getSensorsIPMI( drvtyp, usr, psw, nod, retry, (*C.char)(unsafe.Pointer(&getJson[0])))
C.free(unsafe.Pointer(drvtyp))
C.free(unsafe.Pointer(nod))
C.free(unsafe.Pointer(usr))
C.free(unsafe.Pointer(psw))
C.free(unsafe.Pointer(retry))
if ret == 0 {
var jsonString string
jsonString = C.GoString((*C.char)(unsafe.Pointer(&getJson[0])))
fmt.Println("getSensorsIPMI => ",jsonString)
}
}

Proxy intranet & internet

Install Fiddler on Host (intranet & internet)

open Fiddler

“Tools” -> “Fiddler Options” -> “Connections” -> check “Allow remote computers to connect” and “Fiddler listens on port” keep default 8888 if you would like…

restart Fiddler

Linux Client (only intranet)

Setting

Cancel

  • unset http_proxy
  • unset https_proxy

Docker & Supervisord

Host and inside docker’ containers all use supervisord to control processes…

Host : CentOS 7

Install docker

Notice:

1. Enable IP forwarding in Linux

$ sysctl net.ipv4.ip_forward

net.ipv4.ip_forward = 0

$ sysctl -w net.ipv4.ip_forward=1

$ service docker restart

2. Cannot open directory .: Permission denied

$ chcon -Rt svirt_sandbox_file_t ./code/

Install supervisord

Notice:
1. Supervisord.conf

default file is indeed /etc/supervisor.conf

2.Starting supervisor: Unlinking stale socket /var/run/supervisor.sock

$ pip install meld3==0.6.7

find / -name supervisor.sock

unlink /…/supervisor.sock

$ unlink /var/run/supervisor.sock

Install golang

Notice:

1. GOPATH=”….”

$ vi ~/.bashrc

Add

export GOPATH=”/home/Go”


A. Docker commands

1.Stop all containers

$ docker stop $(docker ps -a -q)

2.Delete all containers

$ docker rm $(docker ps -a -q)
  1. Delete all images
$ docker rmi $(docker images -q)

B. Build docker image

1. Prepare the Dockerfile


FROM centos:centos7
MAINTAINER Jeff Yang
ENV MAJOR_PATH /home/apps/IPMI/
ENV INSTALL_PATH /home/install/ 
ENV CONFIG_PATH /home/apps/DCMS/config/
RUN mkdir -p $MAJOR_PATH 
RUN mkdir -p $CONFIG_PATH
RUN mkdir -p $INSTALL_PATH
### Install supervisord
#RUN yum update -y
#RUN yum -y install python-setuptools epel-release python-pip
#RUN easy_install supervisor
COPY setuptools-19.2.tar.gz $INSTALL_PATH 
COPY meld3-0.6.5.tar.gz $INSTALL_PATH 
COPY elementtree-1.2-20040618.tar.gz $INSTALL_PATH 
COPY supervisor-3.1.3.tar.gz $INSTALL_PATH 
COPY ipmiutil-2.9.6-1_rhel6.x86_64.rpm $INSTALL_PATH  
RUN chmod 700 $INSTALL_PATH/setuptools-19.2.tar.gz && \
tar -zxvf $INSTALL_PATH/setuptools-19.2.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/setuptools-19.2/ && \ 
python setup.py install
RUN chmod 700 $INSTALL_PATH/meld3-0.6.5.tar.gz && \
tar -zxvf $INSTALL_PATH/meld3-0.6.5.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/meld3-0.6.5/ && \ 
python setup.py install
RUN chmod 700 $INSTALL_PATH/elementtree-1.2-20040618.tar.gz && \
tar -zxvf $INSTALL_PATH/elementtree-1.2-20040618.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/elementtree-1.2-20040618/ && \ 
python setup.py install
RUN chmod 700 $INSTALL_PATH/supervisor-3.1.3.tar.gz && \
tar -zxvf $INSTALL_PATH/supervisor-3.1.3.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/supervisor-3.1.3/ && \ 
python setup.py install

2. Build base image


$ docker build -t="code_icdc:v.01″ .

C. Backup image

1. Save image

$ docker save -o code_icdc_v01.tar code_icdc:v.01

2. Load image

$ sudo docker load –input code_icdc_v01.tar

OR

$ sudo docker load < code_icdc_v01.tar

D.

1. Build own program (ipmicdc)


$ go build ipmicdc.go ipmidocker.go

ipmidocker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package main
import (
"math"
"os"
"strconv"
"errors"
"fmt"
"os/exec"
"net/http"
"time"
)
const gDYamlName = "icdc.yml"
const gDHostImage = "code_icdc:v.01"
const gDVolumes1_Host = "./"
const gDVolumes1_Client = "/home/apps/IPMI/"
const gDVolumes2_Host = "/home/apps/DCMS/config/"
const gDVolumes2_Client = "/home/apps/DCMS/config/"
const gDPort = "31001"
var gDTotalContainers int
var gDHostIPPort int
var gDTotalIPsCount int
var gDNumprocs int
var gDMaxHandleIPs int

type IcdcDocker struct {
}

func (sid *IcdcDocker) update(w http.ResponseWriter, r *http.Request) {
if gDHostIPPort<= 0 || gDNumprocs <= 0 || gDMaxHandleIPs<=0 {
fmt.Fprintf(w, "fail")
return
}
err := sid.run(gDHostIPPort, gDNumprocs, gDMaxHandleIPs)
if err != nil{
fmt.Fprintf(w, "fail")
}
fmt.Fprintf(w, "ok")
}

func (sid *IcdcDocker) stop() (e error) {
var err error
err = sid.dockerAllStop()
if err != nil {
return errors.New("run ERROR")
}
err = sid.dockerAllRm()
if err != nil {
return errors.New("run ERROR")
}
return nil
}

func (sid *IcdcDocker) run( hostIpPort int, numprocs int, maxHandleIPs int ) (e error) {
var err error
err = sid.dockerComposeYamlMaker(hostIpPort, numprocs, maxHandleIPs)
if err != nil {
fmt.Println("run ERROR" )
return errors.New("run ERROR")
}
err = sid.dockerAllStop()
if err != nil {
return errors.New("run ERROR")
}
err = sid.dockerAllRm()
if err != nil {
return errors.New("run ERROR")
}
err = sid.dockerStart()
if err != nil {
return errors.New("run ERROR")
}
return nil
}

func (sid *IcdcDocker) dockerStart() (e error) {
if gDTotalContainers <= 0 {
return errors.New("dockerComposeStart ERROR")
}
cmdStr := "docker-compose -f " + gDYamlName + " up -d"
exec.Command("/bin/sh", "-c", cmdStr).Output()
<-time.After(time.Second)
return nil
}

func (sid *IcdcDocker) dockerAllStop() (e error) {
// stop all contains
cmdStr := "docker stop $(docker ps -a -q)"
exec.Command("/bin/sh", "-c", cmdStr).Output()
<-time.After(time.Second)
return nil
}

func (sid *IcdcDocker) dockerAllRm() (e error) {
// remove all contains
cmdStr := "docker rm $(docker ps -a -q)"
//out, _ :=
exec.Command("/bin/sh", "-c", cmdStr).Output()
<-time.After(time.Second)
return nil
}

func (sid *IcdcDocker) dockerChcon() (e error) {
cmdStr1 := "chcon -Rt svirt_sandbox_file_t "+ gDVolumes1_Host
exec.Command("/bin/sh", "-c", cmdStr1).Output()
cmdStr2 := "chcon -Rt svirt_sandbox_file_t "+ gDVolumes2_Host
exec.Command("/bin/sh", "-c", cmdStr2).Output()
return nil
}

func (sid *IcdcDocker) dockerComposeYamlMaker( hostIpPort int, numprocs int, maxHandleIPs int ) (e error) {
gDTotalContainers = 0
//************************
//get number of ip from DB
totalIPsCount := getTotalIPsCount()
//************************
if hostIpPort<= 0 || numprocs <= 0 || maxHandleIPs<=0 || totalIPsCount<=0 {
fmt.Println("dockerComposeYamlMaker ERROR!!!" )
return errors.New("dockerComposeYamlMaker ERROR")
}
file, err := os.Create(gDYamlName)
if err != nil {
fmt.Println("dockerComposeYamlMaker ERROR!!!" )
return errors.New("dockerComposeYamlMaker ERROR")
}
defer file.Close()
file.Chmod(0777)
var s string
var t int
totalContainers := int( math.Ceil( float64(totalIPsCount) / (float64(numprocs) * float64(maxHandleIPs) ) ))
gDHostIPPort = hostIpPort
gDTotalIPsCount = totalIPsCount
gDNumprocs = numprocs
gDMaxHandleIPs = maxHandleIPs
gDTotalContainers = totalContainers
sid.dockerChcon()
for i := 0; i < totalContainers; i++ {
s = "build" + strconv.Itoa(i) + ":\n"
file.WriteString(s)
s = " container_name: envTest" + strconv.Itoa(i) + "\n"
file.WriteString(s)
file.WriteString(" image: "+ gDHostImage + "\n")
file.WriteString(" ports:\n")
s = " - " + strconv.Itoa(hostIpPort+1+i) + ":"+gDPort+"\n"
file.WriteString(s)
file.WriteString(" volumes:\n")
file.WriteString(" - " + gDVolumes1_Host +":"+gDVolumes1_Client+"\n")
file.WriteString(" - " + gDVolumes2_Host +":"+gDVolumes2_Client+"\n")
file.WriteString(" restart: always\n")
file.WriteString(" stdin_open: true\n")
file.WriteString(" environment:\n")
t = i*numprocs*maxHandleIPs
s = " - IPMI_GET_IP_S=" + strconv.Itoa(t) + "\n"
file.WriteString(s)
t = (i+1)*numprocs*maxHandleIPs - 1
s = " - IPMI_GET_IP_E=" + strconv.Itoa(t) + "\n"
file.WriteString(s)
s = " - ICDC_EXE_PATH=" + gDVolumes1_Client + "\n"
file.WriteString(s)
file.WriteString(" command: sh " + gDVolumes1_Client + "start.sh" + "\n")
}
return nil
}

ipmicdc.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func main() {
...
if os.Args[1] == "docker" { // docker version
numprocs := parserSupervisordConf(os.Args[0])
var err error
var sid IcdcDocker
sid.run( gPort, numprocs, gMaxHandleIPs)
if err != nil{
return
}
//--------------
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
sid.stop()
}()
//--------------
http.HandleFunc("/updateDB", sid.update)
var sic IcdcCmd
http.HandleFunc("/discover", sic.commReceiveDiscoverCommand)
http.HandleFunc("/lan", sic.commReceiveLanCommand)
http.ListenAndServe(":"+strconv.Itoa(gPort), nil)
}
...
}

2. Start.sh include docker‘s Supervisord.conf

Start.sh

1
2
3
4
5
#!/bin/sh
cp $ICDC_EXE_PATH/libs/libipmi.so /usr/lib/
ldconfig
cp $ICDC_EXE_PATH/s.conf /etc/supervisord.conf
/usr/bin/supervisord -c $ICDC_EXE_PATH/supervisord.conf -n

Supervisord.conf



[program:ipmicdc]
command=/home/apps/IPMI/ipmicdc %(process_num)d
process_name = %(process_num)d
numprocs=2
autostart=no
autorestart=yes
[program:ipmi]
command=/home/apps/IPMI/ipmicdc
autostart=yes
autorestart=yes

3. Start Host’s Supervisord

$ supervisord -c /home/jeff/icdc/supervisord_docker.conf -n

supervisord_docker.conf


[program:ipmi_docker]
command=./ipmicdc “docker”
autostart=yes
autorestart=true
stopwaitsecs=10

[root@localhost code]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
f32ab2fe909e code_icdc:v.01 “/bin/bash” 44 seconds ago Up 41 seconds 0.0.0.0:31003->9080/tcp envTest1
2028a0d07072 code_icdc:v.01 “/bin/bash” 50 seconds ago Up 44 seconds 0.0.0.0:31002->9080/tcp envTest0  

Docker-compose 4

在[docker-compose-3]中完成一個新的image建立


$ docker images 
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE 
code_icdc latest 220f9d464171 17 hours ago 304.4 MB

可以更改image tag


$ docker tag code_icdc:latest code_icdc:v.01
$ docker images 
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
code_icdc latest 220f9d464171 17 hours ago 304.4 MB
code_icdc v.01 220f9d464171 17 hours ago 304.4 MB

接著,

可以利用dockerfile和compose 使這個新建的image code_icdc 複製產生多組同樣功能images…

準備一個dockerfile

Dockerfile2


FROM code_icdc:v.01
MAINTAINER Jeff Yang
ENV IPMI_GET_IP_S 1
ENV IPMI_GET_IP_E 10

這裡設定一組Environment Variables,來測試複製的image

docker-image.yml


build:
 container_name: envTest
 build: ./
 dockerfile: Dockerfile2
 ports: 
     - 9083:9080
 volumes:
     - /home/jeff/code/test_dockerEnv:/home/code/test_dockerEnv
 restart: always 
 stdin_open: true
 tty: true

$ docker-compose up -d -f docker-image.yml

完成image後,檢視現在多了一個新的testdockerenv_build image


$ docker images 
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
testdockerenv_build latest 48e05900d52b 7 seconds ago 304.4 MB
code_icdc latest 220f9d464171 17 hours ago 304.4 MB
code_icdc v.01 220f9d464171 17 hours ago 304.4 MB

測試程式,簡單的印出環境變數

goEnv.go

1
2
3
4
5
6
7
8
9
10
11
12
13
package main
import (
"fmt"
"os"
"bufio"
)
func main() {
fmt.Println("IPMI_GET_IP_S:", os.Getenv("IPMI_GET_IP_S"))
fmt.Println("IPMI_GET_IP_E:", os.Getenv("IPMI_GET_IP_E"))
//getchar()
reader := bufio.NewReader(os.Stdin)
reader.ReadString('\n')
}

接著,進入container


$ docker exec -it envTest bash

查看supervisord是否有啟動


[root@a6d077cfdd7c home]# supervisorctl status
ipmi RUNNING pid 9, uptime 0:00:42
ipmi_monitor RUNNING pid 22, uptime 0:00:36
ipmicdc:0 STOPPED Not started
ipmicdc:1 STOPPED Not started
ipmicdc:2 STOPPED Not started
ipmicdc:3 STOPPED Not started
ipmicdc:4 STOPPED Not started

執行程式,將印出環境變數


[root@a6d077cfdd7c home]# cd ./code/test_dockerEnv/
[root@a6d077cfdd7c test_dockerEnv]# ./goEnv
IPMI_GET_IP_S: 1
IPMI_GET_IP_E: 10
[root@a6d077cfdd7c test_dockerEnv]# echo $IPMI_GET_IP_E
10

若不需要產生新image,

也可以直接執行docker run,利用現有image產生container


$ docker run -e "IPMI_GET_IP_S=1" -e "IPMI_GET_IP_E=10" -itd --name envTest --restart=always -p 9083:9080 -v /home/jeff/code/test_dockerEnv:/home/code/test_dockerEnv code_icdc:v.01 
90cd3ba79bc4a9b705c823e0ba488e04ad7efc07c7181ef6b28cd14e5dc1d31c

$ docker images
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
code_icdc latest 220f9d464171 18 hours ago 304.4 MB
code_icdc v.01 220f9d464171 18 hours ago 304.4 MB
docker.io/centos centos7 60e65a8e4030 13 days ago 196.6 MB
docker.io/centos latest 60e65a8e4030 13 days ago 196.6 MB

相同步驟確認環境變數


$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
90cd3ba79bc4 code_icdc:v.01 "/bin/sh -c $MAJOR_PA" 17 seconds ago Up 16 seconds 0.0.0.0:9083->9080/tcp envTest

$ docker exec -it envTest bash
[root@90cd3ba79bc4 /]# cd /home/code/test_dockerEnv/
[root@90cd3ba79bc4 test_dockerEnv]# ./goEnv
IPMI_GET_IP_S: 1
IPMI_GET_IP_E: 10

Docker-compose 3

接著利用compose結合dockerfile,並在dockerfile中安裝和啟動supervisord

Dockerfile


FROM centos:centos7
MAINTAINER Jeff Yang
#RUN yum update -y
RUN yum -y install openssl-devel
ENV MAJOR_PATH /home/apps/IPMI/
ENV INSTALL_PATH /home/install/ 
ENV CONFIG_PATH /home/apps/DCMS/config/
RUN mkdir -p $MAJOR_PATH 
RUN mkdir -p $CONFIG_PATH
RUN mkdir -p $INSTALL_PATH
### Install supervisord manually
#RUN yum -y install python-setuptools python-pip
#RUN easy_install supervisor
COPY setuptools-19.2.tar.gz $INSTALL_PATH 
COPY meld3-0.6.5.tar.gz $INSTALL_PATH 
COPY elementtree-1.2-20040618.tar.gz $INSTALL_PATH 
COPY supervisor-3.1.3.tar.gz $INSTALL_PATH  
COPY ipmiutil-2.9.6-1_rhel6.x86_64.rpm $INSTALL_PATH  
RUN chmod 700 $INSTALL_PATH/setuptools-19.2.tar.gz && \
tar -zxvf $INSTALL_PATH/setuptools-19.2.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/setuptools-19.2/ && \ 
python setup.py install
RUN chmod 700 $INSTALL_PATH/meld3-0.6.5.tar.gz && \
tar -zxvf $INSTALL_PATH/meld3-0.6.5.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/meld3-0.6.5/ && \ 
python setup.py install
RUN chmod 700 $INSTALL_PATH/elementtree-1.2-20040618.tar.gz && \
tar -zxvf $INSTALL_PATH/elementtree-1.2-20040618.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/elementtree-1.2-20040618/ && \ 
python setup.py install
RUN chmod 700 $INSTALL_PATH/supervisor-3.1.3.tar.gz && \
tar -zxvf $INSTALL_PATH/supervisor-3.1.3.tar.gz -C $INSTALL_PATH && \
cd $INSTALL_PATH/supervisor-3.1.3/ && \ 
python setup.py install

RUN rpm -i $INSTALL_PATH/ipmiutil-2.9.6-1_rhel6.x86_64.rpm
###
COPY ipmicdc $MAJOR_PATH
RUN chmod 700 $MAJOR_PATH/ipmicdc
COPY ./libs/libipmi.so /usr/lib/
RUN ldconfig
COPY supervisord.conf $MAJOR_PATH
COPY config.ini $MAJOR_PATH
COPY start.sh $MAJOR_PATH
COPY config.json $CONFIG_PATH
RUN ln -s $MAJOR_PATH/supervisord.conf /etc/supervisord.conf

#EXPOSE 9080 9081
CMD $MAJOR_PATH/start.sh 

docker-compose.yml


icdc:
 container_name: jeff
 build: ./
 dockerfile: Dockerfile 
 ports: 
 - 9080:9080
 volumes:
 - /home/jeff/code/:/home/code
 restart: always 
 stdin_open: true
 tty: true

supervisord.conf


...
[program:ipmicdc]
command=/home/apps/IPMI/ipmicdc %(process_num)d 
process_name = %(process_num)d
numprocs=5 
autostart=no 
autorestart=yes
;stdout_logfile=/home/apps/IPMI/hh.log
[program:ipmi]
command=/home/apps/IPMI/ipmicdc 
autostart=yes
autorestart=yes
;stdout_logfile=/home/apps/IPMI/m.log
...

start.sh


#!/bin/sh
/usr/bin/supervisord -c /home/apps/IPMI/supervisord.conf -n

在docker-compose.yml所在目錄下執行


docker-compose up -d

順利的話,supervisord中所設定的程式將會啟動執行