Home Backend Development PHP Tutorial Share examples of correctly publishing PHP code

Share examples of correctly publishing PHP code

Mar 12, 2018 pm 02:44 PM
php share Example


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
Copy after login

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
    Copy after login

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 = &#39;php.pid_&#39; . getmypid();    if (($rev = apc_fetch($key)) != DEPLOY_VERSION) {        if($rev < DEPLOY_VERSION) {
            apc_store($key, DEPLOY_VERSION);
        }

        clearstatcache(true);
    }
Copy after login

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;
Copy after login

有了 $Share examples of correctly publishing PHP code_root,即便 DOCUMENT_ROOT 目录中含有软链接,NGINX 也会把软链接指向的真正的路径发给 PHP,也就是说,对 PHP 而言,软链接已经不存在了!不过作为代价,每一次请求,NGINX 都要通过相对昂贵的 IO 操作获取 $Share examples of correctly publishing PHP code_root 的值,通过 strace 命令我们能监控这一过程,下图从 currentfoo 的过程:

Share examples of correctly publishing PHP code

在本例中,压测发现使用 $Share examples of correctly publishing PHP code_root 后,性能下降了大约 5% 左右,不过明眼人一下就能发现,虽然 $Share examples of correctly publishing PHP code_root 导致了 lstatreadlink 操作,但是 lstat 操作的次数是和目录深度成正比的,也就是说目录越深,执行的 lstat 次数越多,性能下降也就越大。如果能够降低发布目录的深度,那么可以预计还能降低一些性能损耗。

结尾介绍一下 Deployer,它是 PHP 中做得比较好的工具,有很多特色,比如支持并行发布,具体演示如下图,左边是串行,右边是并行,使用「vvv」能得到更详细信息:

Share examples of correctly publishing PHP code

不过 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");?>
Copy after login

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
Copy after login

通过 strace 我们能清晰的看到,虽然表面上使用「ln -sfn」是一步操作,但是内部依然是按照先删除再创建的逻辑执行的,实际上这里应该搭配使用「ln & mv」

shell> ln -sfn releases/foo current.tmpshell> mv -fT current.tmp current
Copy after login

先通过 ln 创建一个临时的软链接,再通过 mv 实现原子操作,此时如果使用 strace 监控,会发现 mv「T」 选项实际上仅仅执行了一个 rename 操作,所以是原子的。

BTW:在使用「ln -sfn」前后,如果使用 stat 查看新旧文件的 inode 的话,可能会发现它们拥有一样的 inode 值,看上去和我们的结论相悖,其实不然,实际上只是复用删除值而已(如果想验证,注意 Linux 会复用,Mac 不会复用)。

据说一千个人的心中就有一千个哈姆雷特,不过我希望所有的 PHP 程序员在发布 PHP 代码的时候都能采用一种方法,那就是本文介绍的方法,正确的方法。

相关推荐:

php代码标志基础讲解

提高PHP代码质量的方法

JS和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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles