SlideShare uma empresa Scribd logo
1 de 17
A FRAMEWORKLESS
APPLICATION AND WHY
WE DID IT
HOW WE BUILT
BONUS: SHORT GUIDE TO PROCESS FORKING,
SIGNALS HANDLING AND MORE
Maksym Bodnar
maksym.bodnar@gmail.com
DEFINITION FROM WIKI
WHAT IS A FRAMEWORK
A software framework is an abstraction in which software providing
generic functionality can be selectively changed by additional user-
written code, thus providing application-specific software.
Key features:
• Inversion of control - overall program flow is controlled by a framework, not by
a developer.
• Extensibility - developer can add or override some parts of the framework to
customize it.
• Non-modifiable part - developer usually is not supposed to modify the code of
the framework
WHY WE NEED THEM
WHAT IS A FRAMEWORK
Main purpose of any software framework is to facilitate development
by allowing programmers to devote their time to meeting software
requirements rather than dealing with low level standard operations
and focus on writing application specific code [wiki].
To achieve those goals frameworks provide:
• Pre-built components and libraries;
• Autoloading mechanism;
• CLI Tools (zf, artisan etc).
PHP + COMPOSER
FRAMEWORKLESS OPTION
• Autoloading mechanism (PSR-4, Composer);
• Components and libraries (Composer);
• CLI tools (partially covered by previous item).
SUMMARY
FRAMEWORK VS FRAMEWORK LESS
Framework pros:
• Execution flow, app “skeleton”;
• Bootstrapping, configuration
loading;
• Tools (classes templates, DB
migrations etc) and fancy helper
functions;
Framework cons:
• Execution flow is enforced;
• Unnecessary overhead/complexity;
• Dependency on framework
maintainers.
Frameworkless pros:
• No enforced execution flow;
• No overhead;
• Way greater flexibility.
Frameworkless cons:
• More typing needed (but it is not
that difficult);
• No tools and no fancy helper
functions;
BUILDING CLI APP: WHERE TO BEGIN
FRAMEWORKLESS
Key word: composer.
Libraries/components we are going to use:
• Container component (for dependencies injection): pimple/pimple;
• Simple lib for loading variables from a config file into $_ENV structure:
vlucas/phpdotenv;
• A library needed to talk to MongoDB (ughhhh): mongodb/mongodb;
• Decrypting cron expressions (needed for scheduler): mtdowling/cron-
expression;
• Nice dates/time handling: nesbot/carbon;
• Working with RabbitMQ: php-amqplib/php-amqplib;
• Sending emails: swiftmailer/swiftmailer;
• Testing: phpunit/phpunit.
BUILDING CLI APP: WHAT IS IN THE CORE
App.php
Application core
• Init container;
• Fill it with different useful
things;
FRAMEWORKLESS
BUILDING CLI APP: INITIALIZE EVERYTHING
FRAMEWORKLESS
Bootstrapping the app:
• Create container;
• Load configs;
• Init DB handlers and logger
bootstrap.php
It is not that difficult, really…
FRAMEWORKLESS
BUILDING CLI APP: INITIALIZE EVERYTHING
Mock some useful
Laravel functions:
• app();
• config();
• env();
STARTING A NEW PROCESS
LET’S FORK
PROCESS PID#111
$pid = pcntl_fork();
PROCESS PID#111
Parent
PROCESS PID#112
Child
$pid ==112 $pid == 0
WHAT’S GOING ON HERE
LET’S FORK
• New completely independent process is forked from the existing
one;
• New process is exact copy of the existing one: all variables,
references, handlers are copied
(parentChildShutdownDemo.php);
• Possible problems:
• Operating system level: zombies/orphans;
• Application level: resources handling;
• In case of demonizing - explicit exit in a child process.
OPERATING SYSTEM: ZOMBIES VS ORPHANS
LET’S FORK
OS keeps track of all processes.
• If a child process exists and this event is not handled by parent,
we get a zombie (defunct) (zombieDemo.php);
• If a parent process exits and child is still alive, it becomes an
orphan (parent PID = 1) (orphanDemo.php).
Not a real problem for a short living processes - important condition:
there should be time when both a parent and a child processes exit. If
parent process continues to run for a long time (daemon scenario),
than extra measures should be taken to prevent zombies duplication.
APPLICATION: RESOURCES HANDLING
LET’S FORK
File descriptors/handlers:
• Both processes use copies of the same descriptor, therefore
exists a risk of concurrent writes/reads to/from the descriptor.
• When process exits all descriptors are destructed by PHP,
therefore the process that is still alive will not be able to use it*.
* If you used to put code that closes descriptors correctly into shutdown
function be aware that in case of forked process if the process is
terminated because of the signal, shutdown function will not be called
unless you register also signal handler for corresponding signal.
SIGNALS
LET’S FORK
• Signals are software interrupts that deliver very short messages
(actually, an int) to process/processes.
• Some signals are catchable, some are not (SIGKILL).
• Install signal handlers for each signal: pcntl_signal(SIGTERM,
“handler”);
PARENT/CHILD COMMUNICATION
ADVANCED FORKING
• Explicit wait: pcntl_waitpid($pid, $status, $options);
• Catch SIGCHLD signal, then do pcntl_waitpid($pid, $status, $options);
• Use pcntl_wifexited()/pcntl_wifsignaled()/pcntl_wifstopped() to figure out how
(why) the child exited, then use:
• pcntl_wexitstatus() in case of normal exit to check the status OR
• pcntl_wtermsig()/pcntl_wstopsig() to check what actual signal the child has
received in case of exit because of signal;
Part of SIGCHLD handler that detects all the circumstances of the child process exit
DEALING WITH DAEMONS
ADVANCED FORKING
• Parent process should be responsible only for spawning children,
all tasks should be done by children;
• Parent process should keep tracking of children PIDs and should
be able to send at least two types of signals:
• Terminate gracefully;
• terminate immediately.
• Parent process should check total memory consumption (free
memory) and load average to decide if it is safe to fork;
• Children should rotate (exit) often to avoid memory leaks.
USEFUL RESOURCES
• http://www.hackingwithphp.com/16/1/0/process-control
• https://secure.php.net/manual/en/book.pcntl.php
• https://secure.php.net/manual/en/book.posix.php
• https://secure.php.net/manual/en/function.memory-get-
usage.php#120665
Magic formula to get total server memory in use:
$percentUsed = ($memory['used'] - $memory['kern']) * 100 / ($memory['used'] + $memory[‘free']);

Mais conteúdo relacionado

Mais procurados

The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012
Jan Jongboom
 

Mais procurados (19)

The Beam Vision for Portability: "Write once run anywhere"
The Beam Vision for Portability: "Write once run anywhere"The Beam Vision for Portability: "Write once run anywhere"
The Beam Vision for Portability: "Write once run anywhere"
 
Trunk based development for Beginners
Trunk based development for BeginnersTrunk based development for Beginners
Trunk based development for Beginners
 
Simplified CI/CD Flows for Salesforce via SFDX - Downunder Dreamin - Sydney
Simplified CI/CD Flows for Salesforce via SFDX - Downunder Dreamin - SydneySimplified CI/CD Flows for Salesforce via SFDX - Downunder Dreamin - Sydney
Simplified CI/CD Flows for Salesforce via SFDX - Downunder Dreamin - Sydney
 
Trunk based development
Trunk based developmentTrunk based development
Trunk based development
 
Node & Express as Workflow Tools
Node & Express as Workflow ToolsNode & Express as Workflow Tools
Node & Express as Workflow Tools
 
Developers' mDay 2017. - Ilija Studen ActiveCollab
Developers' mDay 2017. - Ilija Studen ActiveCollabDevelopers' mDay 2017. - Ilija Studen ActiveCollab
Developers' mDay 2017. - Ilija Studen ActiveCollab
 
Highly Surmountable Challenges in Ruby+OMR JIT Compilation
Highly Surmountable Challenges in Ruby+OMR JIT CompilationHighly Surmountable Challenges in Ruby+OMR JIT Compilation
Highly Surmountable Challenges in Ruby+OMR JIT Compilation
 
Production Ready WordPress - WC Utrecht 2017
Production Ready WordPress  - WC Utrecht 2017Production Ready WordPress  - WC Utrecht 2017
Production Ready WordPress - WC Utrecht 2017
 
GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22GraalVM - MadridJUG 2019-10-22
GraalVM - MadridJUG 2019-10-22
 
How to Upgrade to the Newest Shiniest Django Version
How to Upgrade to the Newest Shiniest Django VersionHow to Upgrade to the Newest Shiniest Django Version
How to Upgrade to the Newest Shiniest Django Version
 
CI
CICI
CI
 
Salesforce CI (Continuous Integration) - SFDX + Bitbucket Pipelines
Salesforce CI (Continuous Integration) - SFDX + Bitbucket PipelinesSalesforce CI (Continuous Integration) - SFDX + Bitbucket Pipelines
Salesforce CI (Continuous Integration) - SFDX + Bitbucket Pipelines
 
Capistrano @ VilniusPHP
Capistrano @ VilniusPHPCapistrano @ VilniusPHP
Capistrano @ VilniusPHP
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
100 tests per second - 40 releases per week
100 tests per second - 40 releases per week100 tests per second - 40 releases per week
100 tests per second - 40 releases per week
 
The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012The Architect Way - JSCamp.asia 2012
The Architect Way - JSCamp.asia 2012
 
Take your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to ModernizationTake your CFML Legacy Apps to Modernization
Take your CFML Legacy Apps to Modernization
 
Calabash Mobile Application Testing Overview
Calabash Mobile Application Testing OverviewCalabash Mobile Application Testing Overview
Calabash Mobile Application Testing Overview
 
Angular Libraries & NPM
 Angular Libraries & NPM Angular Libraries & NPM
Angular Libraries & NPM
 

Semelhante a Frameworkless CLI app in PHP

Lighning Talk: PHP build process
Lighning Talk: PHP build processLighning Talk: PHP build process
Lighning Talk: PHP build process
Bryan Agee
 

Semelhante a Frameworkless CLI app in PHP (20)

Joomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation TestingJoomla Code Quality Control and Automation Testing
Joomla Code Quality Control and Automation Testing
 
python_development.pptx
python_development.pptxpython_development.pptx
python_development.pptx
 
Hyperion EPM APIs - Added value from HFM, Workspace, FDM, Smartview, and Shar...
Hyperion EPM APIs - Added value from HFM, Workspace, FDM, Smartview, and Shar...Hyperion EPM APIs - Added value from HFM, Workspace, FDM, Smartview, and Shar...
Hyperion EPM APIs - Added value from HFM, Workspace, FDM, Smartview, and Shar...
 
Profiling and Tuning a Web Application - The Dirty Details
Profiling and Tuning a Web Application - The Dirty DetailsProfiling and Tuning a Web Application - The Dirty Details
Profiling and Tuning a Web Application - The Dirty Details
 
JIT Compiler
JIT CompilerJIT Compiler
JIT Compiler
 
Lighning Talk: PHP build process
Lighning Talk: PHP build processLighning Talk: PHP build process
Lighning Talk: PHP build process
 
Odo improving the developer experience on OpenShift - hack & sangria
Odo   improving the developer experience on OpenShift - hack & sangriaOdo   improving the developer experience on OpenShift - hack & sangria
Odo improving the developer experience on OpenShift - hack & sangria
 
SpringOne 2016 in a nutshell
SpringOne 2016 in a nutshellSpringOne 2016 in a nutshell
SpringOne 2016 in a nutshell
 
Serverless Functions and Machine Learning: Putting the AI in APIs
Serverless Functions and Machine Learning: Putting the AI in APIsServerless Functions and Machine Learning: Putting the AI in APIs
Serverless Functions and Machine Learning: Putting the AI in APIs
 
Devops with Python by Yaniv Cohen DevopShift
Devops with Python by Yaniv Cohen DevopShiftDevops with Python by Yaniv Cohen DevopShift
Devops with Python by Yaniv Cohen DevopShift
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
An intuitive guide to combining free monad and free applicative
An intuitive guide to combining free monad and free applicativeAn intuitive guide to combining free monad and free applicative
An intuitive guide to combining free monad and free applicative
 
Splunk: Forward me the REST of those shells
Splunk: Forward me the REST of those shellsSplunk: Forward me the REST of those shells
Splunk: Forward me the REST of those shells
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento Development
 
Codecoon - A technical Case Study
Codecoon - A technical Case StudyCodecoon - A technical Case Study
Codecoon - A technical Case Study
 
Redundant devops
Redundant devopsRedundant devops
Redundant devops
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to Work
 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
 
Code quality par Simone Civetta
Code quality par Simone CivettaCode quality par Simone Civetta
Code quality par Simone Civetta
 
Gitlab ci-cd
Gitlab ci-cdGitlab ci-cd
Gitlab ci-cd
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Último (20)

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

Frameworkless CLI app in PHP

  • 1. A FRAMEWORKLESS APPLICATION AND WHY WE DID IT HOW WE BUILT BONUS: SHORT GUIDE TO PROCESS FORKING, SIGNALS HANDLING AND MORE Maksym Bodnar maksym.bodnar@gmail.com
  • 2. DEFINITION FROM WIKI WHAT IS A FRAMEWORK A software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user- written code, thus providing application-specific software. Key features: • Inversion of control - overall program flow is controlled by a framework, not by a developer. • Extensibility - developer can add or override some parts of the framework to customize it. • Non-modifiable part - developer usually is not supposed to modify the code of the framework
  • 3. WHY WE NEED THEM WHAT IS A FRAMEWORK Main purpose of any software framework is to facilitate development by allowing programmers to devote their time to meeting software requirements rather than dealing with low level standard operations and focus on writing application specific code [wiki]. To achieve those goals frameworks provide: • Pre-built components and libraries; • Autoloading mechanism; • CLI Tools (zf, artisan etc).
  • 4. PHP + COMPOSER FRAMEWORKLESS OPTION • Autoloading mechanism (PSR-4, Composer); • Components and libraries (Composer); • CLI tools (partially covered by previous item).
  • 5. SUMMARY FRAMEWORK VS FRAMEWORK LESS Framework pros: • Execution flow, app “skeleton”; • Bootstrapping, configuration loading; • Tools (classes templates, DB migrations etc) and fancy helper functions; Framework cons: • Execution flow is enforced; • Unnecessary overhead/complexity; • Dependency on framework maintainers. Frameworkless pros: • No enforced execution flow; • No overhead; • Way greater flexibility. Frameworkless cons: • More typing needed (but it is not that difficult); • No tools and no fancy helper functions;
  • 6. BUILDING CLI APP: WHERE TO BEGIN FRAMEWORKLESS Key word: composer. Libraries/components we are going to use: • Container component (for dependencies injection): pimple/pimple; • Simple lib for loading variables from a config file into $_ENV structure: vlucas/phpdotenv; • A library needed to talk to MongoDB (ughhhh): mongodb/mongodb; • Decrypting cron expressions (needed for scheduler): mtdowling/cron- expression; • Nice dates/time handling: nesbot/carbon; • Working with RabbitMQ: php-amqplib/php-amqplib; • Sending emails: swiftmailer/swiftmailer; • Testing: phpunit/phpunit.
  • 7. BUILDING CLI APP: WHAT IS IN THE CORE App.php Application core • Init container; • Fill it with different useful things; FRAMEWORKLESS
  • 8. BUILDING CLI APP: INITIALIZE EVERYTHING FRAMEWORKLESS Bootstrapping the app: • Create container; • Load configs; • Init DB handlers and logger bootstrap.php
  • 9. It is not that difficult, really… FRAMEWORKLESS BUILDING CLI APP: INITIALIZE EVERYTHING Mock some useful Laravel functions: • app(); • config(); • env();
  • 10. STARTING A NEW PROCESS LET’S FORK PROCESS PID#111 $pid = pcntl_fork(); PROCESS PID#111 Parent PROCESS PID#112 Child $pid ==112 $pid == 0
  • 11. WHAT’S GOING ON HERE LET’S FORK • New completely independent process is forked from the existing one; • New process is exact copy of the existing one: all variables, references, handlers are copied (parentChildShutdownDemo.php); • Possible problems: • Operating system level: zombies/orphans; • Application level: resources handling; • In case of demonizing - explicit exit in a child process.
  • 12. OPERATING SYSTEM: ZOMBIES VS ORPHANS LET’S FORK OS keeps track of all processes. • If a child process exists and this event is not handled by parent, we get a zombie (defunct) (zombieDemo.php); • If a parent process exits and child is still alive, it becomes an orphan (parent PID = 1) (orphanDemo.php). Not a real problem for a short living processes - important condition: there should be time when both a parent and a child processes exit. If parent process continues to run for a long time (daemon scenario), than extra measures should be taken to prevent zombies duplication.
  • 13. APPLICATION: RESOURCES HANDLING LET’S FORK File descriptors/handlers: • Both processes use copies of the same descriptor, therefore exists a risk of concurrent writes/reads to/from the descriptor. • When process exits all descriptors are destructed by PHP, therefore the process that is still alive will not be able to use it*. * If you used to put code that closes descriptors correctly into shutdown function be aware that in case of forked process if the process is terminated because of the signal, shutdown function will not be called unless you register also signal handler for corresponding signal.
  • 14. SIGNALS LET’S FORK • Signals are software interrupts that deliver very short messages (actually, an int) to process/processes. • Some signals are catchable, some are not (SIGKILL). • Install signal handlers for each signal: pcntl_signal(SIGTERM, “handler”);
  • 15. PARENT/CHILD COMMUNICATION ADVANCED FORKING • Explicit wait: pcntl_waitpid($pid, $status, $options); • Catch SIGCHLD signal, then do pcntl_waitpid($pid, $status, $options); • Use pcntl_wifexited()/pcntl_wifsignaled()/pcntl_wifstopped() to figure out how (why) the child exited, then use: • pcntl_wexitstatus() in case of normal exit to check the status OR • pcntl_wtermsig()/pcntl_wstopsig() to check what actual signal the child has received in case of exit because of signal; Part of SIGCHLD handler that detects all the circumstances of the child process exit
  • 16. DEALING WITH DAEMONS ADVANCED FORKING • Parent process should be responsible only for spawning children, all tasks should be done by children; • Parent process should keep tracking of children PIDs and should be able to send at least two types of signals: • Terminate gracefully; • terminate immediately. • Parent process should check total memory consumption (free memory) and load average to decide if it is safe to fork; • Children should rotate (exit) often to avoid memory leaks.
  • 17. USEFUL RESOURCES • http://www.hackingwithphp.com/16/1/0/process-control • https://secure.php.net/manual/en/book.pcntl.php • https://secure.php.net/manual/en/book.posix.php • https://secure.php.net/manual/en/function.memory-get- usage.php#120665 Magic formula to get total server memory in use: $percentUsed = ($memory['used'] - $memory['kern']) * 100 / ($memory['used'] + $memory[‘free']);