Almost every PHP programmer has published code, which may be synchronized through FTP or rsync , It may also be updated through svn or git. An active project may release code several times a day, but the reality is that few people pay attention to the details. In fact, there are many pitfalls, and it is possible that you are in the pit without knowing it.
A properly implemented publishing system should at least support atomic publishing. If each version represents an independent state, then during the release period, any request can only be executed in a single state. This is called supporting atomic release; on the contrary, if a request spans different states during the release, it cannot be called atomic release. Let us give an example to illustrate: Suppose a request requires include
two PHP files, namely a.php
and b.php
, when include a.php
is completed, release the code, and then include b.php
, if not handled properly, it may result in an old version of a. php
and the new version of b.php
exist in the same request at the same time. In other words, atomic publishing is not implemented.
There are many good tools for publishing code in the open source world, such as capistrano in the ruby community. The process is roughly to publish the code to a brand new directory, and then soft link to the real release directory. .
├── current -> releases/v1 └── releases ├── v1 │ ├── foo.php │ └── bar.php └── v2 ├── foo.php └── bar.php
However, in view of the particularity of PHP, if you simply apply the above process, it will be difficult to achieve true atomic release. To clarify the reason, you also need to understand the two concepts of Cache in PHP
:
opcode cache
Share examples of correctly publishing PHP code cache
Let’s talk about opcode cache
, basically apc
or zend opcode
, everyone is already familiar with its function. Needless to say, it needs to be noted that apc
has many bugs, such as turning on apc. There will be many strange problems after enable_cli is configured, so opcode cache
is better to use zend opcache
as much as possible. If you need to cache data, you can use apcu. In addition, apc
and zend opcode
have different selections of cache keys: apc
chooses the inode
of the file, zend opcode
selects the path
of the file.
Let’s talk againShare examples of correctly publishing PHP code cache
, its role is to buffer the IO operation to obtain file information. Most of the time it is transparent to us, so that Many people don't know its existence. It should be noted that Share examples of correctly publishing PHP code cache
is at the process level, that is to say, each php-fpm
process has its own independent Share examples of correctly publishing PHP code cache
.
Suppose that during the release of the code, the data in opcode cache
or Share examples of correctly publishing PHP code cache
expires, then part of the cache will be old files and part of the cache will be new files. In the case of non-atomic publishing, in order to avoid this situation, we should ensure that the cache expiration time is long enough. It is best that it will never expire unless we refresh it manually. The corresponding configuration is: turn off apc.stat, opcache.validate_timestamps Configuration, setting a sufficiently large Share examples of correctly publishing PHP code_cache_size, Share examples of correctly publishing PHP code_cache_ttl configuration, and necessary monitoring is always beneficial.
The relevant technical details are very trivial. It is recommended that you read the following information carefully:
Share examples of correctly publishing PHP code_cache PHP’s OPCache extension review Atomic Share examples of correctly publishing PHP codes at Etsy Cache invalidation for scripts in symlinked folders
When using soft links to publish code, you usually encounter The first problem that comes up is probably that the new code does not take effect! Even if the apc_clear_cache or opcache_reset method is called, it will not work. Restarting php-fpm
can naturally solve the problem, but restarting is too heavy for scripting languages! Is there no other way besides restarting?
In fact, the reason why such a problem occurs is mainly because opcode cache
obtains file information through Share examples of correctly publishing PHP code cache
, even if the soft link has pointed to the new location. But if old data is still stored in Share examples of correctly publishing PHP code cache
, opcode cache
still cannot know the existence of new code. By default, the Share examples of correctly publishing PHP code_cache_ttl cache validity period is two minutes, which means that the release After the code is issued, it may take up to two minutes to take effect. In order for the release to take effect as soon as possible, it is necessary to clear the Share examples of correctly publishing PHP code cache
on a process basis:
<?php $key = 'php.pid_' . getmypid(); if (($rev = apc_fetch($key)) != DEPLOY_VERSION) { if($rev < DEPLOY_VERSION) { apc_store($key, DEPLOY_VERSION); } clearstatcache(true); }
This will basically work in the apc
environment, but in the There may also be problems in the zend opcode
environment. Because opcache.revalidate_path is turned off by default, the value of unresolved symbolic links will be cached at this time. This will cause the soft link to fail to take effect even if the pointer is modified, so when using zend opcode
When using soft links, you may need to activate opcache.revalidate_path
depending on the situation.
详细介绍参考:PHP’s OPCache extension review。
BTW:如果需要手动重置 opcode cache
,需要注意的是因为它是基于 SAPI 的概念,所以不能直接在命令行下调用 apc_clear_cache 或者 opcache_reset 方法来重置缓存,当然办法总是有的,那就是使用 CacheTool 在命令行下模拟 fastcgi
请求。
分析到这里,我们不妨反思一下:在 PHP 中原子发布之所以是一个棘手的问题,归根结底是因为软链接和缓存之间的的矛盾。不管是 opcode cache
还是 Share examples of correctly publishing PHP code cache
,都是 PHP 固有的缓存特性,基于客观需要无法绕开,如此说来是否有办法绕开软链接,使其成为马奇诺防线呢?答案是 NGINX 的 $Share examples of correctly publishing PHP code_root:
fastcgi_param SCRIPT_FILENAME $Share examples of correctly publishing PHP code_root$fastcgi_script_name; fastcgi_param DOCUMENT_ROOT $Share examples of correctly publishing PHP code_root;
有了 $Share examples of correctly publishing PHP code_root
,即便 DOCUMENT_ROOT
目录中含有软链接,NGINX 也会把软链接指向的真正的路径发给 PHP,也就是说,对 PHP 而言,软链接已经不存在了!不过作为代价,每一次请求,NGINX 都要通过相对昂贵的 IO 操作获取 $Share examples of correctly publishing PHP code_root
的值,通过 strace
命令我们能监控这一过程,下图从 current
到 foo
的过程:
在本例中,压测发现使用 $Share examples of correctly publishing PHP code_root
后,性能下降了大约 5% 左右,不过明眼人一下就能发现,虽然 $Share examples of correctly publishing PHP code_root
导致了 lstat
和 readlink
操作,但是 lstat
操作的次数是和目录深度成正比的,也就是说目录越深,执行的 lstat
次数越多,性能下降也就越大。如果能够降低发布目录的深度,那么可以预计还能降低一些性能损耗。
结尾介绍一下 Deployer,它是 PHP 中做得比较好的工具,有很多特色,比如支持并行发布,具体演示如下图,左边是串行,右边是并行,使用「vvv」能得到更详细信息:
不过 Deployer 在原子发布上有一点瑕疵,具体见 release/symlink
代码:
<?php// Share examples of correctly publishing PHP code:releaserun("cd {{Share examples of correctly publishing PHP code_path}} && if [ -h release ]; then rm release; fi"); run("ln -s $releasePath {{Share examples of correctly publishing PHP code_path}}/release");// Share examples of correctly publishing PHP code:symlinkrun("cd {{Share examples of correctly publishing PHP code_path}} && ln -sfn {{release_path}} current"); run("cd {{Share examples of correctly publishing PHP code_path}} && rm release");?>
在 release
的时候,它是先删除再创建,是一个两步的非原子操作,在 symlink
的时候,看上去「ln -sfn」
是单步原子操作,实际上也是错误的:
shell> strace ln -sfn releases/foo currentsymlink("releases/foo", "current") = -1 EEXIST (File exists)unlink("current") = 0symlink("releases/foo", "current") = 0
通过 strace
我们能清晰的看到,虽然表面上使用「ln -sfn」
是一步操作,但是内部依然是按照先删除再创建的逻辑执行的,实际上这里应该搭配使用「ln & mv」
:
shell> ln -sfn releases/foo current.tmpshell> mv -fT current.tmp current
先通过 ln
创建一个临时的软链接,再通过 mv
实现原子操作,此时如果使用 strace
监控,会发现 mv
的 「T」
选项实际上仅仅执行了一个 rename
操作,所以是原子的。
BTW:在使用「ln -sfn」
前后,如果使用 stat
查看新旧文件的 inode
的话,可能会发现它们拥有一样的 inode
值,看上去和我们的结论相悖,其实不然,实际上只是复用删除值而已(如果想验证,注意 Linux 会复用,Mac 不会复用)。
据说一千个人的心中就有一千个哈姆雷特,不过我希望所有的 PHP 程序员在发布 PHP 代码的时候都能采用一种方法,那就是本文介绍的方法,正确的方法。
相关推荐:
The above is the detailed content of Share examples of correctly publishing PHP code. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.