반응형


+tomcat의 구동 스크립트에 환경변수를 추가하여 java 메모리튜닝 및 외부 라이브러리 경로 설정을 한다.


구동 스크립트 경로: /usr/tomcat7/bin/catalina.sh

위 스크립트 가장 앞 부분에 추가한다.
보통 외부 라이브러리 경로는 /usr/local/lib에 추가한다. 그곳에 *.so 동적 라이브러리들을 추가하고 아래와 같이 LD_LIBRFARY_PATH에 추가해 준다.

#!/bin/sh

export LD_LIBRARY_PATH=.:/usr/lib/oracle/12.1/client64/lib:/usr/lib:/usr/local/lib
export CLASSPATH=/usr/java/latest/jre/lib/ext:/usr/java/latest/lib/tools.jar
JAVA_OPTS="-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 -Djava.library.path=/usr/local/lib -Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m -XX:NewSize=512m -XX:MaxNewSize=512m -XX:PermSize=512m -XX:MaxPermSize=512m -XX:+DisableExplicitGC"

export TOMCAT_HOME=/usr/tomcat7
export CATALINA_HOME=/usr/tomcat7
export CATALINA_BASE=/usr/tomcat7
export CATALINA_PID=/usr/tomcat7/bin/tomcat.pid




+ 톰캣 튜닝
# vi /usr/tomcat/conf/server.xml


connectionTimeout="5000" 
     타임아웃으로 기본 60초 (60000) 이다. 10초이내 권장
maxThreads="100"
     tomcat의 최대 쓰레드 수. 최대 접속 가능한 active user수
acceptCount="100"
     tomcat thread full일 경우 대기 queue의 길이
disableUploadTimeout="true"
     데이터 업로드 할 때 사이즈가 크면 timeout이 걸릴수 있음. 이를 방지.
maxConnection="8192"
     tomcat이 유지하는 최대 접속 수.
     


-listner 설정
루트 계정으로 실행 못하게 막기
 <Listener className="org.apache.catalina.security.SecurityListener" checkedOsUsers="root" /> 

-Connector 설정
protocol="org.apache.coyote.http11.Http11Protocol"
acceptCount="10"
enableLookups="false"
compression="off"
maxConnection="8192"
maxKeepAliveRequest="1"
maxThread="100"
tcpNoDelay="true"

예)
<Connector port="8080" address="localhost" maxThreads="250" maxHttpHeaderSize="8192" emptySessionPath="true" protocol="HTTP/1.1" enableLookups="false" redirectPort="8181" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />


       <Connector port="8443" protocol="HTTP/1.1"
                SSLEnabled="true" scheme="https" secure="true"
                clientAuth="false" sslProtocol="TLS"
                keystoreFile="/var/www/tomcat.keystore" keystorePass="패스워드"
                URIEncoding="UTF-8"
                maxThreads="250" maxHttpHeaderSize="8192"
                enableLookups="false" acceptCount="100" connectionTimeout="20000"
                disableUploadTimeout="true" 
     compression="off"
     tcpNoDelay="true"
/>


+JVM 튜닝
vi $CATALINA_HOME/bin/catalina.sh
첫 줄에 JAVA_OPTS 추가.
-Xmx1024m –Xms1024m -XX:MaxNewSize=384m -XX:MaxPermSize=128m

메모리 부족시 덤프를 뜨게하여 추적할 수 있다.
-XX:-HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=./java_pid<pid>.hprof
-XX:ParallelGCThreads=2 -XX:-UseConcMarkSweepGC

예)
JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m -XX:NewSize=512m -XX:MaxNewSize=512m -XX:PermSize=512m -XX:MaxPermSize=512m -XX:+DisableExplicitGC"



+++ OS 튜닝 필요

+ 사용자 최대 파일(소켓 포함) 오픈 개수
ulimit -a로 확인 가능
소켓도 파일 이므로 최대 사용 개수가 제한된다....

:변경 방법
#sysctl -w fs.file-max=372738

아래도 작업
#vi /etc/sysctl.conf
fs.file-max=372738

#sysctl -p

; 변경 확인
sysctl fs.file-max
or
cat /proc/sys/fs/file-max

-최대 파일 오픈 개수 확인 ; ulimit -a
open files ; 1024
>변경방법
#vi /etc/security/limits.conf
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
; xxxx는 65535 등...
ulimit -a 로 확인

-backlog 최대값 ; sys/socket.h
SOMAXCONN 값을 참조
>변경 방법
sysctl -a | grep somaxconn     ; 확인
sysctl -w net.core.somaxconn=2048



'Develop > Java' 카테고리의 다른 글

tomcat 프로세스 모니터링. 죽으면 다시 시작  (0) 2018.03.06
CentOS, tomcat 타임존 문제  (2) 2018.03.06
jqGrid(2) row(줄) 색상 변경/값 변경  (0) 2016.01.22
jqGrid (1)  (0) 2016.01.19
한글 인코딩 UTF8  (0) 2015.06.02
반응형

리눅스에서 간단히 OpenSSL로 암복호화 테스트하기


+인코딩

-base64 인코딩하기.

echo "this is a test" | openssl enc -base64

-base64 디코딩하기

echo "dGhpcyBpcyBhIHRlc3QK" | openssl enc -d -base64
this is a test

echo "dGhpcyBpcyBhIHRlc3QK" | openssl enc -base64 -d

this is a test



+ AES 256 암복호화

echo "this is a test" | openssl enc -aes-256-cbc -a

암호키 입력

출력은 base64 인코딩형태 (커맨드 마지막에 -a를 빼면 바이너리로 출력하므로 파일 리다이렉션> 으로 파일로 저장할 수도 있다.)


echo "base64 암호화값" | openssl enc -aes-256-cbc -d -a

암호키 입력


+기타 옵션

-in ; 입력 파일

-out ; 출력 파일

-a ; base64 인코딩하여 출력

-k ; 패스워드 (암복호화시 생략하면 프롬프트상에서 물어본다.)



+파일 암복호화 

$ openssl enc -aes-256-cbc -salt -a -in file.txt -k school -out file.txt.enc

$ cat file.txt.enc

U2FsdGVkX19VTO6a11weGV665ZPM3sGKpZadud21IEw=


$ openssl enc -aes-256-cbc -d -a -in file.txt.enc -out file.dec

enter aes-256-cbc decryption password:

$ cat file.dec

hello

(-a를 빼면 바이너리로 데이터 생성, -k 로 패스워드 지정가능.)




+ 해시 테스트

MD5 해시값을 생성한다. 파라미터로 파일명을 주면 파일을 읽어 해시값을 생성하고, echo로 출력한 것을 pipe로 받아 해시값을 생성할 수 도 있다. 

$ openssl md5 filename

$ echo "hello" | openssl md5

주의! echo로 출력시에는 마지막에 \n이 자동으로 들어간다.

이를 막으려면 -n 옵션을 echo에 추가해 주어야 한다.


$ openssl sha1 filename

$ openssl sha256 filename








'Security' 카테고리의 다른 글

DLKM 방식의 후킹 모듈 보호 메커니즘  (1) 2015.06.07
버퍼오버런(Buffer-Overrun)의 실체와 분석  (0) 2015.06.06
해시(Hash)  (1) 2015.06.02
반응형

아래와 같은 함수를 x가 -500~500 까지인 샘플을 가지고, 학습하여 -1000에서 1000까지의 출력결과를 보자.

학습은 기존의 샘플에 맞는 최적화된 모델을 찾을 뿐 그것으로 미래를 예측하는 것은 이 방식으로는 한계가 있다. 주어진 범위 내에서만 가능하다. 학습된 범위 밖의 영역에서는 정확하지 않다. 물론 가까운 정도는 어느정도 맞지 않을까.

학습할 그래프.

위 그래프의 수식은 아무렇게나 만들어본 

y=sin(x/100)*500+ cos(x/27)*300 + x


# -*- coding: utf-8 -*-


'''

Created on Sat May 13 10:54:59 2017


@author: Junhee

'''


#

# complex algbra predict learning? is it possible???

# continous valued target bounded range (-1000,1000)

# not using polynomial modified input!. because I don't know

# what polynomial degree is correct. 

#



import numpy as np

import tensorflow as tf

import matplotlib.pyplot as plt

import time



bDrawFigure = True

# train yes or no

bTrain = 1

#learning_rate = 0.1


#learning_rate = 0.00001

learning_rate = 0.001

train_cnt = 4000




# unknown algbra function

def problem(x):

    y = np.sin(x/100)*500 + np.cos(x/27)*300 +x

    return y

# can u imagine? i dont know.

xrange = np.linspace(-500, 500, 1000)

y_correct = problem(xrange)



# draw graph?

if bDrawFigure:

    plt.figure()

    plt.plot(xrange, y_correct)


output_space = 2000     # tanh ; -1~1 X output_space ; output range! ; -2000~2000


                    # x domain ; -1000~1000

