Здравствуйте уважаемые форумчане!
Я раньше работал с небольшими сайтами и проектами, которые непосредственно работают с базой данных mysql. Можно сказать, что я почти не смотрел в административную часть mysql, его конфигурации и все такое.
И вот устроился на новую работу, и тут мне дают проект, в котором БД весит около 300 гигов, и большие нагрузки к ней, вся БД (около 40 БД с более 2500 таблицами) лежит на одном сервере.
Проект: на сайтах установлены наши счётчики, которые записывают в БД проекта данные о посетителях сайтов, в час около 115.000-130.000 инсертов в БД и селекты в другой БД, чтобы отобразить нашу картинку с рейтингом того сайта.
Схема работы:
Счётчик на сайте обращается в БД top_log и пишет туда в таблицу (с названием текущей даты, если такой таблицы нет, то он создаёт таблицу INNODB) всякие данные о посетителя сайта: айди сайта, браузер пользователя, откуда пришел на сайт, его айпи, разрешения монитора и все такое.
На сервере выполняется JAVA файл (анализатор) , который в 20 потоках обрабатывает записи из таблиц в БД top_log и обработанные записи вкладывает по нужным таблицам нужных БД (top_ref, toprating, tor_br и т.д.)
Примечание анализатору: он в одном потоке делает 100 раз селект из top_log и после обработки данной записи 34 раза делает INSERT в другие БД (таблицы для INSERT изначально создаются в InnoDB, и после обработки всех записей за текущего дня, конвертируеются в MyISAM). После обработки всех записей за текущего дня, он переконвертирует таблицу в top_log в MyISAM, и идет дальше обработать таблицу за следующего дня. Транзакции не используются.
А я написал свой скрипт (анализатор) на php, который берет 100 записей в массив и полученного массива разбивает по столбцам и передает функциям для обработки, а они в свою очередь обрабатывают их и возвращают строку для инсерта в формате:
INSERT tablename(fields_list) values(rec_list1),(rec_list 2),( rec_list3), …(rec_list100) on duplicate key update count=count+1
Т.е., выполняется 1 Select limit 100 записей и создаются 34 Insert с 100 записями каждый, и все полученные инсерты отправляются на Mysql для выполнения одной транзакцией.
Данный php анализатор запускается в 20 потоках, он изумительно начинает работать с первыми 200-300 тысями записями, а потом запросы начинают зависать в процессах MySQL, я включил логирования Commit и Rollback ов, лог Rollback постоянно растёт, так как MySQL не может обработать их и Rollbackит. Соответственно, данные остаются не обработанными и сайт начинает виснет, вернее даже не открывается.
Выложу конфигурацию MySQL и код своего анализатора.
файл: /etc/mysql/my.cnf
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/mysqldb
tmpdir = /tmp
language = /usr/share/mysql/english
skip-external-locking
default_character_set = utf8
bind-address = 91.212.89.6
key_buffer = 512M#16M
max_allowed_packet = 32M#16M
thread_stack = 384K#192K
thread_cache_size = 40#8
skip_name_resolve
tmp_table_size = 2G
join_buffer = 16M
sort_buffer = 32M
myisam_sort_buffer_size = 32M
net_buffer = 32M
net_buffer_length = 2M#32M
read_buffer = 16M
read_rnd_buffer = 16M
max_heap_table_size = 32M
table_cache = 10240
wait_timeout = 120
myisam-recover = BACKUP
max_connections = 100
#table_cache = 64
thread_concurrency = 16
query_cache_limit = 8M#1M
query_cache_size = 256M#16M
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 10
log-queries-not-using-indexes
log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 1
innodb_buffer_pool_size = 8G
innodb_log_file_size = 300M# 5242880
innodb_log_buffer_size = 16M # 8M
innodb_flush_log_at_trx_commit = 0
innodb_thread_concurrency=8
innodb_flush_method=O_DIRECT
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
[mysql]
[isamchk]
!includedir /etc/mysql/conf.d/
[mysqld_safe]
Syslog
Mysql> show processlist
ID Пользователь Хост База данных Команда Время Состояние SQL-запрос
939070 db Query 0 statistics SELECT `md5`
FROM `top_ref`.`20111229_list`
WHERE `md5` = 'b7649aa259590237fdce932711be625d'
LIMIT 1
939540 db Query 0 statistics SELECT `md5`
FROM `top_visitor_month`.`201112_list`
WHERE `md5` = 'd332640baa3007967d06dc90ed482f6d'
939992 db Query 0 update INSERT INTO `top_visitor_month`.`201112` (`pid`,`type`,`count`)VALUES ('16581','fb8ebf174497d59f5517
940438 db Query 0 update INSERT INTO `top_prov_day`.`20111229` (`ip`,`count`,`prid`)VALUES ('1490168914','1','24')ON DUPLICAT
940897 db Query 1 statistics SELECT `md5` FROM `top_visitor_month`.`201112_list` WHERE `md5` = '8741a0f2d613138fa0255e33914eb596'
941326 db Query 0 update INSERT INTO `top_domains`.`20111229` (`pid`,`type`,`count`)VALUES ('20928','4ec480c016f52581661a0002
941817 db Query 0 update INSERT INTO `top_os`.`20111229` (`pid`,`type`,`count`)VALUES ('20928','aea23489ce3aa9b6406ebb28e0cda
942238 db Query 0 update INSERT INTO `top_visitor_month`.`201112` (`pid`,`type`,`count`)VALUES ('1','c7727dec7ab9820a6b428a68
942691 db Query 0 statistics SELECT `md5` FROM `top_visitor_month`.`201112_list` WHERE `md5` = '192a1250c8d0d8bb7a7aec1a766bac39'
943142 db Query 0 statistics SELECT `md5` FROM `top_domains`.`20111229_list` WHERE `md5` = 'd6fdf523205cb8c2ec9c0666716dcac5' LIM
943543 db Query 0 update INSERT INTO `top_visitor_month`.`201112` (`pid`,`type`,`count`)VALUES ('15694','45d5e3fa88f471736bc2
943940 db Query 2 update INSERT INTO `top_prov_month`.`201112` (`ip`,`count`,`prid`)VALUES ('3588642160','1','9')ON DUPLICATE
944474 db Query 0 statistics SELECT `md5` FROM `top_visitor_week`.`20111225_list` WHERE `md5` = '709a9b262af49f61f8001b1ee4828d1a
944917 db Query 0 update INSERT INTO `top_visitor_month`.`201112` (`pid`,`type`,`count`)VALUES ('25667','eb13e44d49603eae650f
945424 db Query 0 update INSERT INTO `top_hour`.`20111229` (`pid`,`hour`,`count`,`ip`)VALUES ('20736','16','1','3588647349')O
945890 db Query 0 update INSERT INTO `toprating`.`20111229` (`pid`,`ip`,`count`)VALUES ('14754','1539592565','1')ON DUPLICATE
946400 db Query 0 update INSERT INTO `top_os`.`20111229` (`pid`,`type`,`count`)VALUES ('14816','edc9f0a5a5d57797bf68e37364743
946888 db Query 0 update INSERT INTO `top_visitor_month`.`201112` (`pid`,`type`,`count`)VALUES ('1203','37e9f8206ab06a1ae60fc
947392 db Query 0 update INSERT INTO `top_visitor_month`.`201112` (`pid`,`type`,`count`)VALUES ('16955','3b0538112e7d18d975d9
947885 db Query 0 update INSERT INTO `top_prov_day`.`20111229` (`ip`,`count`,`prid`)VALUES ('3648412376','1','21')ON DUPLICAT
948303 db Query 0 statistics SELECT `md5` FROM `top_ref`.`20111229_list` WHERE `md5` = 'c1cd9fc6252df1a4aaf305f360738d7f' LIMIT 1
948777 db Query 0 update INSERT INTO `top_visitor_week`.`20111225` (`pid`,`type`,`count`)VALUES ('20736','4082346c7118da88caf
949294 db Query 0 update INSERT INTO `top_visitor_week`.`20111225` (`pid`,`type`,`count`)VALUES ('19385','0bf0f1afa29352ef87e
949786 db Query 0 update INSERT INTO `top_ref`.`20111229` (`pid`,`type`,`count`)VALUES ('20928','4bd7c2db7779d96a3ac428efabac
950265 db Query 1 update INSERT INTO `top_visitor_day`.`20111229` (`pid`,`type`,`count`)VALUES ('2812','1f9b26dcbaba26809facd
1028026 db Query 888 Creating sort index SELECT pr.name as name, COUNT(DISTINCT(res.ip)) as rescount,pr.country as country F
1104739 db Sleep 17 --- ---
1104740 db Query 10 checking permissions SHOW TABLES FROM `d1f32968`
1106530 db Sleep 3 --- ---
1106531 db Query 0 Copying to tmp table SELECT * FROM catalog.`resources` WHERE `providerid`="37" AND `registered`="1" AND `topid`!=0 GROUP
1106615 db Sleep 2 --- ---
1106616 db Query 1 Copying to tmp table SELECT * FROM catalog.`resources` WHERE `providerid`="24" AND `registered`="1" GROUP BY `resgroup`
1106640 db Sleep 2 --- ---
1106642 db Query 1 Copying to tmp table SELECT * FROM catalog.`resources` WHERE `providerid`="24" AND `registered`="1" GROUP BY `resgroup`
1106821 db Query 0 update INSERT INTO `top_log`.`20111229` (`id`,`pid`,`idata`,`ip`,`path`,`path_real`,`agent`,`page_ref`,`coo
1106823 db Sleep 0 --- ---
1106824 db Query 0 --- SHOW PROCESSLIST
1106825 db Query 0 update INSERT INTO `top_log`.`20111229` (`id`,`pid`,`idata`,`ip`,`path`,`path_real`,`agent`,`page_ref`,`coo
Phpmyadmin – Вкладка Состояние
Трафик: статистика по сетевому трафику MySQL-сервера со времени его запуска.
Трафик 1 o в час
Принято 2,781 МБ 703 МБ
Отправлено 21 ГБ 5,498 МБ
Всего 24 ГБ 6,201 МБ
Соединения o в час %
Максимально одновременных 54 --- ---
Неудачных попыток 328 82.89 0.03%
Прерваны 80 20.22 0.01%
Всего 1,140 k 288.14 k 100.00%
________________________________________
Статистика запросов: со времени запуска, на сервер было отослано запросов - 22,879,928.
Всего o в час o в минуту o в секунду
23 M 5.78 M 96.36 k 1.61 k
Тип запроса o в час %
insert 10 M 2.553 M 46.48%
select 4,365 k 1.103 M 20.08%
set option 2,255 k 569.804 k 10.37%
change db 1,749 k 441.892 k 8.04%
update 47 k 11.854 k 0.22%
delete 12 k 3.124 k 0.06%
create table 3,496 883.448 0.02%
show variables 102 25.776 0.00%
Тип запроса o в час %
show collations 101 25.523 0.00%
show table status 100 25.270 0.00%
show tables 54 13.646 0.00%
truncate 22 5.559 0.00%
show binlogs 5 1.264 0.00%
show fields 4 1.011 0.00%
show processlist 2 0.505 0.00%
show databases 1 0.253 0.00%
Тип запроса o в час %
show slave status 1 0.253 0.00%
show plugins 1 0.253 0.00%
show master status 1 0.253 0.00%
show grants 1 0.253 0.00%
show charsets 1 0.253 0.00%
show status 1 0.253 0.00%
Начало SQL-запрос
Переменная Значение Описание
Flush_commands 1
Last_query_cost 0
Slow_queries 25 k
Начало InnoDB
Переменная Значение Описание
Переменные Состояние InnoDB
Innodb_buffer_pool_pages_data 507 k
Innodb_buffer_pool_pages_dirty 77 k
Innodb_buffer_pool_pages_flushed 1,574 k
Innodb_buffer_pool_pages_free 0
Innodb_buffer_pool_pages_misc 17 k
Innodb_buffer_pool_pages_total 524 k
Innodb_buffer_pool_read_ahead_rnd 1,570
Innodb_buffer_pool_read_ahead_seq 258
Innodb_buffer_pool_read_requests 1,557 M
Innodb_buffer_pool_reads 445 k
Innodb_buffer_pool_wait_free 0
Innodb_buffer_pool_write_requests 101 M
Innodb_data_fsyncs 58 k
Innodb_data_pending_fsyncs 0
Innodb_data_pending_reads 1
Innodb_data_pending_writes 0
Innodb_data_read 11 G
Innodb_data_reads 550 k
Innodb_data_writes 821 k
Innodb_data_written 58 G
Innodb_dblwr_pages_written 1,574 k
Innodb_dblwr_writes 18 k
Innodb_log_waits 6
Innodb_log_write_requests 13 M
Innodb_log_writes 20 k
Innodb_os_log_fsyncs 22 k
Innodb_os_log_pending_fsyncs 0
Innodb_os_log_pending_writes 0
Innodb_os_log_written 6,240 M
Innodb_page_size 16 k
Innodb_pages_created 81 k
Innodb_pages_read 630 k
Innodb_pages_written 1,574 k
Innodb_row_lock_current_waits 0
Innodb_row_lock_time 6,967 k
Innodb_row_lock_time_avg 305
Innodb_row_lock_time_max 52 k
Innodb_row_lock_waits 23 k
Innodb_rows_deleted 1
Innodb_rows_inserted 1,944 k
Innodb_rows_read 2,618 M
Innodb_rows_updated 8,880 k
Начало SSL
Переменная Значение Описание
Ssl_accept_renegotiates 0
Ssl_accepts 0
Ssl_callback_cache_hits 0
Ssl_cipher
Ssl_cipher_list
Ssl_client_connects 0
Ssl_connect_renegotiates 0
Ssl_ctx_verify_depth 0
Ssl_ctx_verify_mode 0
Ssl_default_timeout 0
Ssl_finished_accepts 0
Ssl_finished_connects 0
Ssl_session_cache_hits 0
Ssl_session_cache_misses 0
Ssl_session_cache_mode NONE
Ssl_session_cache_overflows 0
Ssl_session_cache_size 0
Ssl_session_cache_timeouts 0
Ssl_sessions_reused 0
Ssl_used_session_cache_entries 0
Ssl_verify_depth 0
Ssl_verify_mode 0
Ssl_version
Начало Обработчик
Переменная Значение Описание
Handler_commit 24 M
Handler_delete 6,528
Handler_discover 0
Handler_prepare 19 M
Handler_read_first 1,878 k
Handler_read_key 217 M
Handler_read_next 3,152 M
Handler_read_prev 159 k
Handler_read_rnd 41 M
Handler_read_rnd_next 1,248 M
Handler_rollback 368
Handler_savepoint 0
Handler_savepoint_rollback 0
Handler_update 10 M
Handler_write 84 M
Начало Кеш запросов
Переменная Значение Описание
Qcache_free_blocks 9,023
Qcache_free_memory 204 M
Qcache_hits 3,202 k
Qcache_inserts 4,042 k
Qcache_lowmem_prunes 0
Qcache_not_cached 323 k
Qcache_queries_in_cache 35 k
Qcache_total_blocks 79 k
Начало Потоки
Переменная Значение Описание
Список процессов
Slow_launch_threads 0
Threads_cached 22
Threads_connected 32
Threads_created 90
Threads_running 3
Threads_cache_hitrate_% 99.99 %
Начало Бинарный журнал
Переменная Значение Описание
Binlog_cache_disk_use 0
Binlog_cache_use 9,599 k
Начало Временные данные
Переменная Значение Описание
Created_tmp_disk_tables 108 k
Created_tmp_files 205
Created_tmp_tables 170 k
Начало Отложенные вставки
Переменная Значение Описание
Delayed_errors 0
Delayed_insert_threads 0
Delayed_writes 0
Not_flushed_delayed_rows 0
Начало Кеш индекса
Переменная Значение Описание
Key_blocks_not_flushed 0
Key_blocks_unused 76
Key_blocks_used 429 k
Key_read_requests 373 M
Key_reads 5,264 k
Key_write_requests 15 M
Key_writes 48 k
Key_buffer_fraction_% 99.99 %
Key_write_ratio_% 0.31 %
Key_read_ratio_% 1.41 %
Начало Объединения
Переменная Значение Описание
Select_full_join 387
Select_full_range_join 0
Select_range 88 k
Select_range_check 0
Select_scan 13 k
Начало Репликация
Переменная Значение Описание
Информация о подчиненных серверах Показать состояние головного сервера
Rpl_status NULL
Slave_open_temp_tables 0
Slave_retried_transactions 0
Slave_running OFF
Начало Сортировка
Переменная Значение Описание
Sort_merge_passes 16
Sort_range 1,075 k
Sort_rows 28 M
Sort_scan 2,001 k
Начало Таблицы
Переменная Значение Описание
Open_tables 1,046
Opened_tables 1,059
Table_locks_immediate 15 M
Table_locks_waited 41 k
Начало Координатор транзакций
Переменная Значение Описание
Tc_log_max_pages_used 0
Tc_log_page_size 0
Tc_log_page_waits 0
Начало
Переменная Значение Описание
Compression OFF
Open_files 658 Количество открытых файлов.
Open_streams 0 Количество открытых потоков (применяется к файлам журналов). Потоком называется файл, открытый с помощью функции fopen().
Open_table_definitions 358
Opened_files 479 k
Opened_table_definitions 371
Prepared_stmt_count 0
Queries 23 M
Uptime_since_flush_status 0 дней, 3 часов, 57 минут и 26 секунд
________________________________________
Состояние репликации
Статус Master
Переменная Значение
File mysql-bin.000231
Position 159068198
Binlog_Do_DB
Binlog_Ignore_DB
PHPMYADMIN – Вкладка Переменные
Серверные переменные и настройки
Переменная Значение сессии / Глобальное значение
auto increment increment 1
auto increment offset 1
autocommit ON
automatic sp privileges ON
back log 50
basedir /usr/
big tables OFF
binlog cache size 32,768
binlog direct non transactional updates OFF
binlog format STATEMENT
bulk insert buffer size 8,388,608
character set client utf8
character set connection utf8
character set database utf8
character set filesystem binary
character set results utf8
character set server utf8
character set system utf8
character sets dir /usr/share/mysql/charsets/
collation connection utf8_general_ci
collation database utf8_general_ci
collation server utf8_general_ci
completion type 0
concurrent insert 1
connect timeout 10
datadir /var/mysqldb/
date format %Y-%m-%d
datetime format %Y-%m-%d %H:%i:%s
default week format 0
delay key write ON
delayed insert limit 100
delayed insert timeout 300
delayed queue size 1,000
div precision increment 4
engine condition pushdown ON
error count 0
event scheduler OFF
expire logs days 1
flush OFF
flush time 0
foreign key checks ON
ft boolean syntax + -><()~*:""&|
ft max word len 84
ft min word len 4
ft query expansion limit 20
ft stopword file (built-in)
general log OFF
general log file /var/run/mysqld/mysqld.log
group concat max len 1,024
have community features YES
have compress YES
have crypt YES
have csv YES
have dynamic loading YES
have geometry YES
have innodb YES
have ndbcluster NO
have openssl DISABLED
have partitioning YES
have query cache YES
have rtree keys YES
have ssl DISABLED
have symlink YES
hostname mysqlsrv
identity 0
ignore builtin innodb OFF
init connect
init file
init slave
innodb adaptive hash index ON
innodb additional mem pool size 1,048,576
innodb autoextend increment 8
innodb autoinc lock mode 1
innodb buffer pool size 8,589,934,592
innodb checksums ON
innodb commit concurrency 0
innodb concurrency tickets 500
innodb data file path ibdata1:10M:autoextend
innodb data home dir
innodb doublewrite ON
innodb fast shutdown 1
innodb file io threads 4
innodb file per table OFF
innodb flush log at trx commit 0
innodb flush method O_DIRECT
innodb force recovery 0
innodb lock wait timeout 50
innodb locks unsafe for binlog OFF
innodb log buffer size 16,777,216
innodb log file size 314,572,800
innodb log files in group 2
innodb log group home dir ./
innodb max dirty pages pct 90
innodb max purge lag 0
innodb mirrored log groups 1
innodb open files 300
innodb rollback on timeout OFF
innodb stats on metadata ON
innodb support xa ON
innodb sync spin loops 20
innodb table locks ON
innodb thread concurrency 8
innodb thread sleep delay 10,000
innodb use legacy cardinality algorithm ON
insert id 0
interactive timeout 28,800
join buffer size 16,777,216
keep files on create OFF
key buffer size 536,870,912
key cache age threshold 300
key cache block size 1,024
key cache division limit 100
language /usr/share/mysql/english/
large files support ON
large page size 0
large pages OFF
last insert id 0
lc time names en_US
license GPL
local infile ON
locked in memory OFF
log OFF
log bin ON
log bin trust function creators OFF
log bin trust routine creators OFF
log error
log output FILE
log queries not using indexes ON
log slave updates OFF
log slow queries ON
log warnings 1
long query time 10
low priority updates OFF
lower case file system OFF
lower case table names 0
max allowed packet 33,554,432
max binlog cache size 18446744073709547520
max binlog size 1,073,741,824
max connect errors 10
max connections 100
max delayed threads 20
max error count 64
max heap table size 33,554,432
max insert delayed threads 20
max join size 18446744073709551615
max length for sort data 1,024
max prepared stmt count 16,382
max relay log size 0
max seeks for key 18446744073709551615
max sort length 1,024
max sp recursion depth 0
max tmp tables 32
max user connections 0
max write lock count 18446744073709551615
min examined row limit 0
multi range count 256
myisam data pointer size 6
myisam max sort file size 9223372036853727232
myisam mmap size 18446744073709551615
myisam recover options BACKUP
myisam repair threads 1
myisam sort buffer size 33,554,432
myisam stats method nulls_unequal
myisam use mmap OFF
net buffer length 1,048,576
net read timeout 30
net retry count 10
net write timeout 60
new OFF
old OFF
old alter table OFF
old passwords OFF
open files limit 20,590
optimizer prune level 1
optimizer search depth 62
optimizer switch index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on
pid file /var/run/mysqld/mysqld.pid
plugin dir /usr/lib/mysql/plugin
port 3,306
preload buffer size 32,768
profiling OFF
profiling history size 15
protocol version 10
pseudo thread id 1,146,002
(Глобальное значение) 0
query alloc block size 8,192
query cache limit 8,388,608
query cache min res unit 4,096
query cache size 268,435,456
query cache type ON
query cache wlock invalidate OFF
query prealloc size 8,192
rand seed1
rand seed2
range alloc block size 4,096
read buffer size 16,777,216
read only OFF
read rnd buffer size 16,777,216
relay log
relay log index
relay log info file relay-log.info
relay log purge ON
relay log space limit 0
report host
report password
report port 3,306
report user
rpl recovery rank 0
secure auth OFF
secure file priv
server id 1
skip external locking ON
skip name resolve ON
skip networking OFF
skip show database OFF
slave compressed protocol OFF
slave exec mode STRICT
slave load tmpdir /tmp
slave net timeout 3,600
slave skip errors OFF
slave transaction retries 10
slow launch time 2
slow query log ON
slow query log file /var/log/mysql/mysql-slow.log
socket /var/run/mysqld/mysqld.sock
sort buffer size 33,554,432
sql auto is null ON
sql big selects ON
sql big tables OFF
sql buffer result OFF
sql log bin ON
sql log off OFF
sql log update ON
sql low priority updates OFF
sql max join size 18446744073709551615
sql mode
sql notes ON
sql quote show create ON
sql safe updates OFF
sql select limit 18446744073709551615
sql slave skip counter
sql warnings OFF
ssl ca
ssl capath
ssl cert
ssl cipher
ssl key
storage engine MyISAM
sync binlog 0
sync frm ON
system time zone UZT
table definition cache 256
table lock wait timeout 50
table open cache 10,240
table type MyISAM
thread cache size 40
thread handling one-thread-per-connection
thread stack 393,216
time format %H:%i:%s
time zone SYSTEM
timed mutexes OFF
timestamp 1,325,159,065
tmp table size 2,147,483,648
tmpdir /tmp
transaction alloc block size 8,192
transaction prealloc size 4,096
tx isolation REPEATABLE-READ
unique checks ON
updatable views with limit YES
version 5.1.49-3-log
version comment (Debian)
version compile machine x86_64
version compile os debian-linux-gnu
wait timeout 120
warning count 0
Мой php analyzer
<?php
error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(0);
$MaxThread=20;
$RecordsPerThread=100;
$fromHour =0;
$toHour=24;
if ($_GET['potok']) $MaxThread = $_GET['potok'];
if ($_GET['recs']) $RecordsPerThread = $_GET['recs'];
if ($_GET['ot']) $fromHour = $_GET['ot'];
if ($_GET['do']) $toHour = $_GET['do'];
$d=explode(" ",date('h A', time()));
$hour=($d[1]=="PM")?(($d[0]+12==24)?0:$d[0]+12):$d[0]; // текущее время (час)
//$worker_processes = array();
for ($i = 0; $i < $MaxThread; $i++)
{
$prid = pcntl_fork();
if ($prid == -1) { continue;}
elseif ($prid > 0) {
// $worker_processes[] = $prid;
continue;
}
$thrid=floatval(substr(microtime(),0,5).substr(strrev(microtime()),0,5))*100000000;
analyzeIt($thrid);
exit;
} //for ($i = 0; $i < $MaxThread; $i++)
exit();
/*
* Функция поиска и передачи для обработки записей
*/
function analyzeIt($thrid)
{
global $RecordsPerThread, $fromHour, $toHour, $hour; // по скольку строк будет обрабатывать каждый поток в один заход
$YYYYMM=date('Ym', strtotime($table));
$db=new MyDB('host','user','password','top_log');
while (true) {
$tables=$db->query("SHOW TABLES FROM ".'top_log'); // список имеющихся таблиц в базе top_log
foreach($tables as $key=>&$value){
// берем необработанных записей
// мы их сначала сразу обозначим как обрабатываемые записи чтобы избежать битых данных
$table=$value[Tables_in_top_log];
logger("table_".$table.".log", date('H:i:s',time()).' : THREAD #:'.$thrid.'-Table '.$table.' Beginned'.chr(10).chr(13));
$continue=true;
while ($continue){
if (($hour>=$fromHour) && ($hour<=$toHour)){
$db->query("Update top_log.".$table." SET thread='".$thrid."', processed=1 WHERE processed=0 and thread='' LIMIT ".$RecordsPerThread);
$records=$db->query("SELECT id,pid,idata,ip,path,path_real,agent,page_ref,color,monitor,vjs FROM top_log.".$table." WHERE processed=1 AND thread='".$thrid."'; ");
createTables($db,$table); // создание таблиц
if ($records) { // в выбранной таблице $value[Tables_in_top_log] имеются записи для обработки
// $time_start = getmicrotime();
// echo "<hr>".$ides."<hr>";
// echo '<br>'.$table."-".$RecordsPerThread.'<hr><br>';
$a_id=$a_pid=$a_idata=$a_ip=$a_path=$a_path_real=$a_agent=$a_page_ref=$a_color=$a_monitor=$a_vjs='';
for ($i=0;$i<count($records);$i++) {
$a_id[]=$records[$i][id];
$a_pid[]=$records[$i][pid];
$a_idata[]=$records[$i][idata];
$a_ip[]=$records[$i][ip];
$a_path[]=$records[$i][path];
$a_path_real[]=$records[$i][path_real];
$a_agent[]=$records[$i][agent];
$a_path_ref[]=$records[$i][page_ref];
$a_color[]=$records[$i][color];
$a_monitor[]=$records[$i][monitor];
$a_vjs[]=$records[$i][vjs];
}
$TRQ_top_br='';
addtoqueries($TRQ_top_br, qTOPBR($table, $a_pid, $a_agent));
addtoqueries($TRQ_top_br, qTOPOS($table, $a_pid, $a_agent));
addtoqueries($TRQ_top_br, qTOPPOPPAGES($table, $a_pid, $a_path));
addtoqueries($TRQ_top_br, qTOPVISITORS($table, $a_pid, $a_ip, $a_agent, $a_color, $a_monitor, $a_vjs, $a_idata));
addtoqueries($TRQ_top_br, qTOPHOUR($table, $a_pid, $a_ip, $a_idata));
addtoqueries($TRQ_top_br, qTOPPROVHOUR($db,$table, $a_pid, $a_ip, $a_idata));
addtoqueries($TRQ_top_br, qTOPSPIDER($table, $a_pid, $a_agent));
addtoqueries($TRQ_top_br, qTOPDOMEN($table, $a_pid, $a_path, $a_path_real, $a_path_ref));
$commit=true;
$db->query("START TRANSACTION");
foreach($TRQ_top_br as $key=>$value) {
$a=$db->query($value);
if (!$a && $a!==0) $commit=false; // rollback
}
if ($commit) {
$db->query("COMMIT");
$db->query(" Update top_log.".$table." SET processed=2 WHERE processed=1 and thread='".$thrid."'; ");
logger("_cmAnalyzer_".$table.".log", date('H:i:s',time()).' : THREAD #:'.$thrid.'-COMITTED IDs=>('.implode(",",$a_id).')'.chr(13).chr(10)."-".chr(10).chr(13));
}
else {
logger("_rbAnalyzer_".$table.".log", date('H:i:s',time()).' : THREAD #:'.$thrid.'-ROLLBACKED IDs=>('.implode(",",$a_id).')'.chr(13).chr(10)."-".chr(10).chr(13));
$db->query("ROLLBACK");
}
sleep(3); //ждем 3 секунда чтобы не занимать всю память
} else
{
$continue=false;
convertTables($db,$table);
logger("table_".$table.".log", date('H:i:s',time()).' : THREAD #:'.$thrid.'-Table '.$table.' Ended'.chr(10).chr(13));
}// if ($records)
} // if (($hour>=$fromHour) && ($hour<=$toHour))
}//while($continue)
} //foreach($tables as $key...
sleep(10); //ждем 10 секунда чтобы не занимать всю память
} // end of while(true)
}
/*
* author (c) maksud
*/
function qTOPDOMEN($table, $pid, $path, $pathreal, $pathref) {
$qrbr1 = " INSERT INTO top_domains.".$table." (pid,type,count) VALUES "; // postDomen
$qrbr2 = " INSERT INTO top_domains.".$table."_list (name,md5) VALUES "; // postDomen list
$qrbr3 = " INSERT INTO top_ref.".$table." (pid,type,count) VALUES "; // postReferral
$qrbr4 = " INSERT INTO top_ref.".$table."_list (name,md5) VALUES "; // postReferral list
$qrbr5 = " INSERT INTO top_search.".$table." (pid,type,count) VALUES "; // postSearch
$qrbr6 = " INSERT INTO top_search.".$table."_list (name,md5) VALUES "; // postSearch list
$qr1=$qr2=$qr3=$qr4=$qr5=$qr6='';
for ($i=0;$i<count($pid);$i++){
$domen=getDomen($path[$i], $pathreal[$i], $pathref[$i]);
if ($domen){
$md5=md5($domen);$md5ref=md5($pathref[$i]);
$qr1.="(".$pid[$i].",'".$md5."',1),";
$qr2.="('".$domen."','".$md5."'),";
$qr3.="(".$pid[$i].",'".$md5ref."',1),";
$qr4.="('".$pathref[$i]."','".$md5ref."'),";
if ($spider=detectSpider($pathref[$i])){
$md5sp=md5($spider);
$qr5.="(".$pid[$i].",'".$md5sp."',1),";
$qr6.="('".$spider."','".$md5sp."'),";
}
}
}
$qrbr1=($qr1)?$qrbr1.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr2=($qr2)?$qrbr2.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
$qrbr3=($qr3)?$qrbr3.substr_replace($qr3,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr4=($qr4)?$qrbr4.substr_replace($qr4,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
$qrbr5=($qr5)?$qrbr5.substr_replace($qr5,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr6=($qr6)?$qrbr6.substr_replace($qr6,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
return array($qrbr1,$qrbr2,$qrbr3,$qrbr4,$qrbr5,$qrbr6);
}
/*
* author (c) Nishanov maksud
*/
function qTOPSPIDER($table, $pid, $agent) {
$qrbr=" INSERT INTO top_robot.".$table." (pid,type,count) VALUES "; // postSpider
$qrbr1=" INSERT INTO top_robot.".$table."_list (name,md5) VALUES "; // postSpider list
$qr1=$qr2='';
for ($i=0;$i<count($pid);$i++){
$spider=detectSpider($agent[$i]);
if ($spider){
$md5=md5($spider);
$qr1.="(".$pid[$i].",'".$md5."',1),";
$qr2.="('".$spider."','".$md5."'),";
}
}
$qrbr=($qr1)?$qrbr.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr1=($qr2)?$qrbr1.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
return array($qrbr,$qrbr1);
}
/*
* author (c) maksud
*/
function qTOPPROVHOUR($db, $table, $pid, $ip, $idata) {
$provs=$db->query(" SELECT DISTINCT topid as pid, ipaddress as ip, providerid as provid FROM catalog.resources WHERE topid IN (".implode(',',$pid).")");
if ($provs) {
$YYYYMM=date('Ym', strtotime($table));
$qrbr = " INSERT INTO top_prov_hour.".$table." (prid,hour,count,ip) VALUES "; // postHour
$qrbr1 = " INSERT INTO top_prov_day.".$table." (prid,ip,count) VALUES "; // postHour
$qrbr2 = " INSERT INTO top_prov_week.".$table." (prid,ip,count) VALUES "; // postHour
$qrbr3 = " INSERT INTO top_prov_month.".$YYYYMM." (prid,ip,count) VALUES "; // postHour
$qr1=$qr2=$qr3=$qr4='';
for ($i=0;$i<count($pid);$i++){
$prIP=false;
foreach($provs as $key => $value){
if ($value[pid] == $pid[$i]) {
$prIP=$value[ip];break 1;
}
}
if (!$prIP || !$prIP == '0.0.0.0' || !$prIP == '255.255.255.255' || $prIP='' ) { continue;}
else { $_d=explode(' ',date('h A', $idata[$i]));$hour=($_d[1]=="PM")?(($_d[0]+12==24)?0:$_d[0]+12):$_d[0];
$qr1.="(".$pid[$i].",'".$hour."',1,'".$ip[$i]."'),"; //pid, hour, count,ip
$qr2.="(".$pid[$i].",'".$ip[$i]."',1),"; //pid, ip, count
}
}
$qrbr=($qr1)?$qrbr.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr1=($qr2)?$qrbr1.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr2=($qr2)?$qrbr2.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr3=($qr2)?$qrbr3.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
return array($qrbr,$qrbr1,$qrbr2,$qrbr3);
}
return '';
}
/*
* author (c) maksud
*/
function qTOPHOUR($table, $pid, $ip, $idata) {
$YYYYMM=date('Ym', strtotime($table));
$qrbr=" INSERT INTO top_hour.".$table." (pid,hour,count,ip) VALUES "; // postHour
$qrbr1=" INSERT INTO toprating.".$table." (pid,ip,count) VALUES "; // postHour
$qrbr2=" INSERT INTO top_week.".$table." (pid,ip,count) VALUES "; // postHour
$qrbr3=" INSERT INTO top_month.".$YYYYMM." (pid,ip,count) VALUES "; // postHour
$qr1=$qr2=$qr3=$qr4='';
for ($i=0;$i<count($pid);$i++){
$_d=explode(' ',date('h A', $idata[$i]));$hour=($_d[1]=="PM")?(($_d[0]+12==24)?0:$_d[0]+12):$_d[0];
$qr1.="(".$pid[$i].",'".$hour."',1,'".$ip[$i]."'),"; //pid, hour, count,ip
$qr2.="(".$pid[$i].",'".$ip[$i]."',1),"; //pid, ip, count
}
$qrbr=($qr1)?$qrbr.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr1=($qr2)?$qrbr1.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr2=($qr2)?$qrbr2.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr3=($qr2)?$qrbr3.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
return array($qrbr,$qrbr1,$qrbr2,$qrbr3);
}
/*
* author (c) maksud
*/
function qTOPVISITORS($table, $pid, $ip, $agent, $color, $monitor, $vjs, $idata) {
$YYYYMM=date('Ym', strtotime($table));
$qrbr=" INSERT INTO top_visitor_hour.".$table." (pid,hour,count,type) VALUES "; // postVisitors
$qrbr1=" INSERT INTO top_visitor_day.".$table." (pid,type,count) VALUES "; // postVisitors
$qrbr2=" INSERT INTO top_visitor_week.".$table." (pid,type,count) VALUES "; // postVisitors
$qrbr3=" INSERT INTO top_visitor_month.".$YYYYMM." (pid,type,count) VALUES "; // postVisitors
$qrbr4=" INSERT INTO top_visitor_day.".$table."_list (ip,agent,color,monitor,vjs,md5) VALUES "; // postVisitors list
$qrbr5=" INSERT INTO top_visitor_week.".$table."_list (ip,agent,color,monitor,vjs,md5) VALUES "; // postVisitors list
$qrbr6=" INSERT INTO top_visitor_month.".$YYYYMM."_list (ip,agent,color,monitor,vjs,md5) VALUES "; // postVisitors list
$qr1=$qr2=$qr3=$qr4=$qr5=$qr6=$qr7='';
for ($i=0;$i<count($pid);$i++){
$md5=md5($ip[$i].$agent[$i].$color[$i].$monitor[$i].$vjs[$i]);
$_d=explode(' ',date('h A', $idata[$i]));$hour=($_d[1]=="PM")?(($_d[0]+12==24)?0:$_d[0]+12):$_d[0];
$qr1.="(".$pid[$i].",'".$md5."',1),"; //pid, type, count
$qr3.="(".$pid[$i].",'".$hour."','".$md5."',1),"; //pid, hour, type, count
$qr2.="('".$ip[$i]."','".$agent[$i]."','".$color[$i]."','".$monitor[$i]."','".$vjs[$i]."','".$md5."'),"; //pid, hour, type, count
}
$qrbr=($qr3)?$qrbr.substr_replace($qr3,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr1=($qr1)?$qrbr1.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr2=($qr1)?$qrbr2.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr3=($qr1)?$qrbr3.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbr4=($qr2)?$qrbr4.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
$qrbr5=($qr2)?$qrbr5.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
$qrbr6=($qr2)?$qrbr6.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
return array($qrbr,$qrbr1,$qrbr2,$qrbr3,$qrbr4,$qrbr5,$qrbr6);
}
/*
* author (c) maksud
*/
function qTOPPOPPAGES($table,$pid,$path){
$qrbr=" INSERT INTO top_pop.".$table." (pid,type,count) VALUES "; // postPopPages
$qrbrl=" INSERT INTO top_pop.".$table."_list (name,md5) VALUES "; // postPopPages list
$qr1=$qr2='';
for ($i=0;$i<count($pid);$i++){
$md5=md5($path[$i]);
$qr1.="(".$pid[$i].",'".$md5."',1),";
$qr2.="('".$path[$i]."','".$md5."'),";
}
$qrbr=($qr1)?$qrbr.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbrl=($qr2)?$qrbrl.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
return array($qrbr,$qrbrl);
}
/*
* функция для определения браузера
* author (c) maksud
*/
function qTOPBR($table,$pid,$agent){
$qrbr=" INSERT INTO top_br.".$table." (pid, type, count) VALUES ";
$qrbrl=" INSERT INTO top_br.".$table."_list (name, version, md5) VALUES ";
$qr1=$qr2='';
for ($i=0;$i<count($agent);$i++){
$browser=user_browser($agent[$i]);
$md5=md5($browser["b"].$browser["v"]);
$qr1.="(".$pid[$i].",'".$md5."',1),";
$qr2.="('".$browser["b"]."','".$browser["v"]."','".$md5."'),";
}
$qrbr=($qr1)?$qrbr.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbrl=($qr2)?$qrbrl.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
return array($qrbr,$qrbrl);
}
/*
* функция для определения OS
* author (c) maksud
*/
function qTOPOS($table,$pid,$agent){
$qrbr=" INSERT INTO top_os.".$table." (pid, type, count) VALUES ";
$qrbrl=" INSERT INTO top_os.".$table."_list (name, md5) VALUES ";
$qr1=$qr2='';
for ($i=0;$i<count($agent);$i++){
$os=user_OS($agent[$i]);
$md5=md5($os);
$qr1.="(".$pid[$i].",'".$md5."',1),";
$qr2.="('".$os."','".$md5."'),";
}
$qrbr=($qr1)?$qrbr.substr_replace($qr1,"",-1)." ON DUPLICATE KEY UPDATE count=count+1;":"";
$qrbrl=($qr2)?$qrbrl.substr_replace($qr2,"",-1)." ON DUPLICATE KEY UPDATE md5=md5;":"";
return array($qrbr,$qrbrl);
}
function createTables($db,$table)
{
$YYYYMM=date('Ym', strtotime($table));
$sqlSTR=array("CREATE TABLE IF NOT EXISTS top_br.".$table."_list
( name varchar( 24 ) CHARACTER SET cp1251 NOT NULL default '',
version varchar( 16 ) NOT NULL default '',
md5 varchar( 32 ) NOT NULL default '' COMMENT 'md5hash',
PRIMARY KEY ( md5 )
) ENGINE = InnoDB DEFAULT CHARSET = utf8;",
"CREATE TABLE IF NOT EXISTS top_br.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_ua.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ",
"CREATE TABLE IF NOT EXISTS top_hour.".$table."
( pid bigint(20) NOT NULL default '0',
hour int(2) NOT NULL default '0',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day and hour',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
PRIMARY KEY (pid,hour,ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS toprating.".$table."
( pid bigint(20) NOT NULL default '0',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
PRIMARY KEY (pid,ip)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;",
"CREATE TABLE IF NOT EXISTS top_month.".$YYYYMM."
( pid bigint(20) NOT NULL default '0',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,ip),
KEY hit (count),
KEY ip (ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_week.".$table."
( pid bigint(20) NOT NULL default '0' COMMENT 'pid of resource',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
count bigint(20) NOT NULL default '0' COMMENT 'hits',
PRIMARY KEY (pid,ip),
KEY ip (ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_prov_hour.".$table."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
hour int(2) NOT NULL default '0',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day and hour',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
PRIMARY KEY (hour,ip),
KEY prid (prid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_prov_day.".$table."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
PRIMARY KEY (ip),
KEY prid (prid)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;",
"CREATE TABLE IF NOT EXISTS top_prov_month.".$YYYYMM."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (ip),
KEY prid (prid),
KEY hit (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_prov_week.".$table."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
count bigint(20) NOT NULL default '0' COMMENT 'hits',
PRIMARY KEY (ip),
KEY prid (prid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_prov_visitor_hour.".$table."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
ip bigint(20) NOT NULL default '0' COMMENT 'ipaddress',
hour int(2) NOT NULL default '0',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day and hour',
type varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor',
PRIMARY KEY (ip,hour,type)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;",
"CREATE TABLE IF NOT EXISTS top_prov_visitor_day.".$table."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
ip bigint(20) NOT NULL default '0' COMMENT 'ipaddress',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day',
type varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor',
PRIMARY KEY (ip,type)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;",
"CREATE TABLE IF NOT EXISTS top_prov_visitor_day.".$table."_list
( md5 varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor',
ip bigint(20) default NULL,
agent text,
color tinyint(2) default NULL,
monitor varchar(10) default NULL,
vjs float default NULL,
PRIMARY KEY (md5),
KEY ip (ip)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251;",
"CREATE TABLE IF NOT EXISTS top_prov_visitor_week.".$table."
( prid bigint(20) NOT NULL default '0' COMMENT 'providerid',
ip bigint(20) NOT NULL default '0' COMMENT 'ip address',
count bigint(20) NOT NULL default '0' COMMENT 'hits',
PRIMARY KEY (ip),
KEY prid (prid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_hour.".$table."
( pid bigint(20) NOT NULL default '0',
hour int(2) NOT NULL default '0',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day and hour',
type varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
PRIMARY KEY (pid,hour,type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_day.".$table."
( pid bigint(20) NOT NULL default '0',
count bigint(20) NOT NULL default '0' COMMENT 'count of unical IP at this day',
type varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
PRIMARY KEY (pid,type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_day.".$table."_list
( md5 varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
ip bigint(20) default NULL,
agent text,
color tinyint(2) default NULL,
monitor varchar(10) default NULL,
vjs float default NULL,
PRIMARY KEY (md5),
KEY ip (ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_month.".$YYYYMM."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY hit (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_month.".$YYYYMM."_list
( md5 varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
ip bigint(20) default NULL,
agent text,
color tinyint(2) default NULL,
monitor varchar(10) default NULL,
vjs float default NULL,
PRIMARY KEY (md5),
KEY ip (ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_week.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
count bigint(20) NOT NULL default '0' COMMENT 'hits',
PRIMARY KEY (pid,type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_visitor_week.".$table."_list
( md5 varchar(32) NOT NULL default '0' COMMENT 'md5 of visitor' ,
ip bigint(20) default NULL,
agent text,
color tinyint(2) default NULL,
monitor varchar(10) default NULL,
vjs float default NULL,
PRIMARY KEY (md5),
KEY ip (ip)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_domains.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_domains.".$table."_list
( name text character set cp1251 NOT NULL,
md5 varchar(32) NOT NULL default '' COMMENT 'md5 hash',
PRIMARY KEY (md5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_os.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_os.".$table."_list
( name text character set cp1251 NOT NULL,
md5 varchar(32) NOT NULL default '' COMMENT 'md5 hash',
PRIMARY KEY (md5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_pop.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_pop.".$table."_list
( name text character set cp1251 NOT NULL,
md5 varchar(32) NOT NULL default '' COMMENT 'md5 hash',
PRIMARY KEY (md5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_ref.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_ref.".$table."_list
( name text character set cp1251 NOT NULL,
md5 varchar(32) NOT NULL default '' COMMENT 'md5',
PRIMARY KEY md5 (md5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='List';",
"CREATE TABLE IF NOT EXISTS top_robot.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_robot.".$table."_list
( name text character set cp1251 NOT NULL,
md5 varchar(32) NOT NULL default '' COMMENT 'md5 hash',
PRIMARY KEY md5 (md5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_search.".$table."
( pid bigint(20) NOT NULL default '0',
type varchar(32) NOT NULL default '0',
count bigint(20) NOT NULL default '0',
PRIMARY KEY (pid,type),
KEY count (count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;",
"CREATE TABLE IF NOT EXISTS top_search.".$table."_list
( name text character set cp1251 NOT NULL,
md5 varchar(32) NOT NULL default '' COMMENT 'md5 hash',
PRIMARY KEY md5 (md5)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
while (list($id,$query)=each($sqlSTR))
{
$db->query($query);
}
}
/*
* Конвертация конечных таблиц в MyISAM
*/
function convertTables($db,$table)
{
$YYYYMM=date('Ym', strtotime($table));
$ts="top_hour";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_br";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_ua";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_os";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_search";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_pop";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_prov_day";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_visitor_week";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_prov_hour";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_prov_week";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_prov_month";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$YYYYMM."';"))
$db->query("alter table ".$ts.".".$YYYYMM." engine=MyISAM;");
$ts="top_visitor_hour";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_visitor_day";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_ref";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_visitor_month";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$YYYYMM."';"))
$db->query("alter table ".$ts.".".$YYYYMM." engine=MyISAM;");
$ts="top_domains";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_robot";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."';"))
$db->query("alter table ".$ts.".".$table." engine=MyISAM;");
$ts="top_br";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_os";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_search";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_pop";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_ref";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_domains";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_visitor_day";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_visitor_week";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$table."_list';"))
$db->query("alter table ".$ts.".".$table."_list engine=MyISAM;");
$ts="top_visitor_month";
if (!$db->query("select table_name from information_schema.tables where engine='MyISAM' and table_schema='".$ts."' and table_name='".$YYYYMM."_list';"))
$db->query("alter table ".$ts.".".$YYYYMM."_list engine=MyISAM;");
}
function user_browser($agent)
{
preg_match("/(MSIE|Opera|Firefox|Chrome|Version|Opera Mini|Netscape|Konqueror|SeaMonkey|Camino|Minefield|Iceweasel|K-Meleon|Maxthon)(?:\/| )([0-9.]+)/", $agent, $browser_info);
list(,$browser,$version) = $browser_info;
if (preg_match("/Opera ([0-9.]+)/i", $agent, $opera)) return array("b"=>'Opera',"v"=>$opera[1]);
if ($browser == 'MSIE') {
preg_match("/(Maxthon|Avant Browser|MyIE2)/i", $agent, $ie);
if ($ie) return array("b"=>$ie[1].' based on IE',"v"=>$version);
return array("b"=>'IE',"v"=>$version);
}
if ($browser == 'Firefox') {
preg_match("/(Flock|Navigator|Epiphany)\/([0-9.]+)/", $agent, $ff);
if ($ff) return array("b"=>$ff[1],"v"=>$ff[2]);
}
if ($browser == 'Opera' && $version == '9.80') return array("b"=>'Opera',"v"=>substr($agent,-5));
if ($browser == 'Version') return array("b"=>'Safari',"v"=>$version);
if (!$browser && strpos($agent, 'Gecko')) return array("b"=>'Browser based on Gecko',"v"=>'');
return array("b"=>$browser,"v"=>$version);
}
function user_OS($agent)
{
$opsys='';
// если с мобильных
if (strstr($agent, 'J2ME/MIDP')) $opsys .= "Мобильная ";
// сами ОСи
if ( strstr ($agent, 'Win') ) :$opsys .= "Windows";
elseif ( strstr($agent, 'Linux') ) :$opsys .= "Linux";
elseif ( strstr ($agent, 'Unix') ) :$opsys .= "Unix";
elseif ( strstr ($agent, 'Mac') ) :$opsys .= "Macintosh";
elseif ( strstr ($agent, 'OS/2') ) :$opsys .= "OS/2";
elseif ( strstr ($agent, 'BeOS') ) :$opsys .= "BeOS";
else :$opsys .= "Другая";
endif;
return $opsys;
}
function detectSpider($agent)
{
$engines = array( array('Aport', 'Aport robot'),
array('Google', 'Google'),
array('Yandex', 'Yandex'),
array('Mail.Ru', 'Mail.Ru Bot'),
array('www.uz', 'WWW.UZ'),
array('msnbot', 'MSN'),
array('Rambler', 'Rambler'),
array('Yahoo', 'Yahoo'),
array('AbachoBOT', 'AbachoBOT'),
array('accoona', 'Accoona'),
array('AcoiRobot', 'AcoiRobot'),
array('ASPSeek', 'ASPSeek'),
array('CrocCrawler', 'CrocCrawler'),
array('Dumbot', 'Dumbot'),
array('FAST-WebCrawler', 'FAST-WebCrawler'),
array('GeonaBot', 'GeonaBot'),
array('Gigabot', 'Gigabot'),
array('Lycos', 'Lycos spider'),
array('MSRBOT', 'MSRBOT'),
array('Scooter', 'Altavista robot'),
array('AltaVista', 'Altavista robot'),
array('WebAlta', 'WebAlta'),
array('IDBot', 'ID-Search Bot'),
array('eStyle', 'eStyle Bot'),
array('Scrubby', 'Scrubby robot'),
array('YaDirectBot', 'Yandex Direct')
);
foreach ($engines as $engine)
{
if (stristr($agent, $engine[0]))
{
if ($engine[0]=='www.uz') {if (substr(strrev($agent),0,6)!="zu.www" && strlen($agent)==6) return ($engine[1]); }
else return($engine[1]);
}
}
return (false);
}
function getDomen($path, $real_path, $page_ref)
{
$domen='';
if (strcasecmp($path,$real_path)!=0) return false;
if (strlen($path)<11) return false;
if (strlen($page_ref)>=11)
{
$k=parse_url($page_ref);$domen.=$k[host];
return $domen;
}
return false;
}
/*
* Класс для работы с БД
*/
class MyDB
{
public $db = null;
private $result = null;
public function __construct($host, $user, $password, $base, $port = null, $charset = 'utf8')
{
$this->db = new mysqli($host, $user, $password, $base, $port);
$this->db->set_charset($charset);
}
public function query($query)
{
if(!$this->db) return false;
if(is_object($this->result))
$this->result->free();
$this->result = $this->db->query($query);
if($this->db->errno)
logger("analyzer_".date('dmY', time()).".log", chr(10).chr(13)."===ERROR #==".$this->db->errno."-::::-".$this->db->error."===QUERY===".$query.chr(13).chr(10)."-");
if(is_object($this->result))
{
while($row = $this->result->fetch_assoc())
$data[] = $row;
return $data;
}
else if($this->result == FALSE) return false;
else return $this->db->affected_rows;
}
}
function getmicrotime(){
if(isset($GLOBALS['SYSTEM']['time_end'])){ $GLOBALS['SYSTEM']['time_last'] = $GLOBALS['SYSTEM']['time_end']; }
list($usec, $sec) = explode(" ",microtime());
$GLOBALS['SYSTEM']['time_end'] = ((float)$usec + (float)$sec);
return $GLOBALS['SYSTEM']['time_end'];
}
function addtoqueries(&$queries,$query){
foreach($query as $key=>$value)
{
if ($value!='') $queries[]=$value;
}
}
function logger($file,$text){
$path_for_log ='/var/www/analyzer/logs/';
$f = fopen($path_for_log.$file, "a");
fwrite($f, $text);
fclose($f);
}
?>
Параметры сервера:
Кол-во процессоров: 8 шт
Тип процессоров: Intel(R) Xeon(R) CPU E5430 @ 2.66GHz
ОЗУ: 16 gb
HDD 1: 60 gb
HDD 2: 500 gb
Уважаемые пользователи.
Что можно сделать с нашей БД чтобы наш проект не зависал, чтобы MySQL работал изумительно ?
буду Очень признателен если обсудим мою проблему и найдем решения. Заранее спасибо всем!