Автор Тема: Високо натоварнане на машината защо  (Прочетена 5821 пъти)

abadon

  • Напреднали
  • *****
  • Публикации: 510
  • Distribution: Debian
  • Window Manager: KDE
    • Профил
    • WWW
Здравейте,

Имам виртуален сървър с Ubuntu hardy, kernel 2.6.24-26-virtual. На този сървър има единствено mysql и apache mod_worker със cgi-php. Като се навържат около 50-100 юзера за този сървър лоуда му скача до небесата до нещо такова:
Цитат
top - 17:23:39 up  2:04,  1 user, load average: 22.16, 26.52, 22.14
Tasks: 123 total,  24 running,  99 sleeping,   0 stopped,   0 zombie
Cpu(s): 20.0%us,  8.7%sy,  0.0%ni, 68.5%id,  2.3%wa,  0.1%hi,  0.4%si,  0.0%st
Mem:   2075816k total,  1672948k used,   402868k free,    47868k buffers
Swap:   401400k total,        0k used,   401400k free,  1031368k cached

И сайта който се хоства почва да зарежда страшно бавно, да дава грешки от рода на Internal server error. Както виждате има свободен рам, CPU-то не е натоварено но защо лоада е такъв голям?

Предварително благодаря!
Активен

Успешното Boot-ване на Windows завършва с рестарт!!!
You are registered as user #382190 with the Linux Counter
Всеки пост - отговор на въпрос

neter

  • Global Moderator
  • Напреднали
  • *****
  • Публикации: 3408
  • Distribution: Debian, SailfishOS, CentOS
  • Window Manager: LXDE, Lipstick
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #1 -: Feb 18, 2010, 17:37 »
Защото имаш голяма хард дискова активност, най-вероятно става дума за четене и писане в база данни. Причината за това голямо писане може да е бавен хард диск (нямам идея какви използваш), големи SQL (MySQL?) заявки, подавани често от кода на сайта (PHP ли е?), които имат нужда от оптимизация, лошо дефинирани индекси, счупени таблици... Може да се наложи доста да се поровиш из кода на сайта и логовете на SQL сървъра, ако не си писал ти кода, докато установиш на какво се дължи това голямо четене/писане. Някаква помощ може да ти окаже mtop ;)
Активен

"Да си добре приспособен към болно общество не е признак за добро здраве" - Джиду Кришнамурти

dejuren

  • Напреднали
  • *****
  • Публикации: 1025
  • Distribution: Ubuntu, RedHat
  • Window Manager: lxde KDE4
    • Профил
Re: Високо натоварнане на машината защо
« Отговор #2 -: Feb 18, 2010, 17:59 »
Моите две стотинки: 2.3% не е огромно натоварване на вх/изх операции, но това е все пак само снимка на топ, напълно възможно е neter да е абсолютно прав и във времето това да става значително повече. А и едно разделяне на mysql и apache на ралични машини винаги е за препоръчване.
Активен

http://webchat.freenode.net/?channels=ubuntu-bg
The quieter you become, the more you are able to hear.
Две седмици цъкане с мишката спестяват два часа четене на документацията.

VladSun

  • Напреднали
  • *****
  • Публикации: 2166
    • Профил
Re: Високо натоварнане на машината защо
« Отговор #3 -: Feb 18, 2010, 19:37 »
А защо ползваш PHP в CGI режим? Имаш две версии на PHP ли?
Активен

KISS Principle ( Keep-It-Short-and-Simple )
http://openfmi.net/projects/flattc/
Има 10 вида хора на този свят - разбиращи двоичния код и тези, които не го разбират :P

abadon

  • Напреднали
  • *****
  • Публикации: 510
  • Distribution: Debian
  • Window Manager: KDE
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #4 -: Feb 18, 2010, 22:05 »
@neter Благодаря за съвета. Сайта е на php платен CMS така че заявките към mysql-а не съм ги писал аз. В  /var/log/mysql/mysql-slow.log, /var/log/mysql.log и /var/log/mysql.err няма никакво съдържание. mtop-а показва:
Цитат
load average: 0.61, 0.61, 0.46 mysqld 5.0.51a-3ubuntu5.4 up 0 day(s),  6:40 hrs
1 threads: 1 running, 7 cached. Queries/slow: 10.9M/0 Cache Hit: 99.41%
Opened tables: 0  RRN: 4.7K  TLW: 26.5K  SFJ: 0  SMP: 0  QPS: 509

ID       USER     HOST             DB           TIME   COMMAND STATE        INFO
234440   root     localhost                            Query                show full processlist


Мисля че всичко е наред? Струва ли си да пипам нещо по него? Да му дам конфигурацията?

@dejuren Това за разделянето на mysql-а и apache-то го знам обаче към текущия момент нямам възможност как да го реализирам.

@VladSun ползвам php-то в CGI режим защото в Debian/Ubuntu пакетите са направени така че щом ползвам worker apache ми се деинсталира mod_php-то понеже имало някакви секюрити проблеми с php-то и работата му с нишки. Единствения вариант който ми дойде на ум е да го ползвам така.
Активен

Успешното Boot-ване на Windows завършва с рестарт!!!
You are registered as user #382190 with the Linux Counter
Всеки пост - отговор на въпрос

neter

  • Global Moderator
  • Напреднали
  • *****
  • Публикации: 3408
  • Distribution: Debian, SailfishOS, CentOS
  • Window Manager: LXDE, Lipstick
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #5 -: Feb 18, 2010, 23:11 »
Какви са останалите параметри на машината? Засега видяхме само количеството на RAM паметта. А каква част от тази памет се използва реално (команда 'free -m' и гледане на buffers отделно в натоварени и ненатоварени моменти)? Питам, защото предполагам, че тези 2ГБ са ти достатъчни и можеш да изключиш swap-а напълно. Забелязал съм малко подобрение в работата на системата, когато към нея няма закачен swap, стига наличната памет да е достатъчна. И това не е случайно - дори и при зададен swappiness 1 и реално не записване нищо в swap-a, винаги остава поне някаква проверка на swap-а, която се бърка из процесите. А задаване на swappiness 1 на практика е излишно, стойността му винаги е по-голяма, вероятността за попадане дори на най-малка информация в swap-a се увеличава, а всяко попадане е свързано с I/O от хард диска, който е много по-бавен от RAM паметта. Аз не използвам swap на машините си - купуването на още една плочка RAM ми коства много по-малко нерви и пари от управлението на swap-a. И все пак говорим за постоянно наблюдавани машини (независимо дали ръчно или чрез набор от скриптове), каквато предполагам е и твоята.
Друго, което използвам, е настройване на MySQL да използва /dev/shm (tmpfs дяла) като временна папка - също се забелязва малко подобрение. Можеш да добавиш следния параметър към изпълнението на mysqld_safe:
Цитат
--tmpdir=/dev/shm
Ако имаш скрипт в /etc/init.d, който използваш за пускане на MySQL, добави параметъра там към изпълнението на mysqld_safe в start().
Наблюдавай mtop по-дълго, и в момент, в който имаш повече едновременни потребители - ако го гледаш в момент, в който нямаш много потребители, и тези потребители изпълняват заявки, които се изпълняват по-бързо от 1 секунда (каквото е минималното време за обновяване екрана на mtop), много е вероятно да не видиш нищо. Целта ти с mtop е да засечеш тежки заявки, или затлачващи се леки и тежки заявки в натоварен момент, за да видиш можеш ли да оптимизираш някоя (в твоя случай с платения готов CMS най-вероятно няма да се наложи оптимизация на заявките), и по-важно, да разбереш имаш ли нужда от наместване параметрите на MySQL (описаните в my.cnf), за да разпределиш ресурсите на машината за твоите нужди.
Покажи съдържанието на конфигурационните файлове на MySQL и Apache - добрият подбор на параметри там води до драстични разлики в натовареността. Можеш да се зачетеш в документацията на MySQL за тези параметри, както и за допълнителни параметри, които текущо нямаш описани в my.cnf, но може да има нужда да добавиш, за да разбереш как действат и с какви стойности биха отговаряли на твоите нужди. В момента ще спомена само key_buffer - задавай го около половината от RAM паметта си (в твоя случай например 1024М).
Активен

"Да си добре приспособен към болно общество не е признак за добро здраве" - Джиду Кришнамурти

abadon

  • Напреднали
  • *****
  • Публикации: 510
  • Distribution: Debian
  • Window Manager: KDE
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #6 -: Feb 18, 2010, 23:50 »
free -m през повечето време показва нещо подобно:
Цитат
             total       used       free     shared    buffers     cached
Mem:          2027       1932         94          0         47       1373
-/+ buffers/cache:        511       1515
Swap:          391          0        391

в mtop-а дори и в натоварените моменти не виждах нищо само за 10-тина мин 2-3 заявки, но това мисля че е нормално.
А конфигурациите ми са така:
/etc/mysql/my.cnf
Цитат
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port            = 3306
socket          = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket          = /var/run/mysqld/mysqld.sock
nice            = 0
open_files_limit= 8192

[mysqld]
#
# * Basic Settings
#

#
# * IMPORTANT
#   If you make changes to these settings and your system uses apparmor, you may
#   also need to also adjust /etc/apparmor.d/usr.sbin.mysqld.
#

user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
language        = /usr/share/mysql/english
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address            = 127.0.0.1
#
# * Fine Tuning
#
max_user_connections    = 25
key_buffer                              = 16M
join_buffer                             = 1M
max_allowed_packet              = 128M #default is 16MB
thread_stack                    = 128K
thread_cache_size               = 128
max_connections         = 500
interactive_timeout             = 10
wait_timeout                    = 10
connect_timeout                 = 10
table_cache             = 1024
record_buffer                   = 1M
sort_buffer_size                = 2M
read_buffer_size                = 2M
max_connect_errors              = 10 # Try number of CPU's*2 for thread_concurrency thread_concurrency=8
thread_concurrency      = 8
myisam_sort_buffer_size = 64M
#
# * Query Cache Configuration
#
query_cache_limit       = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
#log            = /var/log/mysql/mysql.log
#
# Error logging goes to syslog. This is a Debian improvement :)
#
# Here you can see queries with especially long duration
#log_slow_queries       = /var/log/mysql/mysql-slow.log
#long_query_time = 5
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id              = 1
#log_bin                        = /var/log/mysql/mysql-bin.log
expire_logs_days        = 10
max_binlog_size         = 100M
#binlog_do_db           = include_database_name
#binlog_ignore_db       = include_database_name
#
# * BerkeleyDB
#
# Using BerkeleyDB is now discouraged as its support will cease in 5.1.12.
skip-bdb
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
# You might want to disable InnoDB to shrink the mysqld process by circa 100MB.
#skip-innodb
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem



[mysqldump]
quick
quote-names
max_allowed_packet      = 16M

[mysql]
no-auto-rehash  # faster start of mysql but no tab completition

[isamchk]
key_buffer              = 64M
sort_buffer             = 64M
read_buffer             = 16M
write_buffer            = 16M

[myisamchk]

key_buffer              = 64M
sort_buffer             = 64M
read_buffer             = 16M
write_buffer            = 16M

[mysqlhotcopy]

interactive-timeout

#
# * NDB Cluster
#
# See /usr/share/doc/mysql-server-*/README.Debian for more information.
#
# The following configuration is read by the NDB Data Nodes (ndbd processes)
# not from the NDB Management Nodes (ndb_mgmd processes).
#
# [MYSQL_CLUSTER]
# ndb-connectstring=127.0.0.1


#
# * IMPORTANT: Additional settings that can override those from this file!
# The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/
/etc/apache2/apache2.conf
Цитат
#
# Based upon the NCSA server configuration files originally by Rob McCool.
#
# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.2/ for detailed information about
# the directives.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned. 
#
# The configuration directives are grouped into three basic sections:
#  1. Directives that control the operation of the Apache server process as a
#     whole (the 'global environment').
#  2. Directives that define the parameters of the 'main' or 'default' server,
#     which responds to requests that aren't handled by a virtual host.
#     These directives also provide default values for the settings
#     of all virtual hosts.
#  3. Settings for virtual hosts, which allow Web requests to be sent to
#     different IP addresses or hostnames and have them handled by the
#     same Apache server process.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "/var/log/apache2/foo.log"
# with ServerRoot set to "" will be interpreted by the
# server as "//var/log/apache2/foo.log".
#

### Section 1: Global Environment
#
# The directives in this section affect the overall operation of Apache,
# such as the number of concurrent requests it can handle or where it
# can find its configuration files.
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the LockFile documentation (available
# at <URL:http://httpd.apache.org/docs-2.1/mod/mpm_common.html#lockfile>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#<IfModule !mpm_winnt.c>
#<IfModule !mpm_netware.c>
LockFile /var/lock/apache2/accept.lock
#</IfModule>
#</IfModule>

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 2

##
## Server-Pool Size Regulation (MPM specific)
##

# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients           20
    MaxRequestsPerChild   1024
</IfModule>

# worker MPM
# StartServers: initial number of server processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
    StartServers          8
    MaxClients          400
    MinSpareThreads      40
    MaxSpareThreads     400
    ThreadsPerChild      50
    MaxRequestsPerChild   1024
</IfModule>

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#

AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
</Files>

#
# DefaultType is the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain


#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., http://www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog /var/log/apache2/error.log

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

# Include module configuration:
Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf

# Include all the user configurations:
Include /etc/apache2/httpd.conf

# Include ports listing
Include /etc/apache2/ports.conf

#
# The following directives define some format nicknames for use with
# a CustomLog directive (see below).
# If you are behind a reverse proxy, you might want to change %h into %{X-Forwarded-For}i
#
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

#
# ServerTokens
# This directive configures what you return as the Server HTTP response
# Header. The default is 'Full' which sends information about the OS-Type
# and compiled in modules.
# Set to one of:  Full | OS | Minor | Minimal | Major | Prod
# where Full conveys the most information, and Prod the least.
#
ServerTokens Prod

#
# Optionally add a line containing the server version and virtual host
# name to server-generated pages (internal error documents, FTP directory
# listings, mod_status and mod_info output etc., but not CGI generated
# documents or custom error documents).
# Set to "EMail" to also include a mailto: link to the ServerAdmin.
# Set to one of:  On | Off | EMail
#
ServerSignature Off



#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# Putting this all together, we can internationalize error responses.
#
# We use Alias to redirect any /error/HTTP_<error>.html.var response to
# our collection of by-error message multi-language collections.  We use
# includes to substitute the appropriate text.
#
# You can modify the messages' appearance without changing any of the
# default HTTP_<error>.html.var files by adding the line:
#
#   Alias /error/include/ "/your/include/path/"
#
# which allows you to create your own set of files by starting with the
# /usr/share/apache2/error/include/ files and copying them to /your/include/path/,
# even on a per-VirtualHost basis.  The default include files will display
# your Apache version number and your ServerAdmin email address regardless
# of the setting of ServerSignature.
#
# The internationalized error documents require mod_alias, mod_include
# and mod_negotiation.  To activate them, uncomment the following 30 lines.

#    Alias /error/ "/usr/share/apache2/error/"
#
#    <Directory "/usr/share/apache2/error">
#        AllowOverride None
#        Options IncludesNoExec
#        AddOutputFilter Includes html
#        AddHandler type-map var
#        Order allow,deny
#        Allow from all
#        LanguagePriority en cs de es fr it nl sv pt-br ro
#        ForceLanguagePriority Prefer Fallback
#    </Directory>
#
#    ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
#    ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
#    ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
#    ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
#    ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
#    ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
#    ErrorDocument 410 /error/HTTP_GONE.html.var
#    ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
#    ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
#    ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
#    ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
#    ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var
#    ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
#    ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
#    ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
#    ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
#    ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var



# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
Include /etc/apache2/conf.d/

# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/


Процесора ми е това:
Цитат
cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 23
model name      : Intel(R) Xeon(R) CPU           E5405  @ 2.00GHz
stepping        : 10
cpu MHz         : 2000.071
cache size      : 6144 KB
fdiv_bug        : no
hlt_bug         : no
f00f_bug        : no
coma_bug        : no
fpu             : yes
fpu_exception   : yes
cpuid level     : 13
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss nx lm constant_tsc up arch_perfmon pebs bts pni ssse3 cx16 sse4_1 lahf_lm
bogomips        : 4000.14
clflush size    : 64
Активен

Успешното Boot-ване на Windows завършва с рестарт!!!
You are registered as user #382190 with the Linux Counter
Всеки пост - отговор на въпрос

foxb

  • Напреднали
  • *****
  • Публикации: 175
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #7 -: Feb 19, 2010, 00:14 »
Да беше дал и следващите редове от топ, че да видим какво ти товари сървъра...

Лоад авераге 22 означава, че 22 процеса се борят за процесора...

Прегледай си конфигурацията на апаче - за повече поребители трябват специални настройки. В инатернет има примери.

Прегледай си и настройките на Mysql

gat3way

  • Напреднали
  • *****
  • Публикации: 6050
  • Relentless troll
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #8 -: Feb 19, 2010, 01:40 »
Мани ги тия секюрити проблеми, сума ти PHP функции не са thread-safe, нямат изгледи да станат и поради тази причина PHP с mpm_worker е грозно занимание, не невъзможно, ама грозно. mpm_worker е добра идея иначе за статично съдържание, но в случая с PHP като cgi, цялото предимство тотално се губи. Реално погледнато имаш многонишков уеб сървър, който обаче форква по един нов процес за всяка заявка към PHP скрипт. Къде точно ти е файдата като го сравниш с prefork mpm-то?
Активен

"Knowledge is power" - France is Bacon

zeridon

  • Killmode enabled
  • Administrator
  • Напреднали
  • *****
  • Публикации: 1398
  • Distribution: Debian/Ubuntu
  • Window Manager: console/Gnome
  • BOfH
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #9 -: Feb 19, 2010, 10:29 »
По принцип самото cgi е бавничко. Замисли се да пробваш с fast-cgi или fcgi. Ограничение в случая ти е че цмс-а най вероятно е енкоднат с нещо и може би не ги поддържа. Друго което забелязах е неоправдано големия пакет на mysql-a едва ли са му необходими чак 128М (а и така ще освободиш малко памет за апача).

Също както каза gat3way с тая конфигурация губиш удобствата на worker-a. Най вероятно затлачването идва от опита да скочат много апачета горе едновременно.
Активен

Внмимавай имам клещи за кабел
http://www.netsecad.com/
http://theregister.co.uk/odds/bofh/

gat3way

  • Напреднали
  • *****
  • Публикации: 6050
  • Relentless troll
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #10 -: Feb 19, 2010, 10:54 »
Тази конфигурация е всъщност по-лоша от mpm_prefork. При mpm_prefork имаш pool от apache процеси и ако има свободен такъв, той поема заявката (ако нямаш, се форква нов такъв, стига да не удариш MaxClients лимита). Дори да се форкне нов процес, той унаследява адресното пространство на родителя си, при това това е COW процес - няма копиране на страници памет, докато няма писане по тях.

В случаят с CGI, винаги се форква нов процес, нямаш pool с вече форкнати такива. Като добавка, форкнатия процес вика execve() за да зареди php5-cgi, което е свързано с I/O операции. Освен че така трошиш повече процесорно време, I/O, също така хабиш и повече оперативна памет. Последното е защото apache child-овете споделят общо адресно пространство с родителския процес - страниците в паметта са им споделени, поне докато не настъпи модификация. php5-cgi процесите не споделят общи страници памет, с изключение на тази, заета от динамичните библиотеки, с които php5-cgi е линкнат. Голяма част от това което е било общо за apache процесите, в случаят с cgi се зарежда отделно в паметта при стартирането на нов cgi процес.
Активен

"Knowledge is power" - France is Bacon

abadon

  • Напреднали
  • *****
  • Публикации: 510
  • Distribution: Debian
  • Window Manager: KDE
    • Профил
    • WWW
Re: Високо натоварнане на машината защо
« Отговор #11 -: Feb 19, 2010, 13:26 »
@zeridon не знах че cgi е различно от fcgi с което съм. А относно mysql-а и големината на пакета трябват ми 128МВ понеже толкова е лимита за качване на видео файл във сайта ми. Въпреки че файловете не ги блъскам в базата данни а си седят на харда нещо се сбозва ако го намаля. Колкото сложа за лимит на него толкова голям видео файл мога да кача. Такава стойност съм задал и в php.ini

Ще гледам скриптовете и ако може ще го намаля.

@gat3way интересни неща казваш. В началото преди сайта да влезе в продукшън тествах първо  mpm_prefork и mod_php но утрепвах процесора за норматив. А сега с тази конфигурация процесора се разтовари значително, но пък трепя повече рам. Въпреки всичко с worker-а обработвам към 50% повече заявки. Пък и вече сайта се натовари нон стоп има минимум по 50-60 човека онлайн а в пиковите моменти в който лоуда става кошмарен има по 150-160 човека и нямам прозорец да сменям така радикално конфигурацията.

След съветите на всички Вас стигам до извода че MySQL-а не е както трябва. Защото след като намерих този скрипт и направих нещата които ме съветва load-а и в най-пиковите моменти не е повече от 10, но пък нещо се получават грешки от mysql-а....
Активен

Успешното Boot-ване на Windows завършва с рестарт!!!
You are registered as user #382190 with the Linux Counter
Всеки пост - отговор на въпрос