trainx = np.random.rand(train_cnt)*2000-1000   # training set must be shuffle!!!

trainx = trainx.reshape([-1,1])

trainy_cor = problem(trainx)

trainy_cor = trainy_cor.reshape([-1,1])



X = tf.placeholder(tf.float32, shape=[None,1])

Y = tf.placeholder(tf.float32, shape=[None,1])


# make network NN

W1 = tf.Variable(tf.random_normal([1,512]))

b1 = tf.Variable(tf.zeros([512]))

L1 = tf.nn.sigmoid(tf.matmul(X, W1)+b1)

#L1 = tf.nn.tanh(tf.matmul(X, W1)+b1) 


W2 = tf.Variable(tf.random_normal([512,1024]))

b2 = tf.Variable(tf.zeros([1024]))

L2 = tf.nn.sigmoid( tf.matmul(L1, W2)+b2) 


W3 = tf.Variable(tf.random_normal([1024,1024]))

b3 = tf.Variable(tf.zeros([1024]))

L3 = tf.nn.sigmoid( tf.matmul(L2, W3)+b3) 


W4 = tf.Variable(tf.random_normal([1024,1024]))

b4 = tf.Variable(tf.zeros([1024]))

L4 = tf.nn.sigmoid( tf.matmul(L3, W4)+b4) 


W5 = tf.Variable(tf.random_normal([1024,1]))

b5 = tf.Variable(tf.zeros([1]))

#Llast = tf.nn.tanh( tf.matmul(L4, W5)+b5) *output_space

#Llast = (tf.matmul(L4, W5)+b5) *output_space

Llast = (tf.matmul(L4, W5)+b5)


cost = tf.reduce_mean( tf.square(Llast-Y) )


train = tf.train.AdamOptimizer(learning_rate).minimize(cost)


sess = tf.Session()

sess.run( tf.global_variables_initializer())


param_list = {'W1':W1,'b1':b1,

              'W2':W2,'b2':b2,

              'W3':W3,'b3':b3,

              'W4':W4,'b4':b4,

              'W5':W5,'b5':b5,

              }

saver = tf.train.Saver(param_list)

#saver.restore(sess, './unknown_predict.ptl')    # continue train


print( "bTrain=", bTrain, " train_cnt=", train_cnt)

# train

oldtime = time.time()

if bTrain:

    for i in range(train_cnt) :

        _, _cost = sess.run( [train, cost], feed_dict={X:trainx, Y:trainy_cor})

        if i%100==(100-1):

            newtime = time.time()

            term = newtime-oldtime

            print( "train=",i," cost=",_cost, " remaintime=", ((train_cnt-i)/100+1)*term)

            oldtime=newtime

    saver.save(sess, './unknown_predict.ptl')


##########################################################

# test

saver.restore(sess, './unknown_predict.ptl')


test_cnt = 500

testx = np.random.rand(test_cnt)*1000-500  # training set must be shuffle!!!

testx = testx.reshape([-1,1])

testy_cor = problem(testx)

testy_cor = testy_cor.reshape([-1,1])

_llast = sess.run( Llast, feed_dict = { X:testx } )

testcost = np.mean( np.square(_llast-testy_cor))

print ( "cost=", testcost )

#for i in range(test_cnt):

#    print("input=", testx[i], " predict=", _llast[i], " correct=", testy_cor[i])

    

#draw compare

if bDrawFigure:

#    xrange = np.linspace(-1000, 1000, 2000)

    xrange = np.linspace(-500, 500, 1000)

    xrange = xrange.reshape(-1, 1)

    _llast2 = sess.run( Llast, feed_dict = { X:xrange } )

    xrange = xrange.reshape(-1)

    testyrange = _llast2.reshape(-1)

    plt.plot(xrange, testyrange, c='r')    

    

plt.show()



GPU로 돌려야지 안 그럼 오래걸린다.

어쨋거나 결과는 아래와 같다.



0부근에서 오차가 심하다.

학습을 오래 할수록 좋아지기는 한다.




'AI(DeepLearning)' 카테고리의 다른 글

tensorflow 강좌2. 자료형  (0) 2018.07.16
[tf] tensorflow 강좌1 로딩테스트  (0) 2018.07.16
[tf] unknown math polynomial function modeling  (0) 2017.06.01
[tf] XOR tensorflow로 학습구현  (0) 2017.05.23
[tf] XOR manual solve  (0) 2017.05.23

+ Recent posts