GEM Documentation Navigation Page. Documentation is also available at The GEM Home Page. Documentation and Code are both Copyright © 1995-2006 by Sql Technologies. All Rights are Reserved.
CommonFunc.pm
Common Function Library
|
DESCRIPTION
Standard/Miscellaneous functions
SUMMARY
get_version() - returns version of the gem ($version,$sht_version)
is_nt() - return 1/0 if you are on NT/Windows
cd_home() - cd to the directory that contains the main code and return that directory
today() - returns date string yyyymmdd.hhmiss
is_up() - writes lock file useful to determine if program is allready running
CommonHeader.pm
2 HOUR TIMEOUT!
|
DESCRIPTION
This module will be included in most batch jobs. It is currently used to set an alarm to reap processes that get stuck and to define your SYBASE variables.
use alarm(0) to cancel if you want - i use --NOTIMEOUT as a stanadard arg for this
ConnectionManager.pm
Persistent connections class
|
DESCRIPTION
This simple interface allows you to keep connections alive between requests. There is no timeout involved so its probably buggy.
FUNCTIONS
- connect
- connection_status
returns connection status:Ok/Disconnected/Fail/Never/Config Err/"Invalid Login/Pass"
the saved values are stored in Last_Conn_State and Last_Ok_Conn_Time. The Last_Conn_State
values are Ok/Fail/Unknown
if no -name : return hash of connection statuses for passed in type
if -name then return scalar
- decode_row
- disconnect(-name=>xxx, -type=>xxx)
- log_dbi_configuration
internal only
- log_sql
internal only
- new
- _ping
- query
DBIFunc.pm
DBI Database Subroutines
|
DESCRIPTION
This is my cut at a generic subroutine library for sybase perl applications. I have used it for a variety of packages and it seems quite adequate. It currently uses dblib. These routines are useful if you only need a single connection to sybase.
AUTHOR
Edward Barlow
mail: edbarlow@mad.scientist.com
url : http://www.edbarlow.com
All Rights Reserved
FUNCTION OVERVIEW
dbi_add_line_number
dbi_colorize_sql - format sql text
dbi_eachobject
dbi_get_sql_text - get sql text for an object
dbi_get_dirlist
dbi_has_login_failed
dbi_msg_exclude - tell message handler to ignore this message
dbi_msg_ok - tell message handler to error out on this message
dbi_set_ignore
dbi_disconnect - close you connection
dbi_connect - connect to your server
dbi_use_database - use database
dbi_query - the main query
dbi_decode_row - interpret output from dbi_query()
dbi_query_to_table - command - output html formatted
dbi_set_debug - set debug option
dbi_set_web_page - set html_on option
dbi_get_errorlogs - return a list of error log files
dbi_set_mode - set run mode
LIBRARY FUNCTIONS
- dbi_disconnect()
DESCRIPTION: cleans up and exits the server
RETURNS: no return code
- dbi_connect($server,$login,$password)
DESCRIPTION: connects to sybase using login & password.
RETURNS: 1/0
OPTIONAL : -nosybaseenvcheck if you are on a web page and dont want to check $SYBASE
- dbi_use_database($db)
DESCRIPTION: use a database
PARAMETERS: $db - database name
RETURNS: returns 1 (success) or 0 (fail)
- dbi_query($db,$query,$die_on_error,$print_hdr,$add_batchid,$srv,$login,$pass)
DESCRIPTION: run a command
PARAMETERS:
$db - database name
$query - what to run
$die_on_err (optional) - if defined then die if an error
$print_hdr - if defined first row will be header info
$add_batchid - batch id should be added
$srv - OPTIONAL SERVER ONLY FOR THIS COMMAND
$login - OPTIONAL LOGIN TO SERVER ONLY FOR THIS COMMAND
$pass - OPTIONAL PASSWORD TO SERVER ONLY FOR THIS COMMAND
RETURNS: returns array (success) or undef (fail). The array must
be decoded
- dbi_decode_row($row)
DESCRIPTION: decodes packed row returned by the functions
PARAMETERS: $row - packed row
RETURNS: array - each element is a cell for row
- dbi_query_to_table($db,$query,$print_hdr, $table_options)
DESCRIPTION: Run sybase query to table (or multiple tables)
RETURNS: table formatted output
- dbi_msg_exclude()
DESCRIPTION: adds to list of messages to exclude
PARAMETERS: message number
RETURNS: N.A.
NOTES: Currently list of messages is
5701,3,4 - use database successful message
4002 - login incorrect message
911,13,16,18,19 - Unable To Use Db
2409 - char set conversion
20012 - srv name not in interfaces file
20018 - general message
20019 - results pending
- dbi_msg_ok($msg)
DESCRIPTION: remove message from list of messages to exclude
PARAMETERS: message number
RETURNS: N.A.
- dbi_get_sql_text($objname,$print_go)
DESCRIPTION: return text for an object
NOTES: handles any object type in current db
PARAMETERS:
$objname: object name in current db
$print_go: do you wish to include a line with the word go
- dbi_colorize_sql($html)
DESCRIPTION: formats sql text
- dbi_get_dirlist($directory)
DESCRIPTION: Returns list of files in directory
- dbi_get_errorlogs($errorlog_type,$SYBASE)
DESCRIPTION: returns a list of sybase errorlogs.
PARAMETERS: errorlog_type:
if type=0 SYBASE
if type=1 Backupserver
if type=2 Both
- dbi_eachobject($db,$cmd,$type,$do_print)
DESCRIPTION: runs cmd on each object of type and print output
PARAMETERS:
$do_print: print text of what you are doing too
$type: object type
- dbi_set_mode($mode)
DESCRIPTION: sets the mode to NORMAL or INLINE.
RETURNS: Returns current mode (before set).
- dbi_set_debug($debug_mode)
DESCRIPTION: Sets Debug Flag
- dbi_set_web_page($NL)
DESCRIPTION: Sets NEWLINE & controls printing of pre on errors
Do_Time.pm
Misc Time Functions
|
DESCRIPTION
Very simple time functions.
do_time(-time=>secs, -fmt=>formatstring);
do_diff() - pretty print dime differences
Doc.pm
build html documentation
|
SYNOPSIS
Build html based documentation from your perl application using the
perl pod documentation format. The output of this library is a cross
indexed frames based documentation set based on the multiple files
in your perl application (ie. this works on many perl files instead
of just 1).
DESCRIPTION
The user will create a small document generator script (using Doc.pm) which will
specify which files to extract pod from and in what order to do it
(as well as other options). Whenever you wish to rebuild your documentation
set you run the driver program and create them.
FUNCTIONS
- doc_init() - Initialize documentation set.
PARAMETERS: out_dir, source_dir, colorscheme, home_page,
copyright_years, company_name, product_name, color_h1
Starts a frameset that can be referenced via the
file index.htm in the directory you pass as out_dir. This file (index.htm)
contains a master frameset, consisting of three parts:
a page top (top.htm), a table of contents (toc.htm) on the left side,
and a body on the right side (readme.htm). Filenames are fixed.
- doc_navlink() - Add new external link to table of contents.
PARAMETERS: name, link
Places a special hyperlink in the table of contents.
These links are special and will bring up a new browser window.
This is for external links, perhaps to another
set of documentation or to your company home page.
2 breaks appear this after link.
- doc_finish() - Finish / Write up the documentation set.
PARAMETERS: none
Write and close the files opened earlier.
- doc_dir() - Documents a section of data from a files in a directory.
PARAMETERS: files, ignore, dir, section
This is the main function. It documents a section (in the table of contents)
from data in a single directory. By default it includes all files, but you
can specify files with the 'files' parameter and can ignore files with 'ignore'.
The title is 'section' and the directory used is 'dir'.
PARAMETERS DESCRIPTIONS
- source_dir
Source of Folder-Tree input files. These files are required for
javascript. The source dir is an optional parameter. You may think the
documentation looks better if this parameter is not passed :)
- out_dir
Output Directory For the web pages. It actually places stuff in the
html subdirectory of this directory.
- company_name
Your company Name.
- home_page
Your Home Page for links.
- copyright_years
Copyright Notice Years
- indent_level
Default to 1. If this is set to 2 then head2's show up in the
documentation table of contents and head1's are not indented.
If it is set to 1 then head1's in pod files are indented
in table of contents (no head2's). If 0 then all head1's
show up non indented (no head2's).
- product_name
Product Name
- current_section
Section header - goes in table of contents
- color_h1
All first level headings get colored - not just NAME blocks.
- colorscheme
Change the color scheme of the documentation. Currently available color schemes are: DARKRED, PINK, OLIVE, LTBLUE, RED, ORANGE, LTGREEN, DKBLUE, BLUERED, and PURPLE.
NOTES
The documentation shows in a nice 3 pane window. The top pane (top.htm)
will give title info. The left pane (toc.htm) gives table of contents and
navigation information. The right pane (readme.htm) will give documentation
with anchors embedded so the table of contents can work.
Documentation can be built from directories by using the doc_dir function
to read all files for pod documentation. Files can either be in perl
source code (.pl) files or .pod files. Documentation can also come from
files with .htm or .html extensions. These files are parsed so as to
remove everything but the body section.
If reading pod files, the first file is readme.pod. After that
it is alphabetical.
In addition to regular pod documentation, get any documentation between "^# ===" blocks (comments only). If line is of format ^#\s*(\w+)\s*: then word is a heading
Specifically the doc subdirectory will contain README.txt and individual doc pages and the html directory will contain x.html files (from x.pl), and an index.html which is composed of a readme.html and toc.html (table of contents)
CROSSREFERENCE
The application will keep track of any keyword titles (ie items in the table
of contents). When it is almost done, it will rewrite the main page and
replace any words that match the title with self hyperlinks.
EXAMPLE
use strict;
use Doc;
doc_init(
out_dir => '../web' ,
home_page => 'http://www.edbarlow.com',
copyright_years => '1998-1999' ,
company_name => 'IQ Financial' ,
product_name => 'OPERATIONS MGR'
);
# add link to top level
doc_navlink( name=>"Return To Top Level", link=>"../index.htm");
#any pod documents in ../web/pod are in DOCUMENTATION section
doc_dir(
dir => "../web/pod" ,
section => "DOCUMENTATION"
);
# SCREENS section
doc_dir(
ignore => ['func.pl','web_run_cmd.pl',
'web_view_file.pl','web_waitfor.pl'],
dir => "../web" ,
section => "SCREENS"
);
# INTERNALS section
doc_dir(
files => ['func.pl','web_run_cmd.pl',
'web_view_file.pl','web_waitfor.pl'],
dir => "../web" ,
section => "INTERNALS"
);
doc_finish();
GemData.pm
XML Repository Manager
|
DESCRIPTION
XML Repository Manager for the GEM. The G.E.M. uses a file called gem.xml as one of its primary repositories. This data is stored in xml format - and these routines read and write that repository. The data, for clarity, is sometimes saved as gem.dat.
SUMMARY
my $rep = new GemData;
my $rep = new GemData(-file=>Filename);
$rep->dump
$rep->save
$rep->get()
$rep->set()
$rep->survey()
KEYS
The get() and set() subroutines work on a -class / -name / -arg heirarchy. At any level the routines can return a hash of values or a scalar. You set the value by passing in -value=>val. Use the -debug=>1 flag to print debugging messages.
DESCRIPTION
This module provides an interface to an Administrative Database. The G.E.M. can populate this data as can the survey() function of this package.
This database contains information from your run files, interfaces files, and from your sql servers. It will perhaps be expanded to contain information from your unix servers.
AUTHOR
Edward Barlow
mail: edbarlow@hotmail.com
url : http://www.edbarlow.com
All Rights Reserved
TYPES
Data is stored by type. The type indicates the SOURCE of the data. The following types are currently recognized:
- G - General Information (server names etc)
- H - Host specific information (list of files found)
- B - From Backup Server RUN_FILE
- S - From Sybase Server RUN_FILE
- I - From Sybase Server Interfaces File
- M - Space Information
- s - server information (from catalogs)
FUNCTIONS
- $gem_data->fetch_file($ftp,$file,$localname,$filehash,$opt_d,$hostname)
sets $$filehash{$tmp}=1; $$filehash{USED_LOCAL_FILE}=$tmp;
uses the passed in ftp connection
cwd(dirname($file))
unlink $localname
get(basename($file),$localname)
return ($rc, @messages)
- db_open(-dbmname=>filename)
Open a New Database . The name is the root of the dbm file (no .pag/.dir extension. pass -clear to delete data from the dbm database.
- db_close()
Close The database.
- db_param(
-name=>KeyName,
-value=>KeyValue,
-type=>WhereReadFrom,
-server=>ServerName,
-keys,
-dbname=>DbName)
-name: KeyName
-value: if defined then set value, if not then return it
-type: See Type Section Above
-server: server of interest if type B/S or host if type H/I
-keys: if defined returns a list of keys. The keys are returned in
a pipe separated string - type|KeyName|Server|Dbname
-dbname: database name (only for certain key values)
- db_readfile()
Read a file and return a hash of key info. Files may be RUN files or INTERFACE files as per the -type parameter to db_param().
Args
-type=>FileType,
-filename=>FileToRead,
-host=>Hostname,
-orig_filename=>OriginalFilename)
-debug
-localroot the data directory/system_information_data
-type = I (interfaces), Y (environment),
R - From RUN_FILE
B - From Backup Server RUN_FILE
S - From Sybase Server RUN_FILE
# returns a hash # Local_Filename # Hostname
my(%file)= $package->db_readfile(
-type=>"Y",
-debug=>$args{-debug},
-orig_filename=>$curfile,
-filename=>$local_file_list{USED_LOCAL_FILE},
-host=>$args{-name} );
next if defined $file{DONT_USE};
next unless %file;
- db_readserver(
-server=>SERVERNAME,
-login=>LOGIN,
-password=>PASSWORD )
Get Values from a server by connecting and looking in the system catelogs. Results are saved in the database with a key 's'.
KEYS
The following are a list of keys by type of program
- GENERAL (TYPE G)
unix_discover_date
unix_systems
sybase_server
backup_server
- PER HOST (TYPE H) (server should be a unix host)
SYBASE_SRV_LIST List of the Server on this host
Interfaces_File_Id The Id # of the interfaces file
Format File:Count|File:Count...
- RUN_SCRIPT - ALL SERVERS (TYPE B or S)
The following are available for both sybase servers and backup servers
Run_File Path Name To Run File
Sybase_Dir Directory to Sybase (from run file name)
Hostname Host the servers Run File Was Found On
Line_Count Num Non Comment Lines in Run File
Contents Contents of the Run File
type ASE_SERVER or BACKUP_SERVER
- RUN_SCRIPT - BACKUPSERVER - (TYPE B)
Contains the general per server keys plus
Server_Name
Error_Log
- RUN_SCRIPT - SQL SERVER - (TYPE S)
Contains the general per server keys plus
Master_Device
Configuration_File
Error_Log
Single_User_Mode
Master_Mirror_Device
Shmem_Dir
Interfaces_File_Dir
Server_Name
SSO
- INTERFACES FILE - (TYPE I)
$SERVERNAME_## ## is the number of the interfaces file
values are host:port. Duplicate entries in interfaces
file are ignored (last one is used) although a
warning is printed.
- SERVER DISCOVERY (TYPE M)
populated by space_monitor.pl
The following items require a secondary parameter to be passed using the -dbname=>xxx argument
TimeMonitored - a time() value
DbSpaceUsed - last space used (mb)
LogSpaceUsed - last log space used (mb)
DbSpaceUsedPct - last space used (mb)
LogSpaceUsedPct - last log space used (mb)
- SERVER DISCOVERY (TYPE s)
populated by db_readserver()
The following items require a secondary parameter to be passed using the -dbname=>xxx argument
DBoptionsHtml html string of the database options
DBoptions regular string of the database options
DataSpaceByDb data space allocated to this database
LogSpaceByDb log space allocated to this database
DeviceInfo sec param is a sequential number. values are || separated list
of phy,srvr,db,dev,size,alloc,usage
ConfigDefault number is config value. Default for sp_configure value
ConfigName number is config value. Name of sp_configure value
ConfigValue number is config value. Value of sp_configure value
DATABASE OPTIONS (aka sp_dboption)
Offline
OfflineToLoad
NoSepLog
ForLoad
NoChkptRcvry
Suspect
DboOnly
ReadOnly
SelectInto
SglUser
TruncLog
ITEMS WITHOUT DBNAME REQUIRED
BackupServer Name of the backup server
ServerName Name of the local server
BadDatabases space sep list of databases with problems
CharsetDef
Databases space sep list of databases
DateInstalled
NumPgsMb pages per MB
Space_Allocated sum of pages allocated from sysusages
SpaceForServer
Version @@version
Languages space separated list of id of languages installed
Charset space separated list of id of character sets installed
ITEMS WITH JUST A NUMBER INSTEAD OF SERVER
LanguageDef Language name for language id
CharsetDef Character Set name for id
Gem.xml data format
The gem.xml file contains information that the GUI will use and reuse. For example, it contains information regarding the servers and databases that are contained in the system. This information can, however, get out of date, and will be refreshed as needed. That is done by the surveys.
The layout of the file is xml and can be hand edited and viewed. The GemData.pm module manages this file using an interface that looks like:
$package->global_data(-class=>"server", -name=>$s, -arg=>"lastconntime")
The following is a high level view of this xml tree. THis file is more readable than the gem.xml file. You can create your own version of this file in the installer by using the function convert gem.xml to dat.
THE FOLLOWING IS FOR ILLUSTRATIVE PURPOSES ONLY!!! FORMAT MAY CHANGE!!!
'plugin:documenter' => {
'documenter_do_copy' => 'N',
'copy_using_ftp' => 'N'
},
'install' => {
'ENABLE_ORACLE' => 'Y',
'admin_scripts_dir' => 'G:/dist_531/ADMIN_SCRIPTS',
'is_mail_ok' => 'FALSE',
'current_hostname' => 'adwte083',
'ENABLE_SQLSERVER' => 'Y',
'ENABLE_SYBASE' => 'Y',
'isnt' => '1',
'installtype' => 'SAMBA',
'root_dir' => 'G:/dist_531',
'cf_dir' => 'G:/dist_531/conf'
},
'mail' => {
'SMTPMAILSERVER' => 'mail1.mlp.com'
},
'server' => {
'SYBASEDEV2' => {
'state' => 'OK',
'proclib_version' => '6.60',
'database' => {
'tempdb' => '',
'client' => '',
'sybsystemdb' => '',
'imagvue' => '',
'test1' => '',
'tlm' => '',
'clientmlp' => '',
'master' => '',
'sybsystemprocs' => '',
'its_pw' => '',
'shared1' => '',
'model' => ''
},
'server_version' => 'SYBASE 12.51',
'version_poll_time' => '1091468717',
'lastconntime' => '1095353504',
'type' => 'sybase'
},
'ADSRV034' => {
'state' => 'OK',
'proclib_version' => '6.60',
'database' => {
'Northwind' => '',
'tempdb' => '',
'TradeAnalysis' => '',
'pubs' => '',
'master' => '',
'msdb' => '',
'model' => ''
},
'server_version' => 'SQL SERVER 8.00760',
'version_poll_time' => '1091468791',
'lastconntime' => '1091725279',
'type' => 'sqlsvr'
},
'SYBASE1DR' => {
'state' => 'FAIL',
'lastconntime' => '1095353504',
'proclib_version' => '[Can Not Connect]',
'database' => {},
'server_version' => '[Can Not Connect]',
'type' => 'sybase'
},
},
'helpfile' => 'gem.html',
'installsteps' => {
'NEXT_PROCEDURES' => '1094709562',
'VALIDATE_FILE' => '1094709524',
'NEXT_REGISTER' => '1094709493',
'NEXT_SERVER' => '1094709559',
'NEXT_BACKUPS' => '1094709560',
'FINAL_REFORMAT_CODE' => '1095426628',
'VALIDATE_BACKUPS' => '1094709566',
'NEXT_DOCUMENTER' => '1094709561',
'NEXT_WELCOME' => '1095267507',
'NEXT_LOCATIONS' => '1095352025',
'NEXT_PRODUCTS' => '1094709496'
},
'package' => {
'servers.pm' => {},
'numsteps' => '157',
'name' => 'barlow_procedures.pm'
},
'version' => {
'Date' => 'Sep 16 2004',
'Build' => '531',
'VERSION' => 'Build 531 (Sep 16 2004)',
'sht_version' => 'Build 531'
},
'copyright' => {
'notice' => 'copyright (c) 1995-2004 by Edward Barlow'
},
'email' => {},
'administrator' => {
'email' => 'barlowedward@hotmail.com',
'phone' => '555 121234',
'name' => 'Edward Barlow'
}
LogFunc.pm
Parse Log Files For Errors
|
DESCRIPTION
Generic log file filtering library. Can do lots of neat stuff. It is probably not the best way to do it, but it works. Features an optional patern file which can be used to keep track of "recent" changes to the file.
The patern file feature allows you to identify recent changes in your error log. This is optional. The patern file works this way. The first time through (no file will exist), the file will be writen with a byte offset and the text from the last line successfully processed. The next time through, this file can be read and checked to see that the appropriate line exists at the byte offset. This will tell us that the log file has not been overwritten, removed, or whatever. If the line exists at the byte offset, it is assumed that the file has simply been appended to. The search then starts at the byte offset from the patern file. If the string is not at that byte count, the patern file is ignored and the search starts at the beginning of the file.
You may specify an filter file which contains directives on what lines to ignore. Additionally you may ignore lines by using the log_rm_pat function.
SUMMARY
log_filter_file - read a filter directives file
log_process_file - handle an input file and return filtered results
log_rd_patern_file - read patern file
log_wr_patern_file - write patern file
log_debug - set debug mode
log_grep - set paterns that must be in output string
log_rm_pat - this patern should not appear in output
FUNCTIONS
- log_rm_pat
Set paterns to remove from output lines. The lines are not removed, just the patern. The remove paterns should be a pipe (|) separated list. They may contain perl wild cards.
- log_grep(search_patern=>pat,today=>1|0,yesterday=>1|0,date_fmt=>fmtstr)
ARGUMENTS: "search_patern" "today" "yesterday" "date_fmt"
Set information that the output must contain. This can be either based on dates (using today/yesterday with date_fmt) or explicitly. The Search Patern Instructions are a pipe separated list of strings (format a|b|c). Date Format is parsed as follows:
mm 1-12 month
yy 99,00,01 year
dm 1,9,10,13 day of month
dd 01,09,10,13 day of month
mon Jan Feb... month
Input Arguments
search_patern - grep paterns in addition to date filters
today - if defined do today
yesterday - if defined do yesterday
date_fmt - search string format for dates
- log_debug
Sets debug flag. Only run if you want debug messages shown.
- log_filter_file(file=>filename)
Input Arguments
file - patern file to write
Read filter instructions from filename
- log_process_file(file=>input_file,ignore_blanks=>1, search_patern=>patern, byte_offset=>byte_offset_for_pat, max_lines=>max_output_lines, cat_nogrep=>1)
Input Arguments
file - input file to read
ignore_blanks - ignore blanks if defined
search_patern - search patern of last line read
byte_offset - byte offset to start search of search_patern from
cat_nogrep - lines that dont pass grep pass are appended to prior line if the prior line passed all tests. This can join things like deadlock info that spans multiple lines
max_lines - max output lines
Output Parameters
$num_rows_read - rows read
$num_rows_returned - rows filtered
$found_input_patern - did you find the input patern
$lastline_read - can be used as patern for next search
$byte_count - byte count of this last line
@output - filtered output
Filter a File. Returns (num_rows_printed,num_rows_read,found_patern,returned_patern,byte_cnt,@output)
- log_rd_patern_file(file=>filename)
Input Arguments
file - patern file to write
Read a patern file. Returns byte count and start patern.
- log_wr_patern_file(patern=>pat,bytes=>bytes,file=>filename)
Input Arguments
patern - line on the file
bytes - byte count of last read line
file - patern file to write
Write out a patern file.
Notes
The exclude files use a simple syntax...
PATERN=[perlpat] EXCLUDE=[string to exclude]
Logger.pm
master message handler
|
SYNOPSIS
Logger.pm allows you a variety of utility functions to log messages approrpiately according to arguments you have passed in to the logger_init() function. These directives allow you to specify files to log to as well as potential email addresses to send stuff to.
LOGGER OPTIONS
The Arguments passed to logger_init() define the process.
-debug do you wish to see debug messages (1 or undef)
-logfile a log file
-errfile an error log file. removed at process end if empty
-database a database name for error messages
-command_run the current command being run with arguments
-mail_host a mail server/host for mail messages
-mail_to comma separated list of mail targets for errors
-success_mail_to comma separated list of mail targets for success
-success_subject subject line for successes
-fail_subject subject line for fails
logger_init() options for Ed Barlow Scripts
-debug optional
-logfile $opt_l
-errfile $opt_e
-database $opt_d
-command_run $CONFIG{COMMAND_RUN}
-mail_host $CONFIG{MAIL_HOST}
-mail_to $CONFIG{MAIL_TO}
-success_mail_to $CONFIG{SUCCESS_MAIL_TO}
FUNCITONS
logger_init()
logdie(@msgs)
infof(fmt,msg)
info(@msgs)
debug(@msgs)
alert(@msgs)
warning(@msgs)
bad_email(@msgs)
ok_email(@msgs)
Priority order is
debug() < info() < alert() < logdie()
ROUTING
The following maps functions to actions.
HANDLER MIN LVL MAX LVL
screen1 info critical print to screen normal msgs
screen2 debug debug debug messages printed only if -d
file1 info critical log file - normal messages
errfile1 error critical error file- for warnings and up
emailok alert alert use alert level for ok emails
emailbad emergency emergency use emergency for failures
MlpAlarm.pm
Alarming And Monitoring
|
DESCRIPTION
This perl module provides a generic mechanism to manage alarms and monitoring. The tool is distributed as a perl module with several associated programs (a web based GUI, an alarm router, and some monitoring programs). The library contains several simple functions to monitor your systems and some back end functions used by the reporting user interface. Alarm data is stored in a database (Sybase or SQL Server).
SUMMARY
MlpAlarm provides a simple mechanism to manage alarming and reporting. Functions use a by name interface with consistent parameters for simplicity and ease of use. It has the following features
The system supports the following types of "data"
- Heartbeat Data
Heartbeats are frequent up/down type messages regarding state. Examples of programs that generate heartbeats include ping and a database disk space monitor which alarms based on space used. Heartbeats are saved with a -severity argument which can be EMERGENCY, CRITICAL, ERROR, WARNING, or OK. Because we expect heartbeats frequently, it is considered a problem if a heartbeat is not generated in a timely manner. Heartbeats are stored using the MlpHeartbeat() function. The system does not keep track of historical Heartbeat information.
- Batch Job Data
Batch jobs typically run infrequently but regularly. They can thus be treated as Heartbeats with a low frequency. The system identifies batch jobs by the -batchjob argment to MlpHeartbeat. Because some batch jobs have a frequency as low as once per month, it is not considered a warning when a Heartbeat message is not generated in a timely manner.
Because the system does not care how long it is between batch job heartbeats, heartbeat messages for batch jobs may include three states in adition to the normal Heartbeat states. These are "RUNNING", "NOT RUN", and "COMPLETED". Batch jobs, when started, should set their state to RUNNING, and when finished should set their state to COMPLETED (which is the same as OK) or one of the error states.
There are several convenience functions starting with MlpBatch...() that can be used to store Batch Job data. These routines are simple wrappers on MlpHeartbeat().
- Event Data
Events are incidents on our systems for which we care about the time they occurred. Event logs for your servers are an example. Because we care what time they occurred, The system keeps a history of all the events you have saved and a cleanup program must be run to purge this data. Events are stored using the MlpEvent() function.
- Performance Data
Performance data can be stored in free form data for use by graphics functions. The use of performance data is not implemented yet. Performance data will be stored using the MlpPerformance() function
Fundamentally, from the perspective of a user of this module, the system consists of 3 functions named MlpHeartbeat, MlpEvent, and MlpPerformance. These functions can be considered Black Boxes to transmit, store, and route your messages appropriately.
THE GORY DETAILS
System/Subsystem Values
Everything monitored is keyed by monitoring_program, system and subsystem. A Systems is a hardware or software component. Subsystems refer to individual parts of those systems (disks, logs etc). If you are monitoring batch jobs, the system refers to a logical group of batch jobs, while the subsystem refers to the step.
Containers
When you view the data, you view it by Containers, which are groups of systems. The user interface supports a mechanism to create and manage your "Containers". An example of containers are PRODUCTION, DATABASES, or UNIX. This allows different users to see only the subset of systems they are interested in.
State/Severity Values
Key to the system is the state and severity levels. Message routing will be based on a combination of the key (monitoring_program/system/subsystem) and this value.
The following are legitimate heartbeat states
- EMERGENCY = system down / critical failure
- CRITICAL = serious problem.
- ERROR = non fatal error possibly requiring administrator attention
- WARNING = non fatal warning.
- INFORMATION = a simple message. Synonym for OK.
- DEBUG = messages only of interest to developers
Additionally, batch jobs may also be
- STARTED = the job has started
- COMPLETED = the job has completed normally
- NOT_RUN = the job has not started (default state)
If a batch job aborts/fails, the status should not be COMPLETED (it should be one of the other states from above). Note that you can have the batch job submit many RUNNING heartbeats, with different message texts, to identifying the exact position in the batch.
Monitoring api
MlpHeartbeat()
Heartbeat message. A heartbeat message may require attention but the system does not keep heartbeat history. Ping is an example of a heartbeat message.
Requried Arguments: -state, -monitor_program -system
-state=>[STARTED, COMPLETED, RUNNING, EMERGENCY, CRITICAL, ERROR, WARNING, INFORMATION, DEBUG]
Optional Arguments: -debug -subsystem -message_text -document_url -batchjob
-batchjob => this is a batch job - so value is not going to be refreshed frequently
-event_time => valid sybase date time format - usually can be ignored
MlpPerformance()
All arguments to this call, which records system performance data, are optional. Obviously, at least one value should be passed into the routine to make any logical business sense.
Required Arguments: -monitor_program, -system
Standard Optional Arguments: -debug -subsystem
Optional Arguments: -debug -monitor_program -system -subsystem -value1 -value2 -value3 -value4 -value5 -value6 -value7
MlpEvent()
MlpEvent saves Events, which are monitioring messages where history may be of interest. Application errorlogs are examples of events.
Required arguments;
-message_text=>[text string]
-severity=>[EMERGENCY,CRITICAL,ERROR,WARNING,INFORMATION,DEBUG]
-system=>[system being monitored]
-monitor_program=>[program name. Default is basename($0)]
-severity
Optional arguments:
-subsystem=>[subsystem being monitored]
-debug
-event_id=> 0
-message_value=> 0
-message_text
-document_url=> 0
-event_time=>[timestamp of event in sybase format. Default to now]
-save_syslog= 0|1 - save event using syslogd if on unix
-save_dbms = 0|1
Batch Job Convenience Functions
Batch jobs in the system are treated as a special case of Heartbeats. You *could* write your manager using a heartbeat fore each batch, or you can use these convenience functions.
4 functions are provided as simple wrappers to the MlpHeartbeat function for use by batch jobs. These functions are MlpBatchStart, MlpBatchRunning, MlpBatchDone, and MlpBatchErr. Funcamentally, when your batch or monitoring job starts, you call MlpBatchStart and you finish with a call to MlpBatchDone or MlpBatchErr. If your job runs for a while (or continuously), you can use MlpBatchRunning to indicate that the batch is still alive.
- MlpBatchStart()
This function identifies that a program has started. The program should be passed either -name or -system (they are synonyms) and the -batchjob flag. If you are using multiple occurances of this program to check multiple systems, you should identify the system monitored with the -subsystem parameter. If you are running a batchjob, you should also pass a name for the batch job with -monitor_program. Finally you can pass in an optional -message.
Additionally, if this is a -batchjob, you may specify -step to indicate which step this subsystem is numbered and -reset_status to clear times.
example
MlpBatchStart(-monitor_program=>"NightlyCopy", -name="IMAGSYB1", -batchjob=>1);
- MlpBatchStep
This function takes a required -stepname and -stepnum and optional -message. The
step name and number are saved so the next call to MlpBatchDone/MlpBatchErr will know where you are at. The -stepname is considered a -subsystem and a heartbeat is saved with a state of RUNNING
- MlpBatchRunning()
This function just saves a heartbeat in the system so you can see that your batch or monitoring job is working.
example
MlpBatchRunning()
MlpBatchRunning(-message=>"at step number 3")
- MlpBatchDone()
The batch has completed. Required -monitor_program and -system. Optional -name -debug -subsystem -message -stepnum.
- MlpBatchErr()
These two functions indicate the completion of your batch or monitoring job. They also use the same arguments as above, although you probably also want to pass a -message if the job is in error.
example
MlpBatchDone()
MlpBatchErr(-message=>"Cant Connect To The Server")
Monitoring reporting
The reporting functions are pretty for developer internal use and are simply listed here for completeness:
- MlpGetCategory()
Args: -user => username, -debug
Get report category code
- MlpGetScreens()
Args: -user=>username, -category=name, -debug
Get screens viewable by a user
- MlpGetReportCode()
Args: -user=>username, -screen_name=name
Get Report type code
- MlpRunScreen()
Args: -screen_name=name, [-container=name], -system, -program, -debug
MlpRunScreen() returns an array of pointer to arrays. You can
override your predefined containers or just use the normally set up ones. You can pass -NL to define newline characters for debug messages
- MlpGetContainer()
Args: -name=name, [-type=(s)ystem|(c)container], -user=>username, -debug=>[1|0], -screen_name=>name
Fetch a list of systems and containers
- MlpGetDbh()
Returns the DBprocess handle currently in use (shouldnt be needed)
- MlpGetProgram()
Gets a list of monitoring program information
- MlpGetSeverity()
Retrieves a list of severities
- MlpManageData()
Administrative interface to the system
- MlpGetOperator()
Returns operator information
Monitoring coding
Example 1. Write Event Log
The following example writes an event message. Note that the monitor program name will be determined from the current program name, and the system the event is for will be determined by hostname():
#!C:\Perl\bin\perl.exe
use lib 'G:/ADMIN_SCRIPTS/lib';
use strict;
use MlpAlarm;
MlpEvent( -severity=>"INFORMATION",
-message_text=>"Test Message",
-system=>"test");
Example 2. A Simple Monitor
The following example monitors something...
#!C:\Perl\bin\perl.exe
use lib 'G:/ADMIN_SCRIPTS/lib';
use MlpAlarm;
MlpBatchStart( -system=>"TaQ",-subsystem=>'Nyse',-monitorjob => 1 );
if( ! connect($SERVER) ) {
MlpBatchErr( -message=>"Can Not Connect To DB $SERVER: $text" );
MlpHeartbeat( -system => 'TaQ', -subsystem => 'Nyse',
-state=>"ERROR", -monitor_program=>"TaqMonitor",
-message_text=>"Can Not Connect to Taq/Nyse");
die "ERROR - Can Not Connect to Data Source TaQ";
}
while( 1 ) {
my($rc,$text)=monitor_taq($SERVER);
if( $rc eq "ERROR" ) {
MlpHeartbeat( -state=>"ERROR", -debug=>$opt_d, -system=>"TaQ", -subsystem=>"Nyse",
-monitor_program=>"TaqMonitor", -message_text=>$text);
} else {
MlpHeartbeat( -state=>"OK", -debug=>$opt_d, -system=>"TaQ", -subsystem=>"Nyse",
-monitor_program=>"TaqMonitor", -message_text=>"Server Ok: $text");
}
sleep(300);
MlpBatchRunning(-message=>'still working')
}
MlpBatchDone(-message=>'completed normally');
Example 3. A Complex Multistep Batch
Let us assume that we have a batch job called Nightly that is composed of 6 named steps. We would like to see the state of this batch in the appropriate order and would like to reset the state of the subbatches when we start. This way we can see progress. So... we should *always* see 6 substeps plus an overall step when we look a the Heartbeat table. When the batch starts, everything gets marked "not run". When steps get run their status gets updated.
The way we do this is to use our convenience functions. Technically, the master heartbeat differes from that of the steps as it has no -subsystem while the steps do. But they are connected - they share the same other information. The Master row state will be set to RUNNING at the start. This row will have its timestamp updated when any MlpBatchStep row is run. It will also have its message updated to be the last message saved by any of the -step functons. Note that this means that failed substeps where the program continues will result in a progression like (state=RUNNING msg="Running Step 1 : Init") to (state=RUNNING msg="Step 1 Failed") to (state=RUNNING msg="Running Step 2 : AlphaSetup") in short order. You must track final state and write that with MlpBatchDone/MlpBatchErr as normal.
# start up our program, clear the states of all the jobs
my($finalstate,$finalmsg)=("OK","Job Complted Successfully";
# start our batch named Nightly and reset all associated rows
MlpBatchStart( -system=>"Nightly",-batchjob => 1, -reset_status=>1 );
$rc=connect();
if( $rc eq "FAIL" ) { # Fail the whole batch...
MlpBatchErr( -message=>"Can not Connect");
die "Done - Error Can Not Connect";
}
# Step 1 - changed to RUNNING and then to COMPLETED or ERROR
MlpBatchStep( -stepname=>"Init",-stepnum=>1);
$rc=init();
if( $rc eq "FAIL" ) {
MlpBatchErr( -message=>"Step 1 Failed $!", -stepnum=>1 );
($finalstate,$finalmsg)=("ERROR","Step 1 Failed $!");
} else {
MlpBatchDone( -message=>"Step 1 Completed Normally", -stepnum=>1 );
}
# Step 2
if( $finalstate eq "OK" ) {
MlpBatchStep( -stepname=>"AlphaSetup", -stepnum=>2 );
$rc=AlphaSetup();
if( $rc eq "FAIL" ) {
MlpBatchErr( -message=>"Step 2 Failed $!", -stepnum=>2 );
($finalstate,$finalmsg)=("ERROR","Step 2 Failed $!");
} else {
MlpBatchDone( -message=>"Step 2 Completed Normally", -stepnum=>2 );
}
}
# Step 3 - A long Running step
# changed to RUNNING and then the timestamp is updated every 100 second
# loop and finally to COMPLETED or ERROR
if( $finalstate eq "OK" ) {
MlpBatchStep( -stepname=>"AlphaRun", -stepnum=>3 );
while($i<100) {
sleep(100);
$rc = itterate();
last if $rc eq 'FAIL";
MlpBatchRunning(-message=>"step 3: completed $i/100", -stepnum=>3);
$i++;
}
if( $rc eq "FAIL" ) {
MlpBatchErr( -message=>"Step 3 Failed at part $i: $!", -stepnum=>3 );
($finalstate,$finalmsg)=("ERROR","Step 2 Failed at part $i $!");
} else {
MlpBatchDone( -message=>"Step 3 Completed Normally", -stepnum=>3 );
}
}
if( $finalstate eq "ERROR" ) {
MlpBatchErr( -message=>$finalmsg );
} else {
MlpBatchDone( -message=>$finalmsg );
}
Monitoring notes
The following are paths and perl versions that are known to work with this lib.
- NT
With G: mapped to /samba/sybmon
#!//adcluster300/tibco/perl/bin/perl.exe
use lib 'G:/ADMIN_SCRIPTS/lib
- Solaris
#!/usr/local/bin/perl-5.6.1
use lib '/apps/sybmon/ADMIN_SCRIPTS/lib';
- Linux
#!/usr/local/bin/perl-5.8.2
use lib "/apps/sybmon/ADMIN_SCRIPTS/lib";
FEATURE HEARTBEAT
The MlpHeartbeat() function has been modified to provide true heartbeats. Simply pass in an appropriate set of
core information (monitor_program,system,text...) and the argument -heartbeat=minutes and a record will be placed
that has been "REVIEWED" for getdate()+minutes. If no new "heartbeat shows up", an alarm will be sent whenever
it expires!
MONITORJOB / BATCHJOB
In addition to Heartbeats and Events, the system will handle batch jobs and agents. Agents are the
programs that collect Heartbeats and Events. Agents are stored with by setting -monitor_program=>1
in the functions. This saves heartbeat data with batchjob=AGENT. Batchjobs are considered all
data with batchjob!=AGENT but not null. The functions MlpBatchStart, MlpBatchDone, MlpBatchErr,
and MlpBatchRunning and MlpBatchStep.
Plugin.pm
Base Class For GEM Plugins
|
USAGE
This Document Describes how plugins work and how to write them.
Plugins are the objects within the generic enterprise manager that perform all the functionality. This class provides core functionality and is inheirited by .pm files that reside in the plugins subdirectory. This is the documentation on how to write a plugin. It is stored in Plugin.pm.
SYNOPSIS
Generic Enterprise Manager plugins are written to provide users features through the GEM. A plugin is a perl module (extension .pm) that inheirits from the base class Plugin. The .pm file and a .xml file which identifies associated data (author, copyright notice...) are placed in the plugins subdirecory of the application where they will automatically be loaded at run time. Plugins should conform to this specification. If a plugin does not compile, it not loaded at run time ( you will see error messages ). Plugins are called by and run from the PluginManager module.
THE APPLICATION
The application behavior is govened by the top level flags in the driver. The main flags are --NOMSGTAB which (if set) removes the 'application' and --NOSIDEBAR which moves the left side explorer bar.
The application in general consists of several things: a menu bar, a left side explorer bar with associated exp navigation buttons, and a right side results bar. If the --NOMSGTAB is not set, then the right side will be a notebook frame with a few default windows.
TOP OF FILE
It is recommended that the top of a plugin file named xyz follow the following template:
package xyz;
@ISA = qw(Plugin);
use strict;
use vars qw($VERSION);
$VERSION = ".01";
BOTTOM OF FILE
As with all perl modules, the plugin must return a 1 and of course you are encouraged to embed embed perldoc documentation after that line.
1;
__END__
=head1 NAME
eventviewer.pm - Module for viewing events
=head2 DESCRIPTION
The event viewer can be viewed as an example plugin.
etc...
OTHER FUNCTIONS
After that, the plugin should contain subroutines that override the subroutines in its parent Plugin.pm. These will be used to define user interface elements and to handle functionality. You can create and paint a notebook tab if you wish to use one. You can create explorer buttons (lower left side), bitmaps for the upper left side, can add items to the main explorer tree, and can create the functionality that occurs when you right click items on an element of that tree. You can also create menu items for the menu bar. The heirarchy is that the explorer buttons, when clicked, will populate the explorer tree. The tree is painted and right click items added to elements. When a user selects an element on this tree, selects a menu item, or right clicks on one of the right click items, a call back to event_handler() will be performed.
PLUGIN BUILTIN FUNCTIONS
This section lists functions that your plugin must NOT override. These are automatically called from GEM. In other words... theses functions should not be defined by the plugin.
- new - called by PluginManager
- initialize - called by PluginManager
PLUGIN UTILITY FUNCTIONS
The following functions are available to you to use in your plugin:
- $plugin->refresh_tree - refreshes the left side window tree. called natively when the exp buttons are pushed
- $plugin->messageBox(-message=>$str, -title=>$ttl)
Calls a messageBox($str)
- $plugin->DialogBox - return a DialogBox(@_) using normal DialogBox arguments
- $plugin->make_button()
- -widget=>$frame
- -text=>$bstr
- -help=>$help_string
- -command=>$func
- $package->clear_tab($tabname)
$current_main_frame = $package->clear_tab($tabname);
Clears the notebook tab named by $tabname. The cleared frame is then raised and returned to the calling program and can be used as a base frame.
- $package->global_data()
calls gemdata->global_data() to get/set values from the gem.xml configuration file
- $package->show_html()
show a html frame
- $package->unimplemented()
pops up a dialog box that says ... unimplemented...
- $package->write_XMLDATA()
save the globaldata() if needed
- $package->get_last_event_info()
- $package->ignore_events()
- $package->browse()
- $package->get_CONFIG()
PRINT FUNCTIONS
You also have 3 print functions.
- $package->statusmsg(@msg)
a normal/status message that will print to the console, log, and logfile
- $package->notifymsg(@msg)
a status message that will not print to the console
- $package->debugmsg(@msg)
a debug message that will print to the log and console if --DEBUG passed and will always print to the logfile
The following example line will set the statusbar and print to stdout
$package->statusmsg( "[navigator.pm] menuclick($menuitem)\n" );
PLUGIN CALLBACKS
The callbacks define the look and feel of the application. The buttons on the lower left side determines which tree is selected in the explorer type menu above it. This function returns an array of buttons to place in that corner.
- $package->init()
This user defined function will be called to initialize the plugin during startup
- $package->event_handler()
This function takes an event and processes it. The event are categorized. The -eventtype argument defines what type of event is being sent. The following list describes the options that each eventtype can have. Note that the one confusion here is the difference between a tab and a page. A tab is the high level notebook tab (monitoring, log, welcome...). A page is a screen within the tab. Im not really sure how to work pages - how to navigate on them. But the idea is that you have a fixed number of tabs and rather than requiring each plugin to create their own, the plugins can share the tabs. This will make things less crowded.
| EVENT TYPE | ARGUMENT |
| menu | -menuitem |
| tabchange | -oldtab -curtab |
| pagechange | -oldpage -newpage |
| treebrowse | -entrypath -curtab1 |
| treertclick | -entrypath -clicktext |
| expbutton | -context |
| imgbutton | -text |
- $package->getExplorerButtons()
return a hash of buttons that will go in the lower left corner.
- $package->getMenuItems()
Returns an array of menu items (slash delimited) to be displayed in the menu bar. If the parents for the menu item do not exist, they will be created. Thus, if you return /a/b/c you will get 'a' on the menubar and b on its submenu. Placing the mouse on b will show a further submenu of c.
- $package->getPluginPanes($package)
Defines the tabs the plugin wishes to create. The tab names are based on the keys returned in a hash. and the values indicate pointer to functions to run when the tab is raised
- $package->menuclick($package,$Frame,$entryPath)
This function is called with the full path name to the menu (see getMenuItems) when a user clicks on a menu item.
- $package->getTreeColorFunc($package,$curTreeType)
Return function pointer to colorize the tree
- $package->getTreeItems($package,$curTreeType)
Return an array of Tree Items for the current tree type. The tree type is related to the explorer button that is pressed and this function is called every time you press one of these buttons. You should obviously test for tree type and not return anything if the tree type is not of your creation.
- $package->getBitMaps($package)
Called on initialization to get bitmaps that might want to show in upper left side of window
- $package->bitmapclick($package,$Frame,$entryPath)
Called when the bitmap is clicked.
- $package->getTreeRtclk($package,$curTreeType,$treeitmptr)
Native callback that allows you to add right click items in the current tree. Basically you get a tree type in $curTreeType and a pointer to an array of items in the tree ($treeitmptr). You return an array of arrays where the outer array matches the items in $treeitmptr and the inner array is a list of the popup right clicks.
- $package->rtclick($package, $entryPath, $clktext)
This function is called when a user selects a right click item. The entry path is the full path to the item and will match that which was specified in getTreeRtclk. The clktext is the subitem on that menu that was clicked.
PLUGIN DOCUMENTATION
Plugin documentation is contained in an xml file in the plugins directory that has the same root name as the .pm file. I suggest you browse a few of them for functionality.
<package name="MDA_tables" version=".01">
<copyright type="gpl" key="" expires="never" notice="copyright (c) 2005 by edward barlow" />
<help_url>http://www.edbarlow.com/plugins/MDA_tables.html</help_url>
<long_description>Monitoring Table Viewer</long_description>
<short_description>Monitoring Table Viewer</short_description>
<author_name>Edward Barlow</author_name>
<author_mail>barlowedward@hotmail.com</author_mail>
</package>
Event Functions
GEM communicates with the plugins using the function $pluginname->send_event(%args). This function sends the event to each event_handler() function in loaded plugins. These functions, on a plugin by plugin basis, will handle the event.
Fixed Reactions
Clicking on the buttons in the lower left corner will always redraw_tree() in addition to anything else you want it to do.
PluginManager.pm
plugin manager
|
USAGE
PluginManager manages plugins. It is the interface between the GEM and the plugins.
FUNCTIONS
new( %args )
reads all plugins from plugins subdirectory and import()'s them and then runs
new() on each. Also reads .xml files in this directory and saves data.
plugin_names() - returns names of the plugins loaded
menuclick($pluginname,$frame,$txt)
runs plugin->run($frame,$txt) where frame is the appropriate
frame to run in and $txt is the text of the menuitem
initialize(%args)
foreach (plugin) { run plugin->initialize(%args) }
GetExplorerButtons()
foreach (plugin) { push @x,plugin->GetExplorerButtons() };
return @x;
GetMenuItems(%Items)
foreach (plugin) { @x=plugin->GetMenuItems(%args);
foreach (@x) { $Items{$_} = $plugin_name
}
getExplorerBaseItems()
foreach (plugin) { push @x,plugin->GetExplorerButtons() };
return @x;
getTreeItems($tree)
push @treeitems,"/"; push @treertclk,\@dummy;
foreach (plugin) {
($treeref,$treertclref)=plugin->getTreeItems(%args);
push @treeitems,@$treeref; push @treertclk,@$treertclkref;
}
return \@treeitems,\@treertclk
browse($frame,$entrypath)
get plugin from saved values for $entrypath
$plugin->browse(frame,$entrypath)
plugin_data($pluginname)
return $VERSION, $shortdescription, $longdescription from plugin
plus { $xml_by_plugin{$pluginname} }
plus filename,filedate,filesize
in a hash
get_bitmaps()
return( \@ids, \%bitmaps, \%bitmaptext, \%baloontext)
Repository.pm
Customizable Server/Password Repository
|
SYNOPSIS
# Get Password For Particular Server
($login,$password)=get_password(-type=>"sybase", -name=>"SYBPROD")
# Work on all Sybase Servers
use Repository;
@servers=get_password(-type=>xxx,-name=>undef)
foreach (@servers) {
($login,$password)=get_password(-type=>xxx, -name=>$_)
...
}
# Get Unix Servers
use Repository;
@hosts=get_password(-type=>"unix", -name=>undef)
# Get information on particular server
%info_about_servers=get_password_info($server)
DESCRIPTION
This basic module should be extended to allow encryption. For now it
allows you to get passwords from a file for your application through a standard
interface that can be enhanced to meet your security concerns.
Two files are required for this module to work. The first file is a
configuration file that identifies the password information. This file
must exist in the current directory (checked first), or in one of the
directories in your perl library include path. The file name is
sybase_password.cfg by default.
The password file is user definable but needs to follow the following rules:
lines starting with # are ignored
lines starting with any white space are informational and can be
returned with the get_password_info function.
Normally, the password file should be named password.cfg in the current
directory and have the format
SERVERPASSWORDLOGIN
KEY=VALUE
KEY=VALUE
SERVERPASSWORDLOGIN
KEY=VALUE
KEY=VALUE
If your password file is of a different format, or you are using a differently
named password file, you need to define a configuration file (default
sybase_password.cfg). This file should be of the format:
PASSFILE=passwords
SERVER_COL=0
LOGIN_COL=1
PASS_COL=2
get_password_info returns lines that start with spaces
MONITOR SERVERS
Sybase Monitor servers behave slightly differently. These servers are stored in monitorserver.dat and represent
a map of monitor server -> sybase server. When you run get_password(-type=>monitor_server) you get a hash with
keys of MONITOR.$MON_SERVER or HISTORICAL.$HIST_SERVER and values of the ASE Sybase SQL Server associated with the
monitor server. When you run get_password(-type=>monitor_server,-name=XXX_MON) you recieve the login and password information
for the sybase server associated with that monitor server...
RosettaStone.pm
A Rosetta Stone For Database Administration Commands
|
DESCRIPTION
The Rosetta Stone provided translations between ancient languages. This
Rosetta Ston provides translations between database administration commands.
There are a variety of modules that deal with application sql, this module
concentrates on system level sql. Because concepts in system design vary
greatly between databases, not all reports will look identical, and some
reports may not even be available or relevant on some target database systems.
This module uses DBI for connectivity. It uses a combination of internal DBI
function calls and its own direct SQL calls to provide a uniform interface.
The user is responsible for providing a valid DBI connection to these routines.
FUNCTIONS
This module has 3 functions.
- get_system_info()
returns information about
a system, server, database or whatever the terminology to call the highest level database "thing"
might be. Typical reports might include "options", listing system options, "devices", listing files
or partitions the system uses, "schemas", which will describe databases/schemas in the system,
and "logins", listing system users.
example reports : *:file:hash returns a hash of the following keys
NAME SQLSVR SYBASE ORACLE
database Y
name Y Y
phys Y Y
size (MB) Y Y
alloc (MB) Y
free (MB) Y
maxsz Y
growth Y
status Y
- get_schema_info()
returns information about a tablespace, database, or whatever
the primary unit of partitioning of the "thing" might be. Typical reports might include
"tables", "procedures", "properties".
- get_object_info()
returns information about objects within a schema. Typical reports might include "ddl", which would
return DDL create statements and "help" which would summarize the object.
Because of the differences in terminology, the high level "thing" will
henceforth be referred to as a system, the partitions will be schemas, and objects will of course be
referred to as objects.
FUNCTION OPTIONS
The following arguments will be provided to all functions unless noted.
- -connection
This required argument is DBI connection. Queries will be run on this
connection
- -db_type
This represents the DBI type of the connection. Possible values are ODBC,
Sybase, Oracle
or any other DBI server type.
- -reportname
This represents the name of the report you wish to run.
The special reports "allreports" and "objreports" returns an array of allowed reports. if a -db_type
is passed, it returns only reports allowed for that -db_type. if it is not passed,
it returns an array of all reports. If the report is special, an array will
always be returned.
- -debug
The -debug item allows optional printing of diagnostics. It is a pointer to a function, not a
true false argument. Thus, use -debug=>\&print, to get prints to work.
- -schema
The schema, database, or tablespace of interest. Not allowed on get_system_info()
- -object
The object of interest. Only allowed for get_object_info()
- -returntype
The -returntype value may be the string "hash", "keys", "ddl", or "report". if
"hash", a hash is returned. This
hash will be compatible with XML::Simple. if report or ddl, then the return will
be a single string, with
appropriate new lines, columns justified, and a header. This report is
suitable for printing to standard output.
if "keys", then the report will be an array of keys.
ddl is, of course, only appropriate if a specific object is selected.
Return Values
The return value for the function is dependant on the -returntype argument. If
-returntype is "hash", a hash is returned, if "keys", an array, and if "report", a
scalar.
The return value will be undef if an error is encountered, and the function get_error_info()
can be called with no arguments to return the error string.
RunCommand.pm
Architecture Independant External Command Execution
|
DESCRIPTION
This is an attempt at an architecture independent mechanism to run external commands.
On Win32 Architectures, Spawn a separate process window. On unix, run
job in the background window with a fileevent manager. This is only
useful in a Tk architecture.
USAGE
RunCommand(-key=>value...);
-cmd - The system command to run. If the first word in the command ends in .pl, then the
current version of perl will be prepended to it
-err - prefix for alarm messages
-mainwindow - main window - if you pass this an error box will appear if
the command errors out
-printfunc - optional function ref to print ouput messages.
-printhdr - prefix for -printfunc commands
-title - window title
-statusfunc - function ref to print status messages to.
-showinwin - if defined it will create an output window with the results
will use -title||-showinwin for the title
will ignore output lines matching -ignore_string
get_win32_disks($system)
returns an array of disks
FLOW
-statusmsg version info
-statusmsg $cmd without password
if ! open( CMD )
print debug: ...
-mainwindow -> messagebox() if -mainwindow
foreach <results>
-printfunc( -printhdr.$_
push @output,$_
if $?!=0 # command returncode
messagebox ( -err.msg.$cmd_no_pass.@output )
return (0,\@output)
if -showinwin
NOTES
If the command is a perl command, the current running perl will be used
Returns two args - $status, $outputref. $status is 1 for success and 0 for failure. $outputref is a ptr to an array of return data.
UpdFunc.pm
Functions to update directory trees
|
DESCRIPTION
FUNCTIONS TO UPDATE AND MAINTAIN DIRECTORIES
SUMMARY
This library consists of three functions. The dirupdate() function will update common files in directories to the most recent version. The dircmp() routine will compare 2 directories in the same manner as does dircmp(1). The dircopy() makes a target directory EXACTLY like a source directory.
FUNCTIONS
- dirupdate()
Update files between directories to the most recent file. An Output file of copy commands is created. This is useful to maintain releases when development is being handled in more than one subtree.
- dircmp()
Compares directories. Works with the same parameters as the above routine.
- direxact()
Copy Files between different directories from a source directory. An Output file of copy commands is created.
SRC_DIRECTORY - only set on call DIR FNAME EXT DEST_DIRECTORY - destination directories DEBUG
Win32Scheduler.pm
Scheduling Module For Windows and Unix
|
DESCRIPTION
This module can set schedules for batchs on unix and windows. The information as to what you wish to schedule is saved in the gem.xml configuration file.
This module is acutally very simple. It only allows one time schedule (trigger) per job and only permits jobs to run under some very basic criterion.
FUNCTIONS
get_a_task -
-name => task name
get_all_tasks -
schedule_a_job
-name
-schedule hourly, weekly, daily, boot
-account
-password
-program the program you wish to run
-directory working directory
-start_hour
-start_minutes
the following only apply to the hourly schedule and are optional
-end_hour
-end_minutes
-frequency
new
argument : -name_prefix=>prefix : this prefix applies to all jobs you care about. This can be
used to ignore other scheduled jobs that are on the system. If -name_prefix=>xx_,
then only jobs starting with xx_ will be considered
Doc.pm
build html documentation
|
SYNOPSIS
Build html based documentation from your perl application using the perl pod documentation format. The output of this library is a cross indexed frames based documentation set based on the multiple files in your perl application (ie. this works on many perl files instead of just 1).
DESCRIPTION
The user will create a small document generator script (using Doc.pm) which will specify which files to extract pod from and in what order to do it (as well as other options). Whenever you wish to rebuild your documentation set you run the driver program and create them.
FUNCTIONS
- doc_init() - Initialize documentation set.
PARAMETERS: out_dir, source_dir, colorscheme, home_page, copyright_years, company_name, product_name, color_h1
Starts a frameset that can be referenced via the file index.htm in the directory you pass as out_dir. This file (index.htm) contains a master frameset, consisting of three parts: a page top (top.htm), a table of contents (toc.htm) on the left side, and a body on the right side (readme.htm). Filenames are fixed.
- doc_navlink() - Add new external link to table of contents.
PARAMETERS: name, link
Places a special hyperlink in the table of contents. These links are special and will bring up a new browser window. This is for external links, perhaps to another set of documentation or to your company home page. 2 breaks appear this after link.
- doc_finish() - Finish / Write up the documentation set.
PARAMETERS: none
Write and close the files opened earlier.
- doc_dir() - Documents a section of data from a files in a directory.
PARAMETERS: files, ignore, dir, section
This is the main function. It documents a section (in the table of contents) from data in a single directory. By default it includes all files, but you can specify files with the 'files' parameter and can ignore files with 'ignore'. The title is 'section' and the directory used is 'dir'.
PARAMETERS DESCRIPTIONS
- source_dir
Source of Folder-Tree input files. These files are required for javascript. The source dir is an optional parameter. You may think the documentation looks better if this parameter is not passed :)
- out_dir
Output Directory For the web pages. It actually places stuff in the html subdirectory of this directory.
- company_name
Your company Name.
- home_page
Your Home Page for links.
- copyright_years
Copyright Notice Years
- indent_level
Default to 1. If this is set to 2 then head2's show up in the documentation table of contents and head1's are not indented. If it is set to 1 then head1's in pod files are indented in table of contents (no head2's). If 0 then all head1's show up non indented (no head2's).
- product_name
Product Name
- current_section
Section header - goes in table of contents
- color_h1
All first level headings get colored - not just NAME blocks.
- colorscheme
Change the color scheme of the documentation. Currently available color schemes are: DARKRED, PINK, OLIVE, LTBLUE, RED, ORANGE, LTGREEN, DKBLUE, BLUERED, and PURPLE.
NOTES
The documentation shows in a nice 3 pane window. The top pane (top.htm) will give title info. The left pane (toc.htm) gives table of contents and navigation information. The right pane (readme.htm) will give documentation with anchors embedded so the table of contents can work.
Documentation can be built from directories by using the doc_dir function to read all files for pod documentation. Files can either be in perl source code (.pl) files or .pod files. Documentation can also come from files with .htm or .html extensions. These files are parsed so as to remove everything but the body section.
If reading pod files, the first file is readme.pod. After that it is alphabetical.
In addition to regular pod documentation, get any documentation between "^# ===" blocks (comments only). If line is of format ^#\s*(\w+)\s*: then word is a heading
Specifically the doc subdirectory will contain README.txt and individual doc pages and the html directory will contain x.html files (from x.pl), and an index.html which is composed of a readme.html and toc.html (table of contents)
CROSSREFERENCE
The application will keep track of any keyword titles (ie items in the table of contents). When it is almost done, it will rewrite the main page and replace any words that match the title with self hyperlinks.
EXAMPLE
use strict;
use Doc;
doc_init(
out_dir => '../web' ,
home_page => 'http://www.edbarlow.com',
copyright_years => '1998-1999' ,
company_name => 'IQ Financial' ,
product_name => 'OPERATIONS MGR'
);
# add link to top level
doc_navlink( name=>"Return To Top Level", link=>"../index.htm");
#any pod documents in ../web/pod are in DOCUMENTATION section
doc_dir(
dir => "../web/pod" ,
section => "DOCUMENTATION"
);
# SCREENS section
doc_dir(
ignore => ['func.pl','web_run_cmd.pl',
'web_view_file.pl','web_waitfor.pl'],
dir => "../web" ,
section => "SCREENS"
);
# INTERNALS section
doc_dir(
files => ['func.pl','web_run_cmd.pl',
'web_view_file.pl','web_waitfor.pl'],
dir => "../web" ,
section => "INTERNALS"
);
doc_finish();
eventviewer.pl
Module for viewing events
|
DESCRIPTION
The event viewer is an example plugin that is normally run in stand alone mode. It provides a complete interface to your event manangement system.
This plugin is normally called using eventviewer.pl in the root directory. You can also call it using the standard gem syntax:
perl gem.pl --MODULENAME=eventviewer
print must use -showok if you wish to show ok items in the events
TO DO
print "\t<TD ALIGN=CENTER>",$hfont,
submit(-name=>"actionid_$butncnt",-value=>"Submit"),
popup_menu( -name=>"actionval_$butncnt",
-values=>\@hb_values,
-default=>'MsgDelete',
-labels=>\%hb_operations ),
$ehfont,"</TD>\n"
unless defined param("REPORTNAME");
{
my($actionval)=param("actionval_".$action_id);
my($actiontext)=$hb_operations{param("actionval_".$action_id)};
debugmsg("Button Pushed: ".$actiontext);
print drawbanner( b("Processing $actiontext"),"", "Row Key=$action_id" );
my(%keys);
foreach (param()) {
next unless /^sv_${action_id}_/;
my($k)=$_;
s/sv_${action_id}_//;
debugmsg( "KEY=$_ VAL=".param($k) );
$keys{$_} = param($k);
}
if( defined param('sv_admin') ) {
debugmsg( "Admin=".param("sv_admin") );
$keys{Admin}=param("sv_admin");
$admin=param("sv_admin");
}
if( $actionval eq "MsgDelete") {
print join(br,MlpManageData(
OkId=>$action_id,
Operation=>"del",
Admin=>"",
Server => $keys{System},
System => $keys{System},
Program => $keys{Program},
Subsystem => $keys{Subsystem},
State => $keys{State},
)),br;
} elsif( $actionval eq "DeleteMon") {
print join(br,MlpManageData(
OkId=>$action_id,
Operation=>"del",
Admin=>"Delete By Monitor",
Server => $keys{System},
System => $keys{System},
Monitor => $keys{Program},
Program => $keys{Program},
Subsystem => $keys{Subsystem},
State => $keys{State},
)),br;
} elsif( $actionval =~ /MsgOk/) {
my($hours)=24;
$hours=3 if $actionval=~/3hr$/;
$hours=72 if $actionval=~/3dy$/;
print join(br,MlpManageData(
OkId=>$action_id,
Operation=>"Ok",
Admin=>"",
Hours =>$hours,
Server => $keys{System},
System => $keys{System},
Program => $keys{Program},
Subsystem => $keys{Subsystem},
State => $keys{State},
)),br;
} elsif( $actionval eq "Blackout3") {
print join(br,MlpManageData(
Operation=>"setblackout",
Hours => 3,
Value => 1,
Server=>$keys{System},
Admin=>"Production" )),br;
} elsif( $actionval eq "Blackout6") {
print join(br,MlpManageData(
Operation=>"setblackout",
Hours => 6,
Value => 1,
Server=>$keys{System},
Admin=>"Production" )),br;
} elsif( $actionval eq "Blackout24") {
print join(br,MlpManageData(
Operation=>"setblackout",
Days => 1,
Value => 1,
Server=>$keys{System},
Admin=>"Production" )),br;
} elsif( $actionval eq "Blackout72") {
print join(br,MlpManageData(
Operation=>"setblackout",
Days => 3,
Value => 1,
Server=>$keys{System},
Admin=>"Production" )),br;
} elsif( $actionval eq "IgnoreSvr") { # ignore server
print join(br,MlpManageData(
Operation=>"setignore",
Value => 1,
Server=>$keys{System},
Admin=>"Production" )),br;
} elsif( $actionval eq "DeleteAll") {
print join(br,MlpManageData( OkId=>$action_id,
Operation=>"delserver",Program => $keys{Program},
System=>$keys{System})),br;
} elsif( $actionval eq "NotProd") { # server is not production
print join(br,MlpManageData(
Operation=>"setproduction",
Value => 0,
Server=>$keys{System},
Admin=>"Production" )),br;
}
}
This output is documentation for the SQL Technologies GEM LIBRARIES.
copyright © 1998-2008 By
SQL Technologies