An article:
Gearman Introduction, investigation, test and principle analysis
What is Gearman?
It is a distributed program call framework that accomplishes cross-language invocation and is suitable for running work tasks in the background. It was originally a 2005 Perl version, and in 2008 the C + + version was released. Most of the current source code is (Gearmand service job Server) C + +, each API implemented in a variety of language versions. PHP's client API and the worker API are implemented as C extensions, and the PHP official website has this extension in both English and Chinese documents.
Three roles in the Gearman architecture
Client: The initiator of the request, the demand side of the work task (can be C, PHP, Java, Perl, Mysql UDF, etc.)
Job Server: The requesting dispatcher, who forwards the client's request to the appropriate worker (Gearmand service Process creation)
Worker: The handler for the request (can be C, PHP, Java, Perl, and so on)
How does the Gearman work?
As you can see, the Gearman Client api,gearman Worker api,gearman Job Server is provided by the Gearman itself, and we only need to invoke it in the application. Currently, client and worker APIs are rich.
Throughput capacity of Gearman
After the test, the results are as follows:
System environment: ubuntu-14.0.4 1 CPU 4 cores 2G memory (virtual machine)
Default startup:./gearmand-d
client.php
<?PHPEcho"Starting ...",Microtime(true), "\ n";$GMC=Newgearmanclient ();$GMC->setcompletecallback (function($task){//echo $task->data (), "\ n";});$GMC->addserver ("127.0.0.1", 4730); for($i= 0;$i< 100000;$i++) { $GMC->addtaskbackground ("reserve", "just test it",NULL,$i);}$GMC-runtasks ();Echo"End ...",Microtime(true), "\ n";
worker.php
<?PHP$GMW=NewGearmanworker ();$GMW->addserver ("127.0.0.1", 4730);$GMW->addfunction ("reserve",function($job) { if($job->unique () = = 99999) { Echo Microtime(true), "\ n"; } return Strrev($job-workload ());}); while($GMW->work ());
Start a job server instance: Job Server ip:127.0.0.1 port:4730
Start a worker:php worker.php
The worker registers the reserve function and returns the client's job string after it is reversed.
The message for the client work task is: just test it (12 bytes)
Sync: 4100/s Async: 25700/s
memcached memory quasi-persistent throughput capability test./gearmand-d-Q libmemcached--libmemcached-servers=127.0.0.1:11211
Client Delivery 100,000 jobs: 16400/s
Gearman Typical deployment structure
As you can see, the features supported by Gearman:
1. High Availability
Starting two job servers, they are stand-alone service processes that have their own memory queues. When one of the job server processes fails, another job server can dispatch normally. (the Worker API and the client API can switch between job server failures). At any time we can shut down a worker, even if that worker is working on a work task (Gearman will not let the job being executed be lost because the worker is long connected to the job server at work, so once the worker has an exception, Job server can quickly perceive and re-distribute the work that the exception worker is doing just now.
2. Load Balancing (the Gearman protocol will be explained in detail)
The job server does not actively dispatch work tasks, but instead wakes the worker from the idle state to the job server to actively fetch the work task.
3. Expandable
Loosely coupled interfaces and stateless jobs, you only need to start a worker and register to the job server cluster. The newly joined worker does not have any impact on the existing system.
4. Distributed
Gearman is a distributed task distribution framework in which worker and job server,client communicate with the job server based on a TCP socket connection.
5. Queue mechanism
Gearman built-in memory queue, the default queue maximum capacity of 300W, you can configure the maximum support 2^32-1, that is 4 294 967 295.
6. High Performance
As the core of Gearman, the job server is implemented in C/s + +, and because it is just a simple task dispatch, the bottleneck of the system is not on the job server.
Two kinds of work tasks
Background work task Background job--timing diagram
As the figure shows, after the client submits the Job,job server and returns the job_created response after the successful receipt, the client disconnects from the job server. No matter what happens in the future, the client is not concerned about it. Similarly, the client side of the job execution results is not available through the Gearman message framework.
General work task Non-background job--timing Diagram
As the graph shows, the client side in the job execution of the entire process, and the job server side of the link is maintained, which also gives the job after the completion of the execution of the job server to the client to provide a path. At the same time, in the job execution process, the client side can also initiate the job status query. This, of course, requires the support of the worker side.
About persistence
The issue of queue persistence is an issue worth considering. Persistence inevitably affects high performance. Gearman supports the persistence of background work tasks, supports drizzle, MySQL, memcached persistence. For background Jo B,job Server, which is submitted by the client, it ispersisted to the external persistence queue in addition to being distributed in the memory queue. Once a problem restart occurs in the job server, the background job in the external persistence queue is restored to memory and participates in the new dispatch of the job server. This guarantees that the background job that has been committed is not lost due to an exception from the job server. And I test that if persistence is turned on, the background work task will first write the work task to the persistent media, then into the memory queue, and then execute. Non-background work tasks, because the client and the job server is to maintain a long connection state, if the work task execution exception, the client can be flexible processing, so there is no need to persist.
An issue in the Gearman framework
As seen from the typical deployment structure, there is no connection between the two job servers. That is, the background job is not shared between the job servers. If you make two job servers point to the same persistent queue, you can have two job Serer backup each other. But in fact, this is not feasible. The background job in the persistence queue is not transferred to the memory queue until the job server is started. In other words, if the job server1 is down and never starts and the job Server2 is up and running, the uncommitted background job that is submitted to the job Server1 before the job Server1 goes down will always stay in the persistence queue and not be executed. In addition, if multiple job server instances point to the same persistent queue, restarting multiple job server instances causes the work tasks in the durable queue to be loaded multiple times, causing the message to be processed repeatedly.
I recommend the deployment structure
A quasi-persistent queue that uses memcached for background work tasks, preferably memcached and the different machines in the job server network. Two services for two machines are less likely to be hung at the same time, while also guaranteeing high performance. And memcached should be for two mutually independent instances to prevent problems in their Gearman framework above. We can make a monitoring script that, if a job server exits unexpectedly, can be restarted, and maximizes the availability of the job server.
Management tools for Gearman
There is now a management tool, Https://github.com/brianlmoon/GearmanManager, But only support php-5.2, but can modify support php-5.4, I recommend if you use PHP as a worker process, use more than php-5.4 version. The tool design method can be used for reference, can be better management Gearman worker. Time is limited, not yet in-depth study.
Application Scenarios
1. The Linux crontab,php script is responsible for generating the job, distributing the task to multiple servers periodically for concurrent execution. Can take the place of our more crontab work task at present.
2. SMS Message Sending
3. Asynchronous log
4. Cross-language calls to each other (for intensive computing needs, can be implemented in C, PHP calls directly)
5. other time-consuming scripts
Gearman installation (Unbuntu)
1. Download
#wget https://launchpadlibrarian.net/165674261/gearmand-1.1.12.tar.gz
2. Installing dependent Packages
#sudo apt-get Install Libboost1.55-all-dev gperf libevent libevent-dev uuid Libmemcached-dev
#tar ZXVF gearmand-1.1.12.tar.gz
#cd gearmand-1.1.12.tar.gz
#./configure--prefix=/home/phpboy/server/gearman
#make & make Install
3. Start
a) Default boot
./gearman-d
b) Support memcached quasi-persistence
./gearmand-d-Q libmemcached--libmemcached-servers=127.0.0.1:11211
4. Installing the PHP gearman extension
#wget http://pecl.php.net/get/gearman-1.1.2.tgz
#tar ZXVF GEARMAN-1.1.2.TGZ#CD gearman-1.1.2
#phpize
#./configure--with-php-config=php-config
#make & make Install
The 5.php Client API is tested with the PHP worker API and can be used as an example of my tests above
Attached Gearmand (simple description of the startup parameters of the job server)
-b,–backlog=backlog maximum number of connection request queues
-d,–daemon Daemon Daemon Process
-f,–file-descriptors=fds number of file descriptors that can be opened
-h,–help
-l,–log-file=file log File
-l,–listen=address Open the Listening address
-p,–port=port Open the Listening port
-p,–pid-file=file file PID File
protocol used by-r,–protocol=protocol
-q,–queue-type=queue Persistent queue type
-t,–threads=threads number of I/O threads
Valid user name for the-u,–user=user process
Libdrizzle Options:
--libdrizzle-host=host host of server.
--libdrizzle-port=port Port of server.
--libdrizzle-uds=uds Unix domain socket for server.
--libdrizzle-user=user user name for authentication.
--libdrizzle-password=password password for authentication.
--libdrizzle-db=db Database to use.
--libdrizzle-table=table table to use.
--libdrizzle-mysql use MySQL protocol.
Libmemcached Options:
--libmemcached-servers=server_list LIST of Memcached servers to use.
Libsqlite3 Options:
--libsqlite3-db=db Database file to use.
--libsqlite3-table=table table to use.
LIBPQ Options:
--libpq-conninfo=string PostgreSQL connection Information STRING.
--libpq-table=table table to use.
HTTP Options:
--http-port=port port to listen on.
Attached Gearman communication protocol, personal translation and understanding:
Umbrella
Gearman work on TCP, the default port for 4730,client and job server, worker and job server are based on this TCP socket connection. The client is the initiator of the task, the worker is the task performer who can register the handler, and the job server is the dispatcher of the work. The protocol contains two parts of the request message and the response message, and all packets sent to the job server (the data portion of the TCP segment) are considered request messages, and all packets sent from the job server (the data portion of the TCP segment) are considered to be response messages. The communication between the worker or client and the job server is based on the binary data stream, but there is also a line-text protocol-based communication in the management client.
The newspaper style of the request
The newspaper style of response
、
Binary Package
The request message and the response message are packaged in a binary package. A binary package header and an optional data section,
The composition of the header
A. Type of message, request message or response message, 4 bytes
"\0req" Request message
"\0res" Response message
B. Packet type, high (Large) byte order (network byte order), 4 bytes possible types have
Type value name Message type sender
1 Can_do REQ Worker
2 Cant_do REQ Worker
3 Reset_abilities REQ Worker
4 Pre_sleep REQ Worker
5 (unused)--
6 NOOP RES Worker
7 Submit_job REQ Client
8 job_created RES Client
9 Grab_job REQ Worker
Ten No_job RES Worker
Job_assign RES Worker
Work_status REQ Worker
Work_complete REQ Worker
Work_fail REQ Worker
Get_status REQ Client
Echo_req REQ Client/worker
Echo_res RES Client/worker
SUBMIT_JOB_BG REQ Client
ERROR RES Client/worker
Status_res RES Client
Submit_job_high REQ Client
set_client_id REQ Worker
Can_do_timeout REQ Worker
All_yours REQ Worker
Work_exception REQ Worker
Option_req REQ Client/worker
Option_res RES Client/worker
Work_data REQ Worker
Work_warning REQ Worker
Grab_job_uniq REQ Worker
Job_assign_uniq RES Worker
SUBMIT_JOB_HIGH_BG REQ Client
Submit_job_low REQ Client
SUBMIT_JOB_LOW_BG REQ Client
submit_job_sched REQ Client
Submit_job_epoch REQ Client
C. Optional data part length, high (large) byte order (network byte order), 4 bytes, can represent a value of 4294967295
In the data section, the parts of the data section are separated by a null character.
Description of specific package types
Request messages that both client and worker can send:
Echo_req
When the job server receives a request message of this packet type, it simply generates a packet type of echo_res, while the data portion of the request message is used as a message in the data portion of the response message. Primarily for testing or commissioning
Such as:
Client-to-Job Server
\0req Message Type
XX A0 (Packet Type:echo_erq)
XX 4 (Packet length)
The Workload test (a)
Response messages that both client and worker can receive:
Echo_res
The packet type echo_res response message sent when the job server responds to a ECHO_REQ message
Such as:
Client, Job Server
\0res Message Type
XX A1 (Packet type:echo_ers)
XX 4 (Packet length)
The Workload test (a)
ERROR
When a job server error occurs, you need to notify the client or worker
Request message sent by client: (only request messages that can be sent by client)
Submit_job, Submit_job_bg,submit_job_high, Submit_job_high_bg,submit_job_low, SUBMIT_JOB_LOW_BG
When the client has a work task that needs to be run, the corresponding request message is submitted, and the Job server response packet type is the job_created data part of the job handle response message. Submit_job for normal tasks, the client gets the status update and the notification task has completed the response; SUBMIT_JOB_BG is an asynchronous task, the client does not care about the completion of the task; Submit_job_high is a high-priority task, SUBMIT_JOB_HIGH_BG is a high-priority asynchronous task, and Submit_job_low is a low-priority work task, submit_job_low_bg a low-priority asynchronous task.
Such as:
Client-to-Job Server
\0req (Message type)
XX 7 (Packet type:submit_job)
XX 0d (Packet length)
The Reverse\0 (Function)
XX (Unique ID)
The Workload test (a)
Submit_job_sched
Similar to SUBMIT_JOB_BG, this type of work task is not executed immediately, but at some time in the set.
Such as:
Client-to-Job Server
\0req (Message type)
XX (Packet type:submit_job_sched)
XX 0d (Packet length)
The Reverse\0 (Function)
XX (Unique ID)
(Minute 0-59)
(Hour 0-23)
(Day of month 1-31)
(Day of month 1-12)
(Day of week 0-6)
The Workload test (a)
Submit_job_epoch
As with submit_job_sched, just set the time to Uinx timestamp get_status get the status information of a work task execution
Option_req
To set options for client and job server connections
Response messages obtained by the client:
job_created response packet type is submit_job* request packet, data part is JOB handle
Work_data, Work_warning, Work_status, Work_complete,work_fail, work_exception
For work tasks that run in the background, task execution information can be viewed by the package type as the above value.
Status_res
The response packet type is get_status, which is typically used to see if a background work task has been completed and the percentage completed.
Option_res
Request message with response packet type Option_req
Request messages sent by worker:
Can_do
Notifies the job server that a task of the given function name can be performed, and this worker will be placed into a linked list when the worker is awakened when the job server receives a function name work task.
Can_do_timeout
Similar to CAN_DO, only sets a time-out for a given function_name task.
Cant_do
Worker notifies the job server that a task with a given function name cannot be performed
Reset_abilities
Worker notifies the job server that it cannot perform any task with function name
Pre_sleep
The worker notifies the job server that it will enter the sleep phase, and then the worker will wake up with a response packet of type NoOp.
Grab_job
Worker fetches work tasks to the job server and the job server responds to No_job or Job_assig
Ngrab_job_uniq
Similar to Grab_job, but the job server responds with a work task Job_assign_uniq
Work_data
The data section of the worker request message updates the client
Work_warning
The worker request message represents a warning and it should be treated as a warning
Work_statu
Sworker Update the working status of a job handle, the job server should store this information in order to respond to client Get_status requests after
Work_complete
Notifies the job server and all connected clients that the data is part of the data returned to the client
Work_fail
Notifies the job server and all connected clients that the work task execution failed
Work_exception
Notifies the job server and all connected clients that the work task fails to execute and gives the appropriate exception
set_client_id
Set the worker ID so that the job server's console and report commands can identify the individual worker, and the data part is the identity of the worker instance
All_yours
Temporarily not implemented
Response messages obtained by the worker:
NOOP
The job server wakes the worker from sleep so that you can start crawling work tasks
No_job
The job server responds to a GRAB_JOB request, notifying the worker that there are no work tasks waiting to be performed
Job_assign
The job server responds to the Grab_job request, notifying the worker that there are work tasks to be performed
Job_assign_uniq
The job server responds to Grab_job_uniq's request, just as job_assign, simply passing a unique identity to the client
A complete example based on the above protocol description
Worker registration work tasks that can be performed
Worker---Job Server
\0req (Magic)
1 (Packet Type:can_do)
XX 7 (Packet length)
Reverse (Function)
Worker detects or fetches work tasks
Worker---Job Server
\0req (Magic)
XX 9 (Packet type:grab_job)
XX 0 (Packet length)
Job server responds to worker fetching (no work task)
\0res (Magic)
XX 0a (Packet type:no_job)
XX 0 (Packet length)
Worker notifies job server to start sleep
\0req (Magic)
XX 4 (Packet type:pre_sleep)
XX 0 (Packet length)
Client submits work tasks
Client-to-Job Server
\0req (Magic)
XX 7 (Packet type:submit_job)
XX 0d (Packet length)
The Reverse\0 (Function)
XX (Unique ID)
The Workload test (a)
The job server responds to the client's Submit_job request and returns the job handle
\0res (Magic)
XX 8 (Packet type:job_created)
XX 7 (Packet length)
3a 6c H:lap:1 3a (Job handle)
Job Server Wakeup Worker
Worker, Job Server
\0res (Magic)
XX 6 (Packet type:noop)
XX 0 (Packet length)
Working tasks for worker fetching
Worker---Job Server
\0req (Magic)
XX 9 (Packet type:grab_job)
XX 0 (Packet length)
Job server assigns a work task to a worker
Worker, Job Server
\0res (Magic)
XX 0b (Packet type:job_assign)
XX (Packet length)
3a 6c H:lap:1\0 3a to XX (Job handle)
The Reverse\0 (Function)
The Workload test (a)
Worker completes work task notification to job server
\0req (Magic)
XX 0d (Packet type:work_complete)
XX 0c (Packet length)
3a 6c H:lap:1\0 3a to XX (Job handle)
Tset (Response)
Job server notifies the client that a task has been completed
Client, Job Server
\0res (Magic)
XX 0d (Packet type:work_complete)
XX 0c (Packet length)
3a 6c H:lap:1\0 3a to XX (Job handle)
Tset (Response)
Each CLient with the job server is full-duplex communication, where a socket can complete the delivery of multiple work tasks, but the order in which the tasks are received may not be consistent with the order in which they were posted.
Summarize the worker workflow:
1. The worker is registered to the job server via the CAN_DO message.
2. The grab_job was subsequently initiated and the assignment was requested.
3. Job server returns No_job if there is no job to allocate.
4. When the worker receives the no_job, it enters the idle state and returns the Pre_sleep message to the job server, telling the job server: "If there is a job, ask me first with NoOp." ”
5. When the JOB server receives the worker's Pre_sleep message, it understands that the worker who sent the message has entered the idle state.
6. If a job is submitted, the job server sends a NOOP message to the worker first.
7. When the worker receives the NOOP message, it sends Grab_job to the job server to request the task.
8. Job server sends the work to the worker.
9. The worker works and returns Work_complete to the job server when finished.
Transferred from: http://www.phpboy.net/other/907.html
Gearman Knowledge Articles