숫자에 자릿점 찍기

l33t 2009. 7. 20. 11:34

자릿수 구분단위가 없이 큰 숫자를 보는 것은 작으면서도 큰 불편함이다.

db2에서, 또는 printf를 통해서 숫자를 출력할 때 자릿점 찍기가 불가능하다.
ksh로 역시 상당히 어렵다.

다음 펄 스크립트를 사용해 숫자에 자릿점을 넣을 수 있다.
#!/usr/bin/perl -w
use strict;

sub commarize
{
    my $text = reverse($_[0]);
    $text =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
    return(scalar(reverse($text)));
}

my $i = 0;
while ($i <= $#ARGV)
{
    my $s = commarize($ARGV[$i]);
    printf("%s\n",$s);
    ++$i;
}
exit(0);

위 내용을
PATH가 걸린 위치에 commarize 따위의 이름으로 저장하고
chmod 777 실행권한을 지정한 후
ksh 스크립트에서 다음과 같이 사용하면 된다.

foo=$(db2 -x "select count(*) from bigTable")
bar=$(commarize ${foo})
echo "Count = ${bar}"


Posted by in0de
,
// 설치 전 필요사항 체크 루틴
INODE:/sw/db2/FixPak # ./db2prereqcheck

// FixPak 4 를 tar 해제한 후 db2_install 실행
INODE:/sw/db2/FixPak # ./db2_install
 
Default directory for installation of products - /opt/IBM/db2/V9.5
***********************************************************
Do you want to choose a different directory to install [yes/no] ?
yes
Enter full path name for the install directory -
------------------------------------------------
/sw/db2/V9.5.0.4
 
 
Specify one of the following keywords to install DB2 products.
  ESE
  CONSV
  WSE
  CLIENT
  RTCL
 
Enter "help" to redisplay product names.
Enter "quit" to exit.
***********************************************************
ESE
DB2 installation is being initialized.

 Total number of tasks to be performed: 44
Total estimated time for all tasks to be performed: 2092

Task #1 start
Description: Enabling Asynchronous I/O
Estimated time 2 second(s)
Task #1 end

Task #2 start
Description: Checking license agreement acceptance
Estimated time 1 second(s)
Task #2 end

...중간생략...

Task #43 start
Description: Initializing instance list
Estimated time 5 second(s)
Task #43 end

Task #44 start
Description: Updating global profile registry
Estimated time 3 second(s)
Task #44 end

A minor error occurred while installing "DB2 Enterprise Server Edition " on
this computer. Some features may not function correctly.

For more information see the DB2 installation log at
"/tmp/db2_install.log.835722".

// minor error의 내용은 다음과 같음
// SA MP는 현 시스템에서는 사용하지 않는 모듈로, 무시해도 됨
Space required:                            1271 MB
Install SA MP Base Component:              No


DBI1130E  The SA MP Base Component could not be installed or updated
      because system prerequisites were not met. See the log file
      /tmp/prereqSAM.log.876590 for details.

Explanation:

There are system prerequisites for installing or updating the IBM Tivoli
System Automation for Multiplatforms Base Component (SA MP Base
Component). These prerequisites have not been met.

The mentioned log file has the details for the unsatisfied
prerequisites.

To find out more about the system prerequisites for the SA MP Base
Component, see the Installation and Configuration Guide at
http://publib.boulder.ibm.com/tividd/td/IBMTivoliSystemAutomationforMultiplatforms2.2.html.

The SA MP Base Component cannot be installed or updated.

User response:

Modify your system to meet the prerequisites; and use the installSAM
utility to manually install the SA MP Base Component.





INODE:/sw/db2/V9.5.0.4/instance # ./db2iupdt -u testfenc testinst
DBI1070I  Program db2iupdt completed successfully.

// 여기까지는 root 유저로 진행,
// 여기서부터는 instance 유저로 진행
INODE:/sw/db2/V9.5.0.4/instance # su - testinst



// FixPak 설치 후 라이선스가 초기화 되기 때문에 다시 업데이트 해주어야 함
INODE:/sw/db2/license $ db2licm -l
Product name:                     "DB2 Enterprise Server Edition"
License type:                     "Trial"
Expiry date:                      "09/06/2009"
Product identifier:               "db2ese"
Version information:              "9.5"

Product name:                     "DB2 Connect Server"
License type:                     "Trial"
Expiry date:                      "09/06/2009"
Product identifier:               "db2consv"
Version information:              "9.5"



INODE:/sw/db2/license $ db2licm -a db2ese_c.lic

LIC1402I  License added successfully.
LIC1426I  This product is now licensed for use as outlined in your License Agreement.  USE OF THE PRODUCT CONSTITUTES ACCEPTANCE OF THE TERMS OF THE IBM LICENSE AGREEMENT, LOCATED IN THE FOLLOWING DIRECTORY: "/sw/db2/V9.5.0.4/license/ko_KR.eucKR"

INODE:/sw/db2/license $ db2licm -a db2so.lic

LIC1402I  License added successfully.
LIC1426I  This product is now licensed for use as outlined in your License Agreement.  USE OF THE PRODUCT CONSTITUTES ACCEPTANCE OF THE TERMS OF THE IBM LICENSE AGREEMENT, LOCATED IN THE FOLLOWING DIRECTORY: "/sw/db2/V9.5.0.4/license/ko_KR.eucKR"


// 라이선스 업데이트 완료
INODE:/sw/db2/license $ db2licm -l
Product name:                     "DB2 Enterprise Server Edition"
License type:                     "CPU Option"
Expiry date:                      "Permanent"
Product identifier:               "db2ese"
Version information:              "9.5"
Enforcement policy:               "Soft Stop"
Features:
DB2 Database Partitioning:        "Not licensed"
DB2 Performance Optimization ESE: "Not licensed"
DB2 Storage Optimization:         "Licensed"
DB2 Advanced Access Control:      "Not licensed"
DB2 Geodetic Data Management:     "Not licensed"
IBM Homogeneous Replication ESE:  "Not licensed"

Product name:                     "DB2 Connect Server"
License type:                     "Trial"
Expiry date:                      "09/06/2009"
Product identifier:               "db2consv"
Version information:              "9.5"




// CLI, 원격 DB 유틸리티, 시스템 스키마에 대해서 다시 바인드 수행
INODE:/db2/testinst # db2 "bind ./sqllib/bnd/@db2cli.lst blocking all grant public sql error continue"
INODE:/db2/testinst # db2 "bind ./sqllib/bnd/@db2ubind.lst blocking all grant public sql error continue"
INODE:/db2/testinst # db2 "bind ./sqllib/bnd/db2schema.bnd blocking all grant public sql error continue"

// DB를 재기동하면 FixPak 적용이 완료됨
INODE:/db2/testinst # db2stop force
INODE:/db2/testinst # db2start

INODE:/db2/testinst # db2level
DB21085I  Instance "testinst" uses "64" bits and DB2 code release "SQL09054"
with level identifier "06050107".
Informational tokens are "DB2 v9.5.0.4", "s090429", "U825478", and Fix Pack "4".
Product is installed at "/sw/db2/V9.5.0.4".


Posted by in0de
,
여러 가지 방법이 존재하겠지만,
db2diag.log에서 Backup Complete 메시지와 함께 정확한 사이즈가 찍혀있다.

2009-05-15-22.46.53.108696+540 I790856A473        LEVEL: Warning
PID     : 1991526              TID  : 1           PROC : db2agent (SAMPLE) 0
INSTANCE: instance             NODE : 000         DB   : SAMPLE
APPHDL  : 0-1823               APPID: *LOCAL.dbpainst.090515090122
FUNCTION: DB2 UDB, database utilities, sqlubcka, probe:128
MESSAGE : Estimated size of backup in bytes:
DATA #1 : Hexdump, 8 bytes
0x0FFFFFFFFFFEDB78 : 0000 09DD 446C 9000                        ....Dl..

2009-05-15-22.46.53.110938+540 I791330A470        LEVEL: Warning
PID     : 1991526              TID  : 1           PROC : db2agent (SAMPLE) 0
INSTANCE: instance             NODE : 000         DB   : SAMPLE
APPHDL  : 0-1823               APPID: *LOCAL.dbpainst.090515090122
FUNCTION: DB2 UDB, database utilities, sqlubcka, probe:128
MESSAGE : Actual size of backup in bytes:
DATA #1 : Hexdump, 8 bytes
0x0FFFFFFFFFFEDB80 : 0000 09DD D4D4 7000                        ......p.

2009-05-15-22.46.53.111391+540 I791801A355        LEVEL: Warning
PID     : 1991526              TID  : 1           PROC : db2agent (SAMPLE) 0
INSTANCE: instance             NODE : 000         DB   : SAMPLE
APPHDL  : 0-1823               APPID: *LOCAL.dbpainst.090515090122
FUNCTION: DB2 UDB, database utilities, sqlubcka, probe:130
MESSAGE : Backup Complete.

위의 예시에서 16진수 0000 09DD D4D4 7000 를 10진수로 변환하면
Backup image의 byte는 10,848,363,114,496 임을 알 수 있다.
Posted by in0de
,
윈도우를 사용하다보면
아주 드물게 탐색기에서 파일 이름이 사라지는 경우가 발생한다.



검색어를 정하기도 참 난해한 문제인데,
국내에서는 관련된 링크를 찾을 수 없고
국외에서는

vistax64.com:no-text-icons-user-folder.html
mydigitallife.info:missing-file-and-folder-names-in-windows-vista-explorer-large-icon-and-details-view-easter-egg-or-bug/
등을 찾을 수 있지만, 그대로 적용하기는 어려웠다.

이런 경우 시도해볼 수 있는 것은
해당 폴더의 보기 템플릿을 변경했다가, 모든 항목으로 원상복구하여 리셋해 볼 수 있겠다.


윈도우 2003을 사용할 때는 이 문제가 발생해서 재설치까지 했던 적이 있는데
이런 현상은 XP, Vista, Windows 2008까지 골고루 발생하는 것 같고
폴더 보기 설정 풀림 문제와 유사한 원인으로 생각된다.



http://www.vistax64.com/tutorials/70819-windows-explorer-folder-view-settings.html?ltr=W

다음 내용을 *.reg으로 생성하여 레지스트리에 병합한다.


Windows Registry Editor Version 5.00

;폴더 보기 설정 Reset
[-HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU]
[-HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags]
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\BagMRU]
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Bags]
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\ShellNoRoam\BagMRU]
[-HKEY_CURRENT_USER\Software\Microsoft\Windows\ShellNoRoam\Bags]

;폴더 유형 자동 감지 기능 해제
[HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell]
"FolderType"="NotSpecified"

;폴더 보기 기억 개수 확장 (기본값 5,000개의 폴더 설정을 기억 -> 20,000 )
[HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell]
"BagMRU Size"=dword:00004e20


레지스트리 병합 후 재부팅하면 적용이 된다.
Posted by in0de
,
ksh는 아주 기본적인 쉘이어서 라이브러리는 커녕
기본적인 스트링 함수조차 찾기 어렵다.

제한적인 기능 속에서도 도움이 되는


The pattern in the following uses the same wildcards as for filename matching.

${#var}
    $var의 길이를 리턴
${var%pattern}
    removes the shortest suffix of $var patching pattern
${var%%pattern}
    removes the longest suffix of $var patching pattern
${var#pattern}
    removes the shortest prefix of $var patching pattern
${var##pattern}
    removes the longest prefix of $var patching pattern

Numeric variables

$(( integer expression ))
    The $(( ... )) construction interprets the contents as an arithmetic expression (integer only). Variables are referenced by name without the "$". Most of the arithmetic syntax of the 'C' language is supported, including bit manipulations (*,/,+,-,|,&,<<,>>. Use parentheses for changing precedence).

Examples
datapath=/data/public/project/trials/set1/datafile.dat

filename=${datapath##*/}
    filename is set to "datafile.dat" since the longest prefix pattern matching "*/" is the leading directory path (compare basename)
path=${datapath%/*}
    path is set to "/data/public/project/trials/set1" since the shortest suffix pattern matching "/*" is the filename in the last directory (compare dirname)

i=$((i+1))
    often used in while loops
Posted by in0de
,

sqllib/tmp

DB2 LUW 2009. 4. 16. 16:38

${instance home}/sqllib/tmp는 다음의 유틸리티/어플리케이션/툴 들에 의해 I/O가 발생한다.

DB2 Engine
db2 Utilities(Backup, load, import 등)
DB2 Governor
DB2 Snapshot functions
DB2 GUI tools / DB2 Wizards
  (ie. Server profile generated from the Control Center, Redistribution Data wizard) 
DB2 Extenders (ie. Text Information Extender)
any application (ie. WebSphere)


Linux의 경우, sqllib/tmp 에 named pipe를 생성하여
frontend(db2), backend(db2bp) 프로세스 간의 통신을 하기도 한다.

DB2 Engine에서의 temporary processing의 세부내용은 알 수 없겠지만
대부분의 경우는 index key sorting 이라던가
여러 utility나 application들에 의해 I/O가 발생된다고 보면 되겠다.

엔터프라이즈 시스템에서의 sqllib/tmp의 위치는 신경써서 정해야할 듯 한데
실제로 이 디렉토리를 모니터링해보면 상당히 자주, 많이 access하고있고

파일시스템에 문제가 있거나
(ie. 시만텍의 매우 오래된 VxFS 4.0.3.2 (4.0 MP3RP2)의
비효율적인 dirty page scan 알고리즘으로 인해 disk I/O의 30%를 일으켰던 경우)

좋지 못한 성능의 Internal disk에 instance home을 둔다거나 한다면
전체적으로 DB의 성능을 떨어뜨릴 수 있기 때문이다.

instance home 디렉토리는 디스크 장애에 의해서 inaccessible할 경우
DB에 대해서 어떠한 제어도 할 수 없게 되므로, 안정적인 디스크에 두어야 하며

안정적인 디스크에 instance home을 두었으나 속도가 좋지 못해,
sqllib/tmp로 인한 성능 저하가 우려되는 경우
DB 자체적으로 sqllib/tmp의 위치를 hidden parameter등으로 변경할 방법은 존재하지 않으며
다음과 같은 방법으로 성능 좋은 디스크 쪽의 디렉토리를 링크하여
안정성과 성능을 둘 다 만족시킬 수 있다.

mkdir ${better perf disk path}/newTmpPath
rm -rf ${instance home}/sqllib/tmp
ln -s ${better perf disk path}/newTmpPath ${instance home}/sqllib/tmp
Posted by in0de
,

db2diag.log 분할하기

DB2 LUW 2009. 4. 16. 14:50
db2diag.log는 db에 문제가 생겼을 때 참조할 수 있는
가장 확실하고 가장 먼저 살펴볼 제 1의 레퍼런스이다.

db2diag.log는
active log, archive log, loadcopy, dump, tablespaces 와 함께
용량관리를 해주어야 하는 대상이 되는데

db2diag 커맨드는 db2diag.log를 분석하는 포매팅 툴로서,
제공하는 기능들 중에서 -A 옵션으로, db2diag.log를 분할하여 archive 할 수 있다.

in root's crontab
59 23 * * * su - ${instance user} -c "db2diag -A ${diagpath}/db2diag.log" > /dev/null 2>&1

매일 오후 23시 59분에 db2diag.log를 db2diag.log_YYYY-MM-DD-HH.MM.SS 형태로
하루에 하나씩 db2diag.log를 새로 생성하도록 해두면
로그를 검색하기도 쉽고 오래된 로그를 백업해두거나 삭제하는 정책을 만들기도 좋다.
Posted by in0de
,
DB2 v9.x 에서는 column을 drop할 수 있는 등의
DB2 v8.x보다 더 유연한 기능을 제공하기 시작했는데

다음과 같은 명령들을 수행하면 해당 Table은 Reorg Pending 상태가 되며
이렇게 Reorg Pending state에 빠지게 만드는 명령을 REORG-recommended operations 라고 한다.

ALTER TABLE foo DROP COLUMN C1
ALTER TABLE bar ALTER COLUMN C1 SET DATA TYPE BIGINT

하지만 테이블의 스키마를 변경하는 경우라고 하더라도
다음의 경우에는 수행 후에도 Reorg Pending에 빠지지 않는다.

ALTER TABLE bar ALTER COLUMN C1 SET NOT NULL
ADD COLUMN
ALTER COLUMN DEFAULT VALUE
RENAME TABLE
ALTER COLUMN SET DATA TYPE VARCHAR/VARGRAPHIC/CLOB/BLOB/DBCLOB


Reorg Pending이 걸리면, 다음 command만을 수행할 수 있는 상태가 되는데

REORG TABLE
DROP TABLE
ALTER TABLE
RENAME TABLE
TRUNCATE TABLE

이렇게 Reorg Pending이 걸린 상태를 확인하려면,
DB2 v9 부터 제공하기 시작한 Snapshot function 또는 Admin view를 조회하면 된다.

db2 "select TABSCHEMA, TABNAME from SYSIBMADM.ADMINTABINFO where REORG_PENDING = 'Y'"


이렇게 Reorg Pending 상태의 테이블에
INPLACE START 를 명시하여 온라인 리오그를 수행하려 하면
SQL0668N + reason code 7 이 발생하게 되고
7        The table is in the reorg pending state. This can occur after
         an ALTER TABLE statement containing a REORG-recommended
         operation.

         Reorganize the table using the REORG TABLE command (note that
         INPLACE REORG TABLE is not allowed for a table that is in the
         reorg pending state).

이런 경우에는
반드시 Offline Reorg(a.k.a Classic Reorg)를 수행해서 해결해야 한다.
Posted by in0de
,

LOB data size 구하기

DB2 LUW 2009. 3. 31. 17:53
CLOB이나 BLOB등의 binary data가 DB를 얼마나 사용하고 있는 지 확인하려면
EXPORT LOBS IN ... LOBFILE ... MODIFIED BY LOBSINFILE 명령으로 export하여
받은 파일의 크기로 확인하는 방법도 있겠지만

가장 좋은 방법으로는
다음의 snapshot function을 통해
테이블 lob field의 페이지 개수를 알아낼 수 있다.

db2 "select tabname, lob_object_pages from table (snap_get_tab('SAMPLE',-1)) as tab"

단, function 실행 시 예기치 못한 DB shutdown이 발생하는 경우가 아주 드물게 있었으므로
운영 환경에서는 실행 시 유의할 필요가 있다.
Posted by in0de
,
DB backup copy를 사용하여 restore를 수행할 경우,
해당 backup copy의 timestamp를 알아내야 한다.

db2 DB의 backup copy가 생성된 timestamp를 확인하는 command는 다음과 같다.

db2 list history backup since YYYYMMDD for ${dbname}

정상적인 경우에는 다음과 같이 timestamp를 확인할 수 있다.

$ db2 list history backup since 20090316 for sample |more
                    List History File for sample
Number of matching file entries = 12
 Op Obj Timestamp+Sequence Type Dev Earliest Log Current Log  Backup ID
 -- --- ------------------ ---- --- ------------ ------------ --------------
  B  D  20090316183010001   N    O  S0422805.LOG S0422879.LOG 
 ----------------------------------------------------------------------------
  Contains 276 tablespace(s):
  00001 SYSCATSPACE
  00002 USERSPACE1
              ...

그러나, 간혹 다음과 같이 조회 시 오류가 발생하는 경우가 있다.

$ db2 list history backup since YYYYMMDD for ${dbname}
                    List History File for sample
Number of matching file entries = 12
SQL2155W  Changes have been made to the recovery history file since the open
scan was issued.

이는 내부적으로 history file에 대해 open scan이 발행된 후
이를 종료하기 위한 db2HistoryCloseScan API의 호출이
비정상적이었을 경우 발생하는 오류이다.

이런 경우는
다음 SQL로 timestamp를 조회할 수도 있고,

select  timestamp(start_time) as "Start Time (min)",
          case(operationType)         when 'F'  then 'Offline Full'
                                                 when 'N' then 'Online Full'
                                                 when 'I' then 'Offline Incremental'
                                                 when 'O' then 'Online Incremental'
                                                 when 'D' then 'Offline Delta' 
                                                 when 'E' then 'Online Delta'        
          else '?'       end as Type, 
          SQLCODE
 from TABLE(ADMIN_LIST_HIST()) AS LIST_HISTORY
where  operation = 'B' ;

위의 TABLE(ADMIN_LIST_HIST()) snapshot function을 수행하는 과정에서
history file scan이 초기화 되므로
간단히 ADMIN_LIST_HIST() function을 호출한 후에
본디의 list history backup 명령을 사용해서 조회가 가능해진다.
Posted by in0de
,