<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Amyangfei&#39;s Blog</title>
  
  <subtitle>Enjoy Programming</subtitle>
  <link href="http://amyangfei.me/atom.xml" rel="self"/>
  
  <link href="http://amyangfei.me/"/>
  <updated>2023-05-18T04:24:29.678Z</updated>
  <id>http://amyangfei.me/</id>
  
  <author>
    <name>amyangfei</name>
    
  </author>
  
  <generator uri="https://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Lessons learned from TiCDC</title>
    <link href="http://amyangfei.me/2023/05/04/lessons-learned-from-ticdc/"/>
    <id>http://amyangfei.me/2023/05/04/lessons-learned-from-ticdc/</id>
    <published>2023-05-03T16:00:00.000Z</published>
    <updated>2023-05-18T04:24:29.678Z</updated>
    
    <content type="html"><![CDATA[<p><a href="https://github.com/pingcap/tiflow">TiCDC</a> is a change data capture framework developed for <a href="https://github.com/pingcap/tidb">TiDB</a> ecosystem. It allows for the replication of change data to various downstream systems, including MySQL protocol-compatible databases, messaging queue systems like Kafka, and Object Storage Service like S3. As the top one code contributor and the former tech leader of this project, I witnessed the project from a concept to a mature system running in many product environments, and also led several important architecture evolutions of this project. At this moment, I’m going to leave this project and explore new opportunities, I’d like to retrospect and summarize the lessons I have learned from this project.</p><h2 id="Highlights-of-this-system"><a href="#Highlights-of-this-system" class="headerlink" title="Highlights of this system"></a>Highlights of this system</h2><p>In this part I will talk about the highlights of TiCDC, from the perspectives of system architecture, core features, smart design or some engineering implementations.</p><h3 id="A-well-designed-plug-and-play-monolithic-architecture"><a href="#A-well-designed-plug-and-play-monolithic-architecture" class="headerlink" title="A well designed plug-and-play, monolithic architecture"></a>A well designed plug-and-play, monolithic architecture</h3><p>TiCDC stands out due to its well-designed plug-and-play monolithic architecture. Setting up a synchronization path for replicating row-based change data from an existing TiDB cluster is a breeze. Users only need to deploy one or more TiCDC processes connected to the same TiDB cluster to form a unified cluster automatically, without any topology configuration, meta-system deployment, or separated components. Different compute components, including the data source part(puller), data sort part(sorter), data encapsulation part(mounter) and data sink part(sink) are running in the same process. That is what I mean it is a plug-and-play system, and it is a classic monolithic architecture. In addition to its straightforward deployment, TiCDC is designed to handle system maintenance effectively, especially for managing many high-availability scenarios automatically, including node crasing, upstream failure, network partition and so on. TiCDC provides high availability at both the process and data levels.</p><span id="more"></span><ul><li>Process level: the availability of process level means there is always a running entity that is replicating data from upstream to downstream. As for downtime it refers to the RTO(Recovery Time Objective).</li><li>Data level: the availability of data level means TiCDC can always ensure no data loss when system meets disaster and the system guarantees zero RPO in most scenarios(the most here means it still has some corner cases that zero RPO can’t meet).</li></ul><p>To ensure process-level availability, TiCDC ships a leader-follower role model in cluster and relies heavily on the <a href="https://github.com/etcd-io/etcd/blob/0deaec0e4f54beef1cc500ea214694e5326b88c0/client/v3/concurrency/election.go">etcd election feature</a> for leader election. A nearly always online leader manages the synchronization tasks of the entire cluster, including task rescheduling when some node crashes or experiences network partition. In addition a builtin <a href="https://cn.pingcap.com/blog/ticdc-source-code-reading-4">two-phase scheduling</a> can reduce latency in many scenarios including graceful restart, table re-scheduling and more.</p><p>To achieve data-level availability, TiCDC doesn’t persist any data, it reuses the MVCC data in upstream TiKV to avoid data loss during a disaster. The basic idea is to delay upstream GC of MVCC data when the synchronization progress has fallen behind in TiCDC, and TiCDC can scan the historical data from TiKV if it is not GCed. This explains why TiCDC guarantees zero RPO in <strong>most scenarios</strong>, except for the scenario that upstream TiKV GC happens without respecting TiCDC synchronization progress.</p><h3 id="Well-tuned-components"><a href="#Well-tuned-components" class="headerlink" title="Well tuned components"></a>Well tuned components</h3><p>As described in the previous section, there exist several core components in the data flow link of TiCDC, puller, sorter, mounter and sink respectively. Data is flowed in a pipeline mode among these components via gRPC bi-streaming or golang builtin channel, including</p><ul><li>TiKV <strong>pushes</strong> data to TiCDC puller via gRPC stream</li><li>puller <strong>pushes</strong> data to sorter via golang channel</li><li>sink <strong>pulls</strong> data from sorter via golang channel</li></ul><p>In order to guarantee second level synchronization latency, each component must keep in pace, guarantee sub-second level processing latency and low latency when sending data between components. At the same time, low latency also means high throughput since the traffic in the upstream can range a lot. To meet the latency and throughput requirement, each TiCDC component has many optimization techniques. These techniques have been fully discussed in several blogs including:</p><ul><li>The <a href="https://cn.pingcap.com/blog/ticdc-source-code-reading-6">puller implement</a></li><li><a href="https://cn.pingcap.com/blog/ticdc-source-code-reading-7">The sorter implement</a>, where a <a href="https://github.com/cockroachdb/pebble">LSM tree based kv storage pebble</a> is used for data sorting</li><li>The pull based sink, sink itself maintains a memory quota module and pulls data from sorter by actual demand. In this way if regression happens in downstream, the accumulated data in sink is limited and won’t cause OOM. At the same time more data will be continually pushed from TiKV to puller and most of the data will be accumulated in the sorter, where data is cached in disk by multiple levels of LSM tree.</li><li>As for the underlying sink, it is a simple client model, including MySQL client, Kafka client or S3 client. There are some common optimization tricks such as concurrent worker, batch mechanism, asynchronous acknowledgement in Kafka producer, <a href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-multiple-queries.html">multiple statements</a> optimization in MySQL protocol, etc.</li></ul><h2 id="Shortcomings-of-the-system"><a href="#Shortcomings-of-the-system" class="headerlink" title="Shortcomings of the system"></a>Shortcomings of the system</h2><p>There is no silver bullet in software engineering, especially when requirements and scenarios become more and more complex. there are still scenarios where the current system doesn’t behave well, including:</p><ul><li><p>The multi tenants scenario. In this scenario, a single TiCDC cluster needs to serve tens of thousands of changefeeds belonging to different tenants, requiring elastic scheduling and resource isolation. Unfortunately the current monolithic architecture doesn’t fit very well with this scenario for two reasons</p><ul><li>The leader runs a tick function periodically, in which function it iterates each changefeed one by one to maintain changefeed status, including synchronization progress, scheduling information etc.</li><li>Each compute component (puller, sorter, mounter and sink respectively) runs in background goroutines and shares the whole compute resource of the host, there is no resource isolation mechanism.</li></ul></li><li><p>The fast recovery requirement. Supposing there is some error happens in the synchronization path, such as writing to MySQL returns an error and the whole changefeed restarts. The ideal way is to reuse existing computing result and only restarts necessary computing component, in this context it is better to restart sink only, and reuse existing data including the received change logs in puller, the sorted data in sorter and the encapsulated data in mounter. However in current design, TiCDC has to ask TiKV to re-scan historical data from the existing checkpoint, given the watermark that TiCDC has processed before error happens, the data between <code>(checkpoint, processed-watermark]</code> will be processed twice, if the checkpoint is fallen behind a lot, the data size could be very large.</p></li><li><p>The requirements of flexible integration and computational decoupling. These are two different requirements, but they all require TiCDC behaves like a <strong>framework</strong> instead of an independent product. More specifically</p><ul><li>For the flexible integration, supposing users want to collect the encapsulated change logs from TiKV directly and send them to existing computing platform, it is difficult to use a simple TiKV cdc client, which collects raw change logs and encapsulate to standard format such as SQL, and writes data out via a pre-defined RPC format. Or use the code of TiCDC as a golang library, integrate into a program and implement a cdc adapter.</li><li>As for the computational decoupling, it is impossible to limit the resource usage of each compute component, scale out resource based on the workload of different computing components or implement asynchronous computing in the current architecture.</li></ul></li><li><p>Implement a decoupled testing system. Although ticdc has a mature testing system, which covers unit tests, end to end integration tests and various chaos tests scenarios, it still lacks deterministic, and components based testing. Component-based testing can be treated as module-level end-to-end (E2E) testing. For example, in the case of the sorter component, there can be predefined data flow inputs and downstream sink module retrieval, allowing for quantitative testing of the sorter module’s performance and capability. This type of testing is highly beneficial for scenarios involving data consistency and performance testing. Compared to E2E testing across the entire system, this testing approach has a finer granularity and greater test reproducibility.</p></li></ul><p>According to the above description, there are many scenarios for data replication:</p><ul><li>On premises vs. on the cloud</li><li>Building an independent data link for single TiDB cluster vs. building a data transformation platform</li><li>Using pre-defined resource vs. adaptive resource control with auto scaling</li><li>Using a plug-and-play system vs. secondary development</li></ul><p>We can’t build a single system to meet the requirements from all these scenarios, TiCDC has made many tradeoffs to meet the requirements of its target scenarios. In the next chapter, I will further analyze the tradeoffs made during the process of building TiCDC.</p><h2 id="Lessons-learned-from-this-project"><a href="#Lessons-learned-from-this-project" class="headerlink" title="Lessons learned from this project"></a>Lessons learned from this project</h2><p>In this part I will talk about stories behind several core features development, including how technology decision was made, the history of implementation evolution and what I have learned from these stories.</p><h3 id="The-old-value-feature"><a href="#The-old-value-feature" class="headerlink" title="The old value feature"></a>The old value feature</h3><p>In the first version of TiKV cdc component, it only captures the put or delete KV operation, so for the delete or update SQL in the upstream, TiKV cdc outputs the after image of this row only, making it impossible for TiCDC to output the before image of a row change, which is useful in many scenarios, such as the <a href="https://maxwells-daemon.io/dataformat/#update">old filed in maxwell protocol</a>, use old image for row positioning in message consuming scenario etc. After struggling without this feature for several months, we decided to implement it in TiKV cdc component. The implementation involved creating a <a href="https://github.com/tikv/tikv/blob/63d79d3cec8175dad0164ad6f7b390b573a54652/components/cdc/src/old_value.rs#L62">cache</a> for fast old value retrival, and if cache miss occurs, the cdc component would <a href="https://github.com/tikv/tikv/blob/63d79d3cec8175dad0164ad6f7b390b573a54652/components/cdc/src/old_value.rs#L152-L154">seek key-value pair from snapshot of kv engine</a>. This feature has become the fundamental of cdc data source, and achieves data completeness. TiCDC doesn’t need to subscribe change logs of index region and has more flexibility in data processing.</p><p>Initially, there were concerns about the performance and complexity of implementing the old value feature in TiKV cdc, but we ignore the functional necessity. However, the functional necessity of this feature is reasonable, fundamental, and important, making it worth investing a significant amount of labor and resources into. Fortunately we finally decided to solve this problem. To our surprise after we started working on solving this problem, we didn’t meet many problems that we used to concern, and did not consume too much manpower while working on this feature. Overall, adding the old value feature to TiKV cdc was a significant improvement that solved a crucial problem and provided more flexibility in data processing. It was an essential investment that proved to be worthwhile.</p><h3 id="The-history-of-sorter"><a href="#The-history-of-sorter" class="headerlink" title="The history of sorter"></a>The history of sorter</h3><p>At the very begining, TiCDC only has a in memory sorter,  which runs very fast but prone to OOM errors.  In order to avoid OOM we have to restrict the input buffer size which is used for buffer pending events in memory sorter, making it impossible to handle the incremental scan scenario (The incremental scan scenario refers to TiCDC starts to synchronize data from an old TSO, TiKV scans large size data from snapshot of kv engine and all of this data needs to be sorted together).</p><p>To address this limitation, we designed the unified sorter, which combines memory sorter and disk based merge sorter. The unified sroter solves both OOM problem and the problem of large historical data incremental scan, which is benefit from the cache capability provided by disk storage. However in the replication model, each table needs to start a table pipeline for data processing, and <a href="https://github.com/pingcap/tiflow/blob/57673d9a4676cfb5eeea531961eca0588c10eac2/cdc/processor/pipeline/sorter.go#L88">each table pipeline needs to initialize a UnifiedSorter object</a>. When TiCDC needs to replicate large amount tables, for example 60M tables, TiCDC has to open several files for each table pipeline and meets <code>no space left on device</code> error (ref: <a href="https://github.com/pingcap/tiflow/issues/2793">pingcap&#x2F;tiflow&#x2F;issues&#x2F;2793</a>).</p><p>To address the file descriptor problem, two solutions were proposed, optimizing the unified sorter or using a different sorting mechanism that can sort over multiple tables and provide read API by tables. After discussion an <a href="https://github.com/pingcap/tiflow/blob/07d53135540a7445ae4882bb46ff0258ac88c73b/docs/design/2022-03-16-ticdc-db-sorter.md">LSM tree based db sorter</a> was adopted and it took about half a year to mature this feature.</p><p>Along with the usage scenarios increase, the data scale continues to expand,  TiCDC’s performance is facing increasingly stringent challenge. The evolution of this feature deeply reflects the evolution of scenarios and requirements.</p><h3 id="The-buggy-history-of-flow-control"><a href="#The-buggy-history-of-flow-control" class="headerlink" title="The buggy history of flow control"></a>The buggy history of flow control</h3><p>As a monolithic architecture, TiCDC components are all running in the same process and the internal data flow is connected via golang channel. For quite a long time we didn’t make detail regulation between components to restrict the rate of data input and output, or have a overall flow control and back pressure design. We met many bugs mainly OOM and deadlocks, such as <a href="https://github.com/pingcap/tiflow/issues/1675">pingcap&#x2F;tiflow&#x2F;issues&#x2F;1675</a>, <a href="https://github.com/pingcap/tiflow/issues/3531">pingcap&#x2F;tiflow&#x2F;issues&#x2F;3531</a>, <a href="https://github.com/pingcap/tiflow/issues/3338">pingcap&#x2F;tiflow&#x2F;issues&#x2F;3338</a>. In order to solve these problems, we made many bug fixes and they can be grouped into several categories:</p><ul><li>Split critical tasks and secondary tasks to avoid the starvation of critical task slows down the whole system, even causes deadlock. A real example of this fix is to run DDL EventFeed stream in an independent gRPC connection.</li><li>Replace blocking API with non-blocking API, if the blocking code could trigger a chain reaction and cause deadlock.</li><li>Choose the push model or pull model carefully, especially when handling complex data flow and scenes full of uncertainty, such as huge performance changes in either producer or consumer, multiple data flows that are affected each other (that is the exactly the old situation in TiCDC push model and table based memory control, each table has its own memory quota, but the progress of each table is controlled by a global watermark, on the other hand the global watermark is decided by the resolved watermark of each table).</li></ul><p>Apart from the bug fixes, ticdc also made several architecture refactor, changing from the original channel driven model, to table pipeline model, then to actor model, and finally made a pull based model(in sink part, except for puller and sorter). Each refactor consumed a lot of manpower, however most of the codes in pipeline model and actor model are not used any more. As a matter of fact we used to disscuss the microservice architecture for TiCDC and tried to build each computing components into independent services, such as puller service, sorter service and sink service, they can be connected with explicit API and under clear flow control. However, these plans were not fully realized due to product strategy and a lack of strong execution. Despite this, the TiCDC team is currently considering evolving the project to accommodate multi tenancy scenario, this is an existing evolution, let’s wait and see it happens.</p><p>It is always a controversial topic about whether to adopt a microservices architecture and how to divide services. Recently there is a hot discussion about microservices, <a href="https://www.primevideotech.com/video-streaming/scaling-up-the-prime-video-audio-video-monitoring-service-and-reducing-costs-by-90">Prime Video audio&#x2F;video monitoring service reduced costs by 90% by migrating from a microservice to a single process</a> and another similar article provides high level summary of <a href="https://coolshell.cn/articles/22422.html">serverless, microservices, and monolithic architecture</a>, and concludes several principles for dividing microservices:</p><ol><li>Bounded context. The granularity of microservices cannot be larger than the Bounded Context in Domain-Driven Design, which is a business domain.</li><li>Single responsibility, high cohesion, and loose coupling. Combine what changes for the same reason (cohesion) and separate what changes for different reasons (decoupling).</li><li>Transactions and consistency. For two heavily dependent functions that require completing a transaction and ensuring strong consistency, it is best not to separate them and keep them together.</li><li>Match the organizational structure. Keep things from the same team together and separate those from different teams.</li></ol><p>Regarding the above three points, TiCDC is well suited for service-oriented decomposition:</p><ol><li>The puller and sink are highly abstract source and sink components, very similar to the abstraction of <a href="https://docs.confluent.io/platform/current/connect/kafka_connectors.html">Kafka Connectors</a>; the sorter is data consistency oriented component, and the mounter is a computing component used for data processing and transforming.</li><li>Referring to the first point, these four components are independent in the business domain and have computing responsibilities that meet the characteristics of high cohesion and low coupling.</li><li>Each data change in TiCDC includes a global timestamp (TSO), and TiCDC provides watermark with linearizability guarantee (which is called <a href="https://docs.pingcap.com/tidb/dev/ticdc-architecture#resolvedts">resolved-ts</a> in TiCDC). The sorting of timestamps can ensure consistency of data across components, and there is no need for transaction-level constraints between components.</li></ol><p>In fact, during the process of TiCDC’s future cloudification and moving to service-oriented architecture, there must be many known problems, such as the cost and binding issues when integrating with cloud computing components; the impact on system latency, cost increase, SLA, and operational costs due to the data flow pattern of inter-service communication after splitting into multiple services, all of which need to be addressed and there is a long way to go.</p><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>Although the development of TiCDC has made mistakes, took some long detours, this is the inevitable process and it’s important to learn from mistakes and improve upon them.</p><p>Regarding the ideal evolution routine I think TiCDC should abstract the key computing components and define two types of interfaces for interaction between components. By using golang channels for intra-process communication and RPC for inter-process communication, TiCDC could become a flexible and scalable system.</p><p>In addition, the ability to use TiCDC as a monolithic application, as well as separate it into different computing services, would provide more flexibility in deployment options. For example, TiCDC could be quickly deployed on-premises in the form of monolithic application, or used in a cloud environment where it can leverage various general-purpose computing capabilities such as S3 or message queues, in the form of microservice architecture.</p><p>Overall, these changes would make TiCDC a more powerful and versatile tool for data integration and processing, providing users with more options to adapt to their specific requirements.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;&lt;a href=&quot;https://github.com/pingcap/tiflow&quot;&gt;TiCDC&lt;/a&gt; is a change data capture framework developed for &lt;a href=&quot;https://github.com/pingcap/tidb&quot;&gt;TiDB&lt;/a&gt; ecosystem. It allows for the replication of change data to various downstream systems, including MySQL protocol-compatible databases, messaging queue systems like Kafka, and Object Storage Service like S3. As the top one code contributor and the former tech leader of this project, I witnessed the project from a concept to a mature system running in many product environments, and also led several important architecture evolutions of this project. At this moment, I’m going to leave this project and explore new opportunities, I’d like to retrospect and summarize the lessons I have learned from this project.&lt;/p&gt;
&lt;h2 id=&quot;Highlights-of-this-system&quot;&gt;&lt;a href=&quot;#Highlights-of-this-system&quot; class=&quot;headerlink&quot; title=&quot;Highlights of this system&quot;&gt;&lt;/a&gt;Highlights of this system&lt;/h2&gt;&lt;p&gt;In this part I will talk about the highlights of TiCDC, from the perspectives of system architecture, core features, smart design or some engineering implementations.&lt;/p&gt;
&lt;h3 id=&quot;A-well-designed-plug-and-play-monolithic-architecture&quot;&gt;&lt;a href=&quot;#A-well-designed-plug-and-play-monolithic-architecture&quot; class=&quot;headerlink&quot; title=&quot;A well designed plug-and-play, monolithic architecture&quot;&gt;&lt;/a&gt;A well designed plug-and-play, monolithic architecture&lt;/h3&gt;&lt;p&gt;TiCDC stands out due to its well-designed plug-and-play monolithic architecture. Setting up a synchronization path for replicating row-based change data from an existing TiDB cluster is a breeze. Users only need to deploy one or more TiCDC processes connected to the same TiDB cluster to form a unified cluster automatically, without any topology configuration, meta-system deployment, or separated components. Different compute components, including the data source part(puller), data sort part(sorter), data encapsulation part(mounter) and data sink part(sink) are running in the same process. That is what I mean it is a plug-and-play system, and it is a classic monolithic architecture. In addition to its straightforward deployment, TiCDC is designed to handle system maintenance effectively, especially for managing many high-availability scenarios automatically, including node crasing, upstream failure, network partition and so on. TiCDC provides high availability at both the process and data levels.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="performance" scheme="http://amyangfei.me/tags/performance/"/>
    
    <category term="cdc" scheme="http://amyangfei.me/tags/cdc/"/>
    
    <category term="scalability" scheme="http://amyangfei.me/tags/scalability/"/>
    
    <category term="high avavailability" scheme="http://amyangfei.me/tags/high-avavailability/"/>
    
  </entry>
  
  <entry>
    <title>An investigation of execution timeout with go-mysql</title>
    <link href="http://amyangfei.me/2023/04/14/diagnose-go-mysql-execution-timeout/"/>
    <id>http://amyangfei.me/2023/04/14/diagnose-go-mysql-execution-timeout/</id>
    <published>2023-04-13T16:00:00.000Z</published>
    <updated>2023-04-14T12:43:57.118Z</updated>
    
    <content type="html"><![CDATA[<p>This is a real case in my recent work with <a href="https://github.com/go-sql-driver/mysql">go-mysql</a> client. In this scenario, there exits a MySQL connection pool(which maintains multiple database connections) that keeps writing transactions to peer databases, such as a MySQL or TiDB. Each transaction contains several insert, update or delete DMLs, the DML count ranges from 40 to 128. In order to reduce round trip between MySQL client and MySQL server, we adopt the <a href="https://dev.mysql.com/doc/c-api/8.0/en/c-api-multiple-queries.html">multiple statements</a> in transaction, which conbines multiple DMLs in a single SQL statement. A sample code snippet with go-sql-driver is as follows.</p><span id="more"></span><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// normal transaction</span></span><br><span class="line"></span><br><span class="line">dsn := <span class="string">&quot;root@tcp(127.0.0.1:3306)/test?interpolateParams=false&quot;</span></span><br><span class="line">db, err := sql.Open(<span class="string">&quot;mysql&quot;</span>, dsn)</span><br><span class="line"><span class="comment">// handle err</span></span><br><span class="line"></span><br><span class="line">tx, err := db.BeginTx(ctx, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">// handle err</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i := <span class="keyword">range</span> sqls &#123;</span><br><span class="line">  _, err := tx.ExecContext(ctx, sqls[i], args[i])</span><br><span class="line">  <span class="comment">// handle err</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">_, err = tx.Commit()</span><br><span class="line"><span class="comment">// handle err</span></span><br></pre></td></tr></table></figure><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// use multiple statements</span></span><br><span class="line"></span><br><span class="line">dsn := <span class="string">&quot;root@tcp(127.0.0.1:3306)/test?multiStatements=true&amp;interpolateParams=true&quot;</span></span><br><span class="line">db, err := sql.Open(<span class="string">&quot;mysql&quot;</span>, dsn)</span><br><span class="line"><span class="comment">// handle err</span></span><br><span class="line"></span><br><span class="line">tx, err := db.BeginTx(ctx, <span class="literal">nil</span>)</span><br><span class="line"><span class="comment">// handle err</span></span><br><span class="line"></span><br><span class="line">multiStmtSQL := <span class="string">&quot;&quot;</span></span><br><span class="line">argvs := <span class="built_in">make</span>([]<span class="keyword">interface</span>&#123;&#125;, <span class="number">0</span>)</span><br><span class="line"><span class="keyword">for</span> i := <span class="keyword">range</span> sqls &#123;</span><br><span class="line">  multiStmtSQL += sqls[i] + <span class="string">&quot;;&quot;</span></span><br><span class="line">  argvs = <span class="built_in">append</span>(argvs, args[i]...)</span><br><span class="line">&#125;</span><br><span class="line">_, err := tx.ExecContext(ctx, multiStmtSQL, argvs)</span><br><span class="line"><span class="comment">// handle err</span></span><br><span class="line"></span><br><span class="line">_, err = tx.Commit()</span><br><span class="line"><span class="comment">// handle err</span></span><br></pre></td></tr></table></figure><p>After the we change from common transaction to multiple statements SQL, we benchmark the write performance in two different environments, the main difference is that one is X86 architecture physical machine, and the other one is an ARM architecture cluster. To our surprise in the ARM cluster write throughput has 140%-180% regression and we meet many network packet errors from sql driver, while in the X86 cluster there is no regression. From logs we can observed <code>tx.ExecContext()</code> was blocked and timeout after 2 minutes, the underlying timeout happens in sql driver and the <a href="https://github.com/go-sql-driver/mysql/blob/5cee457661043566c72c86b89aadbab7b88cce7a/packets.go#L32-L37">read from TCP connection</a>.</p><blockquote><p>[2023&#x2F;03&#x2F;22 19:25:45.304 +08:00] [ERROR] [packets.go:37] [“read tcp 10.233.80.156:42700-&gt;10.109.103.19:4000: i&#x2F;o timeout”] [component&#x3D;”[mysql]”]</p><p>[2023&#x2F;03&#x2F;22 19:25:45.305 +08:00] [WARN] [mysql.go:819] [“execute DMLs with error, retry later”] [error&#x3D;”MySQL txn error: invalid connection”] [duration&#x3D;2m0.039613308s] [query&#x3D;”…”] [count&#x3D;78]</p></blockquote><p>The <code>invalid connection</code> error is very common, it can be caused by many reasons. For example if the client connection is idle for a time longer than <code>conn-max-life-time</code> in MySQL server, the peer MySQL will close the connection, and once the client writes data in this connection, <code>invalid connection</code> error will raise. To verify whether this is the cause, I checked the <code>*DB.SetConnMaxLifetime</code> in client side and <code>wait_timeout</code> variables in MySQL server side, they are both with proper value. Besides there isn’t any connection disconnecting log in MySQL server side. I have two possible suspicions here that causes write timeout in MySQL client</p><ul><li>One is there isn’t any data written to MySQL server, and the data is blocked somewhere such as the network send buffer.</li><li>The other one is the transaction has been sent to MySQL and MySQL executes the query successfully but the response can’t be received by client side for some reasons.</li></ul><p>Besides I checked kernel diagnostic messages via <code>dmesg -T</code> and founnd many following errors.</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">[Wed Mar 22 21:40:41 2023] hns3 0000:bd:00.0 enp189s0f0: L3/L4 error pkt</span><br><span class="line">[Wed Mar 22 21:40:41 2023] hns3 0000:bd:00.0 enp189s0f0: L3/L4 error pkt</span><br><span class="line">[Wed Mar 22 21:41:13 2023] hns3 0000:bd:00.0 enp189s0f0: L3/L4 error pkt</span><br><span class="line">[Wed Mar 22 21:41:13 2023] hns3 0000:bd:00.0 enp189s0f0: L3/L4 error pkt</span><br><span class="line">[Wed Mar 22 21:41:13 2023] hns3 0000:bd:00.0 enp189s0f0: L3/L4 error pkt</span><br><span class="line">[Wed Mar 22 21:41:13 2023] hns3 0000:bd:00.0 enp189s0f0: L3/L4 error pkt</span><br></pre></td></tr></table></figure><p>The error message suggests that there was an issue with the packet’s routing or delivery at the network or transport layer. So I captured the TCP package with tcpdump and observed it with wireshark. First I query packets with <code>tcp.flags.fin == 1</code> to find out the port on disconnect connections. Then I picked one of the ports <code>tcp.port == 36582</code> and observed its behavior.</p><p><img src="/images/20230414_tcpdump.png" alt="tcpdump analysis"></p><ul><li>Based on the data, Number-11447 is the last MySQL response OK packet received by client on port 36582, and the data packet has <code>More results = 1</code> set by MySQL, indicating that there should be more response OK packets to follow.</li><li>However, within the 120 seconds timeout period, the client side did not receive any more response OK packets.</li><li>This phenomenon is consistent with MySQL server not having the “write: broken pipe” log, suggesting that MySQL sent the response data but lost it at the network layer. Therefore, MySQL network driver on the client side is blocked at the read packet call.</li></ul><p>At this point, I believe the error was caused by the NIC driver. About several weeks later, after the NIC driver is upgraded by technical support of hardware vendors, this error disappears and everything is back to normal.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;This is a real case in my recent work with &lt;a href=&quot;https://github.com/go-sql-driver/mysql&quot;&gt;go-mysql&lt;/a&gt; client. In this scenario, there exits a MySQL connection pool(which maintains multiple database connections) that keeps writing transactions to peer databases, such as a MySQL or TiDB. Each transaction contains several insert, update or delete DMLs, the DML count ranges from 40 to 128. In order to reduce round trip between MySQL client and MySQL server, we adopt the &lt;a href=&quot;https://dev.mysql.com/doc/c-api/8.0/en/c-api-multiple-queries.html&quot;&gt;multiple statements&lt;/a&gt; in transaction, which conbines multiple DMLs in a single SQL statement. A sample code snippet with go-sql-driver is as follows.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="mysql" scheme="http://amyangfei.me/tags/mysql/"/>
    
    <category term="go-mysql" scheme="http://amyangfei.me/tags/go-mysql/"/>
    
    <category term="tcpdump" scheme="http://amyangfei.me/tags/tcpdump/"/>
    
  </entry>
  
  <entry>
    <title>Tips about golang memory diagnostics</title>
    <link href="http://amyangfei.me/2022/06/26/golang-memory-diagnose/"/>
    <id>http://amyangfei.me/2022/06/26/golang-memory-diagnose/</id>
    <published>2022-06-25T16:00:00.000Z</published>
    <updated>2022-10-14T14:34:08.716Z</updated>
    
    <content type="html"><![CDATA[<p>When we diagnose performance issues of a running system, memory issue is always a must check item, which could affect latency, throughput, jitter from many aspects. This article focuses on memory issue in golang program, and summaries how to diagnose golang memory issues with the help of principles and toolchains.</p><span id="more"></span><h1 id="Golang-memory-management"><a href="#Golang-memory-management" class="headerlink" title="Golang memory management"></a>Golang memory management</h1><p>Understanding the principles of golang memory management is a necessary prerequisite before digging into memory problems. Memory management is a large concept including memory model, memory layout, stack and heap usage, memory allocation and release, as for golang it is the topic of garbage collection. First of all this article lists some great resources talking about these topics.</p><ul><li>memory model, memory layout<ul><li><a href="https://go.dev/ref/mem">The Go Memory Model</a>, this is from the golang official blog.</li><li><a href="https://go101.org/article/memory-layout.html">go101, Memory Layouts</a></li></ul></li><li>golang stack and heap<ul><li><a href="https://deepu.tech/memory-management-in-golang/">Visualizing memory management in Golang</a></li><li><a href="https://medium.com/eureka-engineering/understanding-allocations-in-go-stack-heap-memory-9a2631b5035d">Understanding Allocations in Go</a>, this article talks deeply about what happens when allocating memory in golang.</li></ul></li><li>golang GC<ul><li><a href="https://go.dev/blog/ismmkeynote">Getting to Go: The Journey of Go’s Garbage Collector</a></li><li><a href="https://blog.plan99.net/modern-garbage-collection-911ef4f8bd8e">Modern garbage collection - A look at the Go GC strategy</a></li><li><a href="https://xargin.com/impl-of-go-gc/">Implementation of go GC(in Chinese)</a></li></ul></li></ul><h1 id="How-to-diagnose-memory-problem"><a href="#How-to-diagnose-memory-problem" class="headerlink" title="How to diagnose memory problem"></a>How to diagnose memory problem</h1><p>It is common to meet the following memory problems, this section will discuss diagnostics of golang memory problem and the next section will talk about some best practises to write memory friendly code in golang.</p><ul><li>runtime.gcBgMarkWorker costs a large amount of CPU time, what is going on actually?</li><li>I have added a memory allocation restriction to my problem but why is it still OOM?</li><li>Why is memory allocation so slow, which costs nearly one second?</li><li>Besides the memory usage, are there any more metrics that can help to diagnose memory problems?</li><li>When a memory problem is located, what can I do to fix it or improve the situation?</li></ul><h2 id="Metrics"><a href="#Metrics" class="headerlink" title="Metrics"></a>Metrics</h2><p>Go runtime provides a <a href="https://pkg.go.dev/runtime/metrics">builtin memory metrics</a>, it is easy to use <a href="https://github.com/prometheus/client_golang">prometheus&#x2F;client-go</a> to access these metrics. Note before go1.17, these metrics are <a href="https://github.com/prometheus/client_golang/blob/2c3d072cdd4dbd9dbbfe415cbd01851db8962289/prometheus/collectors/go_collector_go116.go#L21">collected by <code>runtime.ReadMemStats</code> function</a>, which requires <code>stop the world</code> and should take the implications into account when deciding whether to use the Go collector. While since go1.17 it <a href="https://github.com/prometheus/client_golang/blob/2c3d072cdd4dbd9dbbfe415cbd01851db8962289/prometheus/collectors/go_collector_latest.go#L83">uses <code>runtime/metrics</code></a> instead. As for the detailed description of each metric can be found in <a href="https://povilasv.me/prometheus-go-metrics/">prometheus go metrics</a>, this article pays attention to part of these metrics.</p><h3 id="memory-size-and-gc-related"><a href="#memory-size-and-gc-related" class="headerlink" title="memory size and gc related"></a>memory size and gc related</h3><ul><li><em><strong>process_resident_memory_bytes</strong></em>: the memory allocated from the OS, which means the amount of memory that belongs specifically to this process in bytes, known as <strong>rss</strong>.</li><li><em><strong>go_memstats_next_gc_bytes</strong></em>: the target heap size for the end of the next GC cycle.</li><li><em><strong>go_memstats_next_gc_bytes &#x2F; (1 + GOGC &#x2F; 100)</strong></em>: an estimated heap size that is <strong>being used</strong> by program, and also the memory that can be <strong>fully</strong> managed by program. It was estimated by next GC threshold and GOGC parameter, and it should be almost equal to the <code>inuse_space</code> from pprof heap profile. Besides, between two consecutive GC, this value stays unchanged(because <code>go_memstats_next_gc_bytes</code> doesn’t change during that time), and that’s why <code>inuse_space</code> and heap profile details stay unchanged during two GC.</li><li><em><strong>go_memstats_heap_alloc_bytes - go_memstats_next_gc_bytes &#x2F; (1 + GOGC &#x2F; 100)</strong></em>: it approximately equals to the size of garbage memory. Combining <code>being used memory</code> and <code>estimate garbage memory</code>, in some memory increasing scenario, we can deduce whether the memory increasing is caused by real memory usage increasing, or is caused by slow GC.</li><li><em><strong>go_memstats_last_gc_time_seconds</strong></em>: contains unix timestamp when last GC finished. We can use <code>(clamp_max(idelta(go_memstats_last_gc_time_seconds&#123;&#125;[1m]), 1)) &gt; 0</code> to tell when GC happens.</li><li><em><strong>go_gc_duration_seconds</strong></em>: calls <code>debug.ReadGCStats()</code> with <a href="https://github.com/prometheus/client_golang/blob/2c3d072cdd4dbd9dbbfe415cbd01851db8962289/prometheus/go_collector.go#L253-L254">PauseQuantile set to 5</a>, which returns the minimum, 25%, 50%, 75%, and maximum pause times. From this metric we can get the maximum GC stw duration, which will lead to the same latency to program.</li></ul><h3 id="allocate-and-free-rate"><a href="#allocate-and-free-rate" class="headerlink" title="allocate and free rate"></a>allocate and free rate</h3><ul><li><em><strong>irate(go_memstats_alloc_bytes_total)</strong></em>: <code>go_memstats_alloc_bytes_total</code> keeps increasing as objects are allocated in the heap, but doesn’t decrease when they are freed. Calling <code>irate</code> with it can reflect the throughput of memory allocation (qps).</li><li><em><strong>irate((go_memstats_alloc_bytes_total{} - go_memstats_heap_alloc_bytes{})[30s:])</strong></em>: this can be used to query the throughput of memory free.</li><li><em><strong>irate(go_memstats_mallocs_total)</strong></em>: shows how many heap objects are allocated. Calling <code>irate</code> with it can reflect memory allocated operation rate (ops).</li><li><em><strong>irate(go_memstats_frees_total)</strong></em>: shows how many heap objects are freed. Calling <code>irate</code> with it can reflect memory release operation rate (ops).</li></ul><h2 id="More-diagnose-methods"><a href="#More-diagnose-methods" class="headerlink" title="More diagnose methods"></a>More diagnose methods</h2><ul><li><a href="https://go.dev/doc/diagnostics">Tracing and Debugging</a></li><li>Some debug cases:<ul><li>mark assist case: <a href="https://github.com/golang/go/issues/27732">https://github.com/golang/go/issues/27732</a></li><li>sweep latency: <a href="https://github.com/golang/go/issues/18155">https://github.com/golang/go/issues/18155</a></li></ul></li></ul><h1 id="Common-memory-related-optimization"><a href="#Common-memory-related-optimization" class="headerlink" title="Common memory related optimization"></a>Common memory related optimization</h1><p>Some common optimization ways will be discussed in this part, since GC is not a silver bullet for all scenarios, and golang GC and runtime are changing with every new release, the following optimization ways are suitable for specific scenarios.</p><ul><li>The hack way to leverage cpu usage and GC performance by configuring GOGC. A real case about GOGC optimization is discussed in <a href="https://eng.uber.com/how-we-saved-70k-cores-across-30-mission-critical-services/">How We Saved 70K Cores Across 30 Mission-Critical Services (Large-Scale, Semi-Automated Go GC Tuning @Uber)</a>. Basically, this way is trying to adjust <code>GOGC</code> to an appropriate value based on the hard limit of memory, it is suitable for the scenario that has higher memory&#x2F;CPU ratio, or the live_dataset is much less than hard limit of memory, in such scenarios, increasing <code>GOGC</code> will make the GC happens less frequenlty. There is a proof why increasing <code>GOGC</code> can decrease CPU costs in <a href="https://tip.golang.org/doc/gc-guide#Additional_notes_on_GOGC">golang doc</a>. Note althrough increasing <code>GOGC</code> can decrease CPU cost, it doesn’t mean the larger memory the better, since golang GC has there trigger conditions, including <a href="https://github.com/golang/go/blob/4aa1efed4853ea067d665a952eee77c52faac774/src/runtime/mgc.go#L549-L565">gcTriggerHeap, gcTriggerTime and gcTriggerCycle</a>. Considering we set <code>GOGC</code> to a large enough number(according to the hard limit of memory), each time the GC is triggered by <code>gcTriggerTime</code>(2 minutes by default) instead of <code>gcTriggerHeap</code>, the golang process won’t consume as much memory as <code>live_dataset * (1+GOGC/100)</code> and a lot of memory is not fully used.</li><li>Use go ballast to reduce GC frequency, this is originally used in twitch and described in article <a href="https://blog.twitch.tv/en/2019/04/10/go-memory-ballast-how-i-learnt-to-stop-worrying-and-love-the-heap/">Go memory ballast: How I learnt to stop worrying and love the heap</a>, there is also a related discussion in <a href="https://github.com/golang/go/issues/23044">golang&#x2F;go&#x2F;issues&#x2F;23044</a>.</li><li>Have a deep mind about whether memory is allocated in stack or heap, feel comfortable to use memory escape analysis and follow some best practises about variable passing, such as for small data, use pass-by-value instead of pointer, which do not escape to heap and can be recycled in time, in order to reduce GC pressure. Especially the variables passing by code snippet is a hot path. In the article <a href="https://blog.devgenius.io/in-depth-analysis-of-golang-memory-escape-edfbfb856913">Golang Memory Escape In-Depth Analysis</a> has more details about escape analysis.</li><li>Avoid <a href="https://go101.org/article/memory-leaking.html">common memory leaking patterns</a>.</li><li>Since go1.19 (which has not been released so far), a new <code>runtime/debug</code> function called <code>SetMemoryLimit</code> will be provided, this feature adds a memory limit that would give the Go runtime the information it needs to both respect users’ memory limits, and allow them to optionally use that memory always, to cut back the cost of garbage collection. It mainly focuses to solve the out-of-memory problem, but note OOM can still happen when memory limit is set. The tracking issue of this feature is <a href="https://github.com/golang/go/issues/48409">golang&#x2F;go&#x2F;issues&#x2F;48409</a>.</li></ul><h1 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h1><ul><li><a href="https://go.dev/ref/mem">The Go Memory Model</a></li><li><a href="https://go101.org/article/memory-layout.html">go101, Memory Layouts</a></li><li><a href="https://deepu.tech/memory-management-in-golang/">Visualizing memory management in Golang</a></li><li><a href="https://medium.com/eureka-engineering/understanding-allocations-in-go-stack-heap-memory-9a2631b5035d">Understanding Allocations in Go</a></li><li><a href="https://go.dev/blog/ismmkeynote">Getting to Go: The Journey of Go’s Garbage Collector</a></li><li><a href="https://blog.plan99.net/modern-garbage-collection-911ef4f8bd8e">Modern garbage collection - A look at the Go GC strategy</a></li><li><a href="https://xargin.com/impl-of-go-gc/">Implementation of go GC(in Chinese)</a></li><li><a href="https://povilasv.me/prometheus-go-metrics/">prometheus go metrics</a></li><li><a href="https://go.dev/doc/diagnostics">Tracing and Debugging</a></li><li><a href="https://eng.uber.com/how-we-saved-70k-cores-across-30-mission-critical-services/">How We Saved 70K Cores Across 30 Mission-Critical Services (Large-Scale, Semi-Automated Go GC Tuning @Uber)</a></li><li><a href="https://blog.twitch.tv/en/2019/04/10/go-memory-ballast-how-i-learnt-to-stop-worrying-and-love-the-heap/">Go memory ballast: How I learnt to stop worrying and love the heap</a></li><li><a href="https://blog.devgenius.io/in-depth-analysis-of-golang-memory-escape-edfbfb856913">Golang Memory Escape In-Depth Analysis</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;When we diagnose performance issues of a running system, memory issue is always a must check item, which could affect latency, throughput, jitter from many aspects. This article focuses on memory issue in golang program, and summaries how to diagnose golang memory issues with the help of principles and toolchains.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="system diagnose" scheme="http://amyangfei.me/tags/system-diagnose/"/>
    
    <category term="memory" scheme="http://amyangfei.me/tags/memory/"/>
    
    <category term="GC" scheme="http://amyangfei.me/tags/GC/"/>
    
  </entry>
  
  <entry>
    <title>An investigation into slow sudo command</title>
    <link href="http://amyangfei.me/2022/02/20/diagnose-slow-sudo/"/>
    <id>http://amyangfei.me/2022/02/20/diagnose-slow-sudo/</id>
    <published>2022-02-19T16:00:00.000Z</published>
    <updated>2022-02-20T06:11:56.864Z</updated>
    
    <content type="html"><![CDATA[<p>In recent days I created a new virtual machine with ubuntu 20.04, but I found the terminal command with <code>sudo</code> took a long time, almost 3 seconds each time. When I seach <code>sudo command slow</code> in Google, the first two search results are both from stackflow and suggest adding an entry <code>127.0.0.1 hostname</code> to <code>/etc/hosts</code> file. I checked <code>/etc/hosts</code> and found the entry <code>127.0.0.1 hostname</code> exists (in fact I made a mistake here, which I will describe later). This article describes the investigation into this issue in timeline.</p><span id="more"></span><h2 id="Investigation-process"><a href="#Investigation-process" class="headerlink" title="Investigation process"></a>Investigation process</h2><p>Firstly I use the strace to record system calls information of a <code>sudo</code> command.</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo strace -r -T -o sudo_strace.log -e trace=all sudo <span class="built_in">echo</span> hi</span><br></pre></td></tr></table></figure><p>From the output of strace I find a suspicious point, <code>poll</code> read from <code>fd=4</code> costs 2.915s, based on the context of this system call, it is a DNS resolution for hostname <code>ubuntuwork.internal.xxx</code>. There exist several questions</p><ol><li>Why the DNS resolution for hostname doesn’t use host table directly</li><li>Why there is a DNS resolution for <code>ubuntuwork.internal.xxx</code></li><li>Why sudo command has a DNS resolution for hostname</li><li>Is there a DNS cache working</li></ol><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">0.000103</span> socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, IPPROTO_IP) = <span class="number">4</span> &lt;<span class="number">0.000043</span>&gt;</span><br><span class="line"><span class="number">0.000090</span> setsockopt(<span class="number">4</span>, SOL_IP, IP_RECVERR, [<span class="number">1</span>], <span class="number">4</span>) = <span class="number">0</span> &lt;<span class="number">0.000035</span>&gt;</span><br><span class="line"><span class="number">0.000085</span> connect(<span class="number">4</span>, &#123;sa_family=AF_INET, sin_port=htons(<span class="number">53</span>), sin_addr=inet_addr(<span class="string">&quot;127.0.0.53&quot;</span>)&#125;, <span class="number">16</span>) = <span class="number">0</span> &lt;<span class="number">0.000041</span>&gt;</span><br><span class="line"><span class="number">0.000093</span> poll([&#123;fd=<span class="number">4</span>, events=POLLOUT&#125;], <span class="number">1</span>, <span class="number">0</span>) = <span class="number">1</span> ([&#123;fd=<span class="number">4</span>, revents=POLLOUT&#125;]) &lt;<span class="number">0.000034</span>&gt;</span><br><span class="line"><span class="number">0.000087</span> sendmmsg(<span class="number">4</span>, [&#123;msg_hdr=&#123;msg_name=<span class="literal">NULL</span>, msg_namelen=<span class="number">0</span>, msg_iov=[&#123;iov_base=<span class="string">&quot;C\324\1 \0\1\0\0\0\0\0\1\nubuntuwork\10internal&quot;</span>..., iov_len=<span class="number">60</span>&#125;], msg_iovlen=<span class="number">1</span>, msg_controllen=<span class="number">0</span>, msg_flags=<span class="number">0</span>&#125;, msg_len=<span class="number">60</span>&#125;, &#123;msg_hdr=&#123;msg_name=<span class="literal">NULL</span>, msg_namelen=<span class="number">0</span>, msg_iov=[&#123;iov_base=<span class="string">&quot;\242\310\1 \0\1\0\0\0\0\0\1\nubuntuwork\10internal&quot;</span>..., iov_len=<span class="number">60</span>&#125;], msg_iovlen=<span class="number">1</span>, msg_controllen=<span class="number">0</span>, msg_flags=<span class="number">0</span>&#125;, msg_len=<span class="number">60</span>&#125;], <span class="number">2</span>, MSG_NOSIGNAL) = <span class="number">2</span> &lt;<span class="number">0.000355</span>&gt;</span><br><span class="line"><span class="number">0.000546</span> poll([&#123;fd=<span class="number">4</span>, events=POLLIN&#125;], <span class="number">1</span>, <span class="number">5000</span>) = <span class="number">1</span> ([&#123;fd=<span class="number">4</span>, revents=POLLIN&#125;]) &lt;<span class="number">2.915181</span>&gt;</span><br><span class="line"><span class="number">2.915528</span> ioctl(<span class="number">4</span>, FIONREAD, [<span class="number">60</span>])  = <span class="number">0</span> &lt;<span class="number">0.000168</span>&gt;</span><br><span class="line"><span class="number">0.000382</span> recvfrom(<span class="number">4</span>, <span class="string">&quot;C\324\201\203\0\1\0\0\0\0\0\1\nubuntuwork\10internal&quot;</span>..., <span class="number">2048</span>, <span class="number">0</span>, &#123;sa_family=AF_INET, sin_port=htons(<span class="number">53</span>), sin_addr=inet_addr(<span class="string">&quot;127.0.0.53&quot;</span>)&#125;, [<span class="number">28</span>-&gt;<span class="number">16</span>]) = <span class="number">60</span> &lt;<span class="number">0.000062</span>&gt;</span><br><span class="line"><span class="number">0.000185</span> poll([&#123;fd=<span class="number">4</span>, events=POLLIN&#125;], <span class="number">1</span>, <span class="number">2083</span>) = <span class="number">1</span> ([&#123;fd=<span class="number">4</span>, revents=POLLIN&#125;]) &lt;<span class="number">0.000057</span>&gt;</span><br><span class="line"><span class="number">0.000140</span> ioctl(<span class="number">4</span>, FIONREAD, [<span class="number">60</span>])  = <span class="number">0</span> &lt;<span class="number">0.000078</span>&gt;</span><br><span class="line"><span class="number">0.000170</span> brk(<span class="number">0x5582dd4ce000</span>)       = <span class="number">0x5582dd4ce000</span> &lt;<span class="number">0.000060</span>&gt;</span><br><span class="line"><span class="number">0.000142</span> recvfrom(<span class="number">4</span>, <span class="string">&quot;\242\310\201\203\0\1\0\0\0\0\0\1\nubuntuwork\10internal&quot;</span>..., <span class="number">65536</span>, <span class="number">0</span>, &#123;sa_family=AF_INET, sin_port=htons(<span class="number">53</span>), sin_addr=inet_addr(<span class="string">&quot;127.0.0.53&quot;</span>)&#125;, [<span class="number">28</span>-&gt;<span class="number">16</span>]) = <span class="number">60</span> &lt;<span class="number">0.000066</span>&gt;</span><br><span class="line"><span class="number">0.000390</span> close(<span class="number">4</span>)                  = <span class="number">0</span> &lt;<span class="number">0.000085</span>&gt;</span><br><span class="line"><span class="number">0.000159</span> brk(<span class="number">0x5582dd4be000</span>)       = <span class="number">0x5582dd4be000</span> &lt;<span class="number">0.000061</span>&gt;</span><br><span class="line"><span class="number">0.000112</span> socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, IPPROTO_IP) = <span class="number">4</span> &lt;<span class="number">0.000041</span>&gt;</span><br></pre></td></tr></table></figure><ol><li>For the first question, I re-check the hosts file and hostname, and find the mistake in hostname setting. From <a href="https://man7.org/linux/man-pages/man7/hostname.7.html">hostname(7)</a> we can see valid characters for hostnames are ASCII(7) letters from a to z, the digits from 0 to 9, and the hyphen (-). Since the underscore is invalid character in hostname, the system call <code>gethostbyname</code> will return <code>ubuntuwork</code> and it is not listed in host table. The DNS resolution procedure will first query host table, if the query item is not found, system will continue to check the <code>search</code> domain.</li></ol><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">➜  hostname</span><br><span class="line">ubuntuwork</span><br><span class="line"></span><br><span class="line">➜  <span class="built_in">cat</span> /etc/hosts</span><br><span class="line">127.0.0.1 localhost ubuntu_work</span><br><span class="line">127.0.1.1 ubuntu_work</span><br><span class="line"></span><br><span class="line">➜  <span class="built_in">cat</span> /etc/hostname</span><br><span class="line">ubuntu_work</span><br></pre></td></tr></table></figure><ol start="2"><li>By default, the search field in <code>/etc/resolv.conf</code> is empty but it can be configured with one or more search domains. After I check the <code>/etc/resolv.conf</code> I find <code>internal.xxx</code> in the search field. That explains why there is a DNS resolution for <code>ubuntuwork.internal.xxx</code>. There is another question, why does the dns lookup for a <code>no such name</code> host cost so much time?</li></ol><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">nameserver</span> <span class="number">127.0</span><span class="number">.0</span><span class="number">.53</span></span><br><span class="line"><span class="string">options</span> <span class="string">edns0</span> <span class="string">trust-ad</span></span><br><span class="line"><span class="string">search</span> <span class="string">internal.xxx</span></span><br></pre></td></tr></table></figure><ol start="3"><li><p>For the third question, in order for sudo to know whether this rule should be applied, it needs to lookup the host it is running on. More details are explained in a stackoverflow answer <a href="https://superuser.com/a/429890">sudo command trying to search for hostname</a>.</p></li><li><p>Is there a DNS cache for linux server? The answer is no in OS-level unless a caching service such as Systemd-Resolved, DNSMasq, or Nscd is installed and running. In ubuntu 20.04 systemd-resolved is enabled by default, and I check the cached items by following commands. The <code>USR1</code> signal will not stop the service but tells systemd-resolved to write all the current cache entries (and some other information) to the system log. After checking the output file for cached items by searching <code>CACHE:</code>. <code>ubuntuwork</code> is not in the cached items, which explains why the <code>sudo</code> is slow each time.</p></li></ol><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ sudo killall -USR1 systemd-resolved</span><br><span class="line">$ sudo journalctl -u systemd-resolved &gt; ./dns-cache.txt</span><br></pre></td></tr></table></figure><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>After I have figured out the root cause, I find either of the following ways can workaround and make the <code>sudo</code> run normally.</p><ul><li>Add an entry of <code>127.0.0.1 ubuntuwork</code> to <code>/etc/hosts</code></li><li>Remove the <code>search</code> line in <code>/etc/resolv.conf</code></li></ul><p>And actually, I should correct the hostname, such as renaming hostname from <code>ubuntuwork</code> to <code>ubuntu-work</code> and add corresponding entry to <code>/etc/hosts</code>.</p><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li><a href="https://man7.org/linux/man-pages/man7/hostname.7.html">hostname(7) man page</a></li><li><a href="https://superuser.com/a/429890">Sudo command trying to search for hostname</a></li><li><a href="http://manpages.ubuntu.com/manpages/focal/man8/systemd-resolved.service.8.html">systemd-resolved man page</a></li><li><a href="https://askubuntu.com/a/1281629">How can I see systemd-resolve dns cache?</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;In recent days I created a new virtual machine with ubuntu 20.04, but I found the terminal command with &lt;code&gt;sudo&lt;/code&gt; took a long time, almost 3 seconds each time. When I seach &lt;code&gt;sudo command slow&lt;/code&gt; in Google, the first two search results are both from stackflow and suggest adding an entry &lt;code&gt;127.0.0.1 hostname&lt;/code&gt; to &lt;code&gt;/etc/hosts&lt;/code&gt; file. I checked &lt;code&gt;/etc/hosts&lt;/code&gt; and found the entry &lt;code&gt;127.0.0.1 hostname&lt;/code&gt; exists (in fact I made a mistake here, which I will describe later). This article describes the investigation into this issue in timeline.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="strace" scheme="http://amyangfei.me/tags/strace/"/>
    
    <category term="dns" scheme="http://amyangfei.me/tags/dns/"/>
    
    <category term="system diagnose" scheme="http://amyangfei.me/tags/system-diagnose/"/>
    
  </entry>
  
  <entry>
    <title>Dive into the network regression affection to network service</title>
    <link href="http://amyangfei.me/2022/02/01/network-regression-affect-to-service/"/>
    <id>http://amyangfei.me/2022/02/01/network-regression-affect-to-service/</id>
    <published>2022-01-31T16:00:00.000Z</published>
    <updated>2022-08-27T13:23:21.004Z</updated>
    
    <content type="html"><![CDATA[<p>In recent work my team devoted in a cross region data replication solution, a simplified abstraction of the workload is as follows</p><img src="/images/20220201_service_architecture.png"><p>The gRPC service and downstream MySQL are located in different AWS regions(such as one in EU, and the other one in US East), and the average network latency between these two regions is 70ms. We have a choice to deploy the data transfer service in either gRPC service side or downstream MySQL side. After a series of tests, we observed that deploying data transfer service in the downstream(the downstream MySQL) side has much larger throughput than deploying it in the upstream(the gRPC service) side. This article will analyze the root cause from both benchmark result and principle analysis, try to find potential solutions and give advice about such scenarios.</p><span id="more"></span><h2 id="Comparing-different-workloads"><a href="#Comparing-different-workloads" class="headerlink" title="Comparing different workloads"></a>Comparing different workloads</h2><p>Intuitively the impact of network regression (including latency, packet loss etc.) is different in the above scenario, gRPC stream has no regression when having 75ms latency, while MySQL execution throughput drops a lot. In this section I will compare several workloads under network regression. The experiment was conducted on several servers in one IDC, and the network regression was simulated by <a href="https://github.com/chaos-mesh/chaosd">chaosd</a>. I simulated the network latency and packet loss, which are the most common network regression in the real world. The simulated workloads are as follows:</p><ol><li><p>The first one is a simple sysbench insert workload, writing data to 32 tables in MySQL directly with 32 sysbench threads.</p></li><li><p>The second one is to simulate a gRPC bidirectional stream between client and server, the client starts N workers, each one sets up a gRPC stream and receives data from gRPC server. The client will collect received data and report throughput every 10 seconds. The benchmark code can be found in <a href="https://github.com/amyangfei/grpc-test/tree/master/cmd">grpc-test</a>.</p></li><li><p>The third one is another MySQL usage scenario, but it has elastic workers compared to sysbench workload. Elastic worker means when the write to MySQL is slow, the program will spawn more workers to write to MySQL. Each worker writes simple insert SQL to MySQL, and there is no wait condition among workers, which means the worker can run concurrently and transactions in MySQL have no lock contention. The benchmark code can be found in <a href="https://github.com/amyangfei/grpc-test/blob/master/cmd/elastic_mysql_main.go">elastic_mysql</a>, besides the max pending workers in this experiment is <code>worker size * max pending per worker = 20 * 120 = 2400</code>.</p></li></ol><p>The benchmark result is as follows, note the absolute value of throughput is not essential, but we should pay attention to the throughput change when network regression happens.</p><table><thead><tr><th>Network latency</th><th align="center">0ms</th><th align="center">10ms</th><th align="center">25ms</th><th align="center">50ms</th><th align="center">75ms</th><th align="center">100ms</th><th align="center">150ms</th><th align="center">200ms</th></tr></thead><tbody><tr><td>sysbench insert</td><td align="center">10732</td><td align="center">2741</td><td align="center">1170</td><td align="center">603</td><td align="center">408</td><td align="center">309</td><td align="center">208</td><td align="center">157</td></tr><tr><td>gRPC bi-stream</td><td align="center">42.4M</td><td align="center">41.9M</td><td align="center">42.3M</td><td align="center">42.0M</td><td align="center">36.1M</td><td align="center">29.3M</td><td align="center">19.8M</td><td align="center">14.9M</td></tr><tr><td>elastic MySQL worker (qps&#x2F;pending workers)</td><td align="center">4000&#x2F;0</td><td align="center">4000&#x2F;80</td><td align="center">4000&#x2F;205</td><td align="center">4000&#x2F;420</td><td align="center">4000&#x2F;780</td><td align="center">3380&#x2F;2353</td><td align="center">2314&#x2F;2385</td><td align="center">1682&#x2F;2392</td></tr></tbody></table><img src="/images/20220201_throughput_regression_latency.png"><table><thead><tr><th>packet loss</th><th align="center">0</th><th align="center">2%</th><th align="center">5%</th><th align="center">10%</th><th align="center">15%</th></tr></thead><tbody><tr><td>sysbench insert</td><td align="center">10732</td><td align="center">5502</td><td align="center">2145</td><td align="center">1129</td><td align="center">684</td></tr><tr><td>gRPC bi-stream</td><td align="center">42.4M</td><td align="center">42.1M</td><td align="center">41.1M</td><td align="center">37.6M</td><td align="center">7.7M</td></tr><tr><td>elastic MySQL worker (qps&#x2F;pending workers)</td><td align="center">4000&#x2F;0</td><td align="center">4000&#x2F;20</td><td align="center">4000&#x2F;62</td><td align="center">4000&#x2F;156</td><td align="center">3999&#x2F;297</td></tr></tbody></table><img src="/images/20220201_throughput_regression_packet_loss.png"><p>In addition to the absolute value of throughput, the jitter of throughput is another important factor of service quality. Given the gRPC bi-stream and network loss scenario, we run each test for 10 minutes, observe throughput every 5 seconds and calculate the standard deviation divided by average throughput of these points to measure the throughput stability, and the test result is as follows.</p><img src="/images/20220201_throughput_stability.png"><p>It is easy to draw some conclusions from the above benchmark result</p><ul><li><p>The network regression(either latency or packet loss) impact on throughput in sysbench workload is significant. As for the reasons, in sysbench workload the throughput is decided by the thread count (which is a fixed number and configured by <code>--threads</code> when running sysbench) and throughput of a single thread. Each single thread executes transaction serially in a loop until meeting some exit condition(ref: <a href="https://github.com/akopytov/sysbench/blob/master/src/lua/internal/sysbench.lua#L29-L55">internal&#x2F;sysbench.lua:thread_run</a>). So in the sysbench workload, when response from MySQL is slowed down by network regression, the worker thread will waste a lot of time waiting for SQL execution response and leads to severe regression of throughput.</p></li><li><p>The network regression impact on throughput in gRPC bi-stream workload is not significant, which is achieved by the throughput optimization on high latency connections. gRPC-go implements a <a href="https://grpc.io/blog/grpc-go-perf-improvements/#bdp-estimation-and-dynamic-flow-control-window">BDP estimation and dynamic flow control window</a> feature. This feature calculates the current BDP (Bandwidth Delay Product (BDP) is the bandwidth of a network connection times its round-trip latency. This effectively tells us how many bytes can be “on the wire” at a given moment, if full utilization is achieved) and bandwidth sample and decides if the flow control windows should go up (<a href="https://docs.google.com/document/d/1Eq4eBEbNt1rc8EYuwqsduQd1ZfcBOCYt9HVSBa--m-E/pub">algorithm</a>). There exists a long issue(<a href="https://github.com/grpc/grpc-go/issues/1043">grpc-go issue#1043</a>) that discusses this topic, which deserves to take a look.</p></li><li><p>The network regression has no impact on throughput in elastic worker workload when the worker doesn’t reach the upper limit. Since more workers can be spawned when some pending executions are not returned, the SQL execution bandwidth (from the point view of server side) will be fully used, without time wasted in waiting for response to arrive at the client side. Compared with the gRPC scenario, the elastic worker is another kind of dynamic window.</p></li><li><p>Note we can’t achieve performance optimization by increasing worker size or buffer size infinitely. For example in the elastic MySQL worker scenario, when MySQL worker count increases, more lock contention will happend in either client side (more workers lead to heavy workload of runtime) or server side (more transactions lead to more lock conflicts). This can be treated as a kind of <a href="https://en.wikipedia.org/wiki/Bufferbloat">bufferbloat</a>. Known reasons for performance drawbacks include:</p><ul><li>More lock contention will happen in either the client side (more workers lead to heavy workload of runtime) or server side (more transactions lead to more lock conflicts).</li><li>More clients wait for response from server side leads to longer latency, more waiting clients could cause connection reset by peer because of timeout.</li></ul></li></ul><h2 id="Potential-solutions-to-increase-throughput"><a href="#Potential-solutions-to-increase-throughput" class="headerlink" title="Potential solutions to increase throughput"></a>Potential solutions to increase throughput</h2><p>Coming back to the scenario that is mentioned at the beginning of the article, our solution is to put the data transfer service in the same region with the downstream MySQL, but whether there exists other solutions? There may or may not, which is based on the cost of system modification, this section will talk about two potential solutions, one solution is to relay the data via a suitable protocol, and the other one is trying to tune the network via some networking tunnel.</p><h3 id="The-relay-service-solution"><a href="#The-relay-service-solution" class="headerlink" title="The relay service solution"></a>The relay service solution</h3><p>This solution is straightforward, it still deploys data transfer service in the upstream region, but it doesn’t execute SQLs directly to downstream MySQL, instead it works as a relay service, it works as a gRPC server that serves gRPC stream with translated SQLs, in the downstream we deploy another consumer service to receives translated SQLs from the relay service, and the consumer writes SQLs to the downstream MySQL. This solution has several advantages, as well as several disadvantages</p><ul><li>Advantages<ul><li>Reduce throughput loss with the help of good performance of gRPC on high latency network.</li><li>Reduce network bandwidth between upstream and downstream regions, because the data transferred is the minimal SQL data.</li></ul></li><li>Disadvantages<ul><li>Long data links will introduce larger latency.</li><li>More components will introduce more costs, both in development and system maintenance.</li></ul></li></ul><h3 id="Tuning-the-network-with-tunnel"><a href="#Tuning-the-network-with-tunnel" class="headerlink" title="Tuning the network with tunnel"></a>Tuning the network with tunnel</h3><p>kcptun is a tunnel based on <a href="https://github.com/skywind3000/kcp/blob/master/README.en.md">KCP</a> with N:M multiplexing and FEC(Forward error correction) for transfer error correction. KCP can achieve the transmission effect of a reduction of the average latency by 30% to 40% and reduction of the maximum delay by a factor of three, at the cost of 10% to 20% more bandwidth wasted than TCP. kcptun can be used in some cross-region scenarios to accelerate TCP stream, in order to verify whether kcptun can help the above scenario, I test the sysbench workload with kcptun again. The basic topology is as follows</p><img src="/images/20220201_accelerate_with_kcptun.png"><table><thead><tr><th></th><th align="center">0-100ms</th><th align="center">0-50ms</th><th align="center">0-25ms</th><th align="center">0-10ms</th><th align="center">100ms</th><th align="center">50ms</th><th align="center">25ms</th><th align="center">10ms</th></tr></thead><tbody><tr><td>Direct write</td><td align="center">969</td><td align="center">2199</td><td align="center">3875</td><td align="center">6274</td><td align="center">309</td><td align="center">603</td><td align="center">1160</td><td align="center">2716</td></tr><tr><td>Write via kcptun</td><td align="center">3730</td><td align="center">4967</td><td align="center">5395</td><td align="center">5948</td><td align="center">308</td><td align="center">596</td><td align="center">1145</td><td align="center">2613</td></tr></tbody></table><img src="/images/20220201_throughput_regression_with_kcptun.png"><p>From the benchmark result, we can see if the network has a fixed latency, kcptun doesn’t make any sense to improve throughput, even a little regression. On the other hand, if the latency of network is not stable, the larger latency jitter exists, the higher throughput improvement will be gained with  kcptun. Considering the network situation and the overhead of KCP encoding&#x2F;decoding, this strategy is not a silver bullet but can improve performance in part of scenarios.</p><h2 id="Advices-about-system-performance"><a href="#Advices-about-system-performance" class="headerlink" title="Advices about system performance"></a>Advices about system performance</h2><ul><li>The performance of a system should be estimated. It is important to abstract the architecture and estimate the performance indicators based on known knowledge.</li><li>If the estimation is beyond precocious, try to write a minimal demo to simulate the workload.</li><li>The deployment topology is worth thinking deeply before running the system in a production environment.</li><li>There always exist tradeoffs in software systems, we can add enough metrics to the system and tune the performance and resource usage dynamically.</li></ul><h2 id="Remaining-problems"><a href="#Remaining-problems" class="headerlink" title="Remaining problems"></a>Remaining problems</h2><p>There still exist many topics that have not been discussed in this article, such as</p><ul><li>In real word, when the performance of a network service drops or jitter happens because of network regression, is there any way to diagnose network conditions quickly or even find the problems before it affects the service and adopt some strategies to reduce the impact. For example<ul><li>In the gRPC scenario, is there any gRPC metric to show the flow control window size, message buffer size that can help to monitor the gRPC running status.</li><li>In the MySQL scenario, how to measure whether the bandwidth of client side and server side is busy or free.</li><li>In real world network regression is not a decline of a single indicator, it may be multifactor functioning and how to evaluate the network regression is a big topic. A related article: <a href="https://manjusaka.itscoder.com/posts/2022/01/31/a-simple-introduction-about-network-monitoring-in-linux-kernel/">network quality monitoring in Linux kernel</a>.</li></ul></li><li>This article only talks about the network regression affections to MySQL protocol and gRPC streaming(HTTP&#x2F;2 underlying), there are many commonly used protocols that have not been discussed, such as HTTP&#x2F;1.1, WebSocket etc.</li></ul><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li><a href="https://en.wikipedia.org/wiki/Bufferbloat">Wikipedia&#x2F;Bufferbloat</a></li><li><a href="https://grpc.io/blog/grpc-go-perf-improvements/">gRPC-Go performance Improvements</a></li><li><a href="https://docs.google.com/document/d/1Eq4eBEbNt1rc8EYuwqsduQd1ZfcBOCYt9HVSBa--m-E/pub">HTTP&#x2F;2 Receive Window Auto-Tuning</a></li><li><a href="https://ably.com/blog/grpc-stream-performance">The Mysterious Gotcha of gRPC Stream Performance</a></li><li><a href="https://manjusaka.itscoder.com/posts/2022/01/31/a-simple-introduction-about-network-monitoring-in-linux-kernel/">简单聊聊在 Linux 内核中的网络质量监控</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;In recent work my team devoted in a cross region data replication solution, a simplified abstraction of the workload is as follows&lt;/p&gt;
&lt;img src=&quot;/images/20220201_service_architecture.png&quot;&gt;

&lt;p&gt;The gRPC service and downstream MySQL are located in different AWS regions(such as one in EU, and the other one in US East), and the average network latency between these two regions is 70ms. We have a choice to deploy the data transfer service in either gRPC service side or downstream MySQL side. After a series of tests, we observed that deploying data transfer service in the downstream(the downstream MySQL) side has much larger throughput than deploying it in the upstream(the gRPC service) side. This article will analyze the root cause from both benchmark result and principle analysis, try to find potential solutions and give advice about such scenarios.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="performance" scheme="http://amyangfei.me/tags/performance/"/>
    
    <category term="TCP" scheme="http://amyangfei.me/tags/TCP/"/>
    
    <category term="network chaos" scheme="http://amyangfei.me/tags/network-chaos/"/>
    
  </entry>
  
  <entry>
    <title>Best practises for goroutine inspection in golang</title>
    <link href="http://amyangfei.me/2021/12/05/go-gorouinte-diagnose/"/>
    <id>http://amyangfei.me/2021/12/05/go-gorouinte-diagnose/</id>
    <published>2021-12-04T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>Go runtime provides a convenient way to dump stack traces of all current goroutines via <a href="https://pkg.go.dev/runtime/pprof#Profile">pprof</a>, which can save developers a lot time to diagnose the programming problems including deadlock, goroutine pause(such as IO wait, blocking chan receive etc.), goroutine leak. In a long running go process, there could be thousands of goroutines, it takes some time to find the susceptible stack trace from large amount of lines, this article concludes some common methods to discovery suspectable stack trace&#x2F;goroutine quickly.</p><span id="more"></span><h2 id="Group-the-goroutines"><a href="#Group-the-goroutines" class="headerlink" title="Group the goroutines"></a>Group the goroutines</h2><p>When dumping the goroutines via <code>/debug/pprof/goroutine?debug=1</code>, the goroutine information is grouped by stack trace signature, goroutines with the same stack trace are listed in a same group, such as following</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">3</span> @ <span class="number">0x43b705</span> <span class="number">0x46f298</span> <span class="number">0x46f26e</span> <span class="number">0x47c8b9</span> <span class="number">0xa428fd</span> <span class="number">0x473521</span></span><br><span class="line">#    <span class="number">0x46f26d</span>    sync.runtime_notifyListWait+<span class="number">0xcd</span>                                           runtime/sema.<span class="keyword">go</span>:<span class="number">513</span></span><br><span class="line">#    <span class="number">0x47c8b8</span>    sync.(*Cond).Wait+<span class="number">0x98</span>                                                     sync/cond.<span class="keyword">go</span>:<span class="number">56</span></span><br><span class="line">#    <span class="number">0xa428fc</span>    google.golang.org/grpc/internal/transport.(*http2Client).keepalive+<span class="number">0x35c</span>   google.golang.org/grpc@v1<span class="number">.40</span><span class="number">.0</span>/internal/transport/http2_client.<span class="keyword">go</span>:<span class="number">1373</span></span><br></pre></td></tr></table></figure><p>However the <code>debug=1</code> dump doesn’t contain some critical information, including the goroutine state, the parameter signature of each function call, as well as the goroutine ID. The <code>debut=2</code> mode will carry more information but the stack traces will be listed one by one. Given a sample <code>debug=2</code> mode <a href="https://github.com/amyangfei/amyangfei.github.com/files/7655479/goroutines.tar.gz">goroutine dump</a>, it contains 4724 goroutines. It is convenient to use <a href="https://github.com/linuxerwang/goroutine-inspect">goroutine-inspect</a> to analyze the goroutine dump, such as load the sample dump file, it will group the goroutines by state, as following:</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"># of goroutines: <span class="number">4724</span></span><br><span class="line"></span><br><span class="line">        IO wait: <span class="number">25</span></span><br><span class="line">   <span class="keyword">chan</span> receive: <span class="number">590</span></span><br><span class="line">       runnable: <span class="number">79</span></span><br><span class="line">        running: <span class="number">1</span></span><br><span class="line">         <span class="keyword">select</span>: <span class="number">3249</span></span><br><span class="line">     semacquire: <span class="number">711</span></span><br><span class="line"> sync.Cond.Wait: <span class="number">68</span></span><br><span class="line">        syscall: <span class="number">1</span></span><br></pre></td></tr></table></figure><p><a href="https://github.com/linuxerwang/goroutine-inspect">goroutine-inspect</a> provides many ways for goroutine analysis, such as using <code>dedup</code> to fold goroutines with the same stack trace, this group way works the same as <code>debug=1</code> in pprof. It also supports to query goroutines via <a href="https://github.com/Knetic/govaluate">govaluate expression evaluation</a>, the supported query patterns can be found in <a href="https://github.com/linuxerwang/goroutine-inspect#properties-of-a-goroutine-dump-item">Properties of a Goroutine Dump Item</a>.</p><h2 id="Understand-the-information-in-a-stack-trace"><a href="#Understand-the-information-in-a-stack-trace" class="headerlink" title="Understand the information in a stack trace"></a>Understand the information in a stack trace</h2><p>A stack trace contains not only the call stack of packages and functions, but also the function parameter signatures, including memory address, structure information(such as len or capacity, etc.). A more detailed analysis can be found in this article, <a href="https://www.ardanlabs.com/blog/2015/01/stack-traces-in-go.html">Stack Traces In Go</a>. Apart from the stack trace and parameter signature, goroutine state is the most important part to locate stuck issues, such as network IO blocking, channel receive blocking etc.</p><h2 id="Understand-the-goroutine-state"><a href="#Understand-the-goroutine-state" class="headerlink" title="Understand the goroutine state"></a>Understand the goroutine state</h2><p>As a matter of fact, the state listed in pprof goroutine dump combines the runtime G status and the waiting reason of blocking G. The G status is defined in <a href="https://github.com/golang/go/blob/go1.16.11/src/runtime/runtime2.go#L15-L86">go runtime with 9 states</a>, they are</p><ul><li><code>idle</code>: goroutine was just allocated and has not yet been initialized.</li><li><code>runnable</code>: goroutine is on a run queue. It is not currently executing user code. The stack is not owned.</li><li><code>running</code>: goroutine may execute user code. The stack is owned by this goroutine. It is not on a run queue. It is assigned an M and a P (g.m and g.m.p are valid).</li><li><code>syscall</code>: goroutine is executing a system call. It is not executing user code. The stack is owned by this goroutine. It is not on a run queue. It is assigned an M.</li><li><code>waiting</code>: goroutine is blocked in the runtime.</li><li><code>moribund_unused</code>: currently unused, but hardcoded in gdb scripts.</li><li><code>dead</code>: goroutine is currently unused. It may be just exited, on a free list, or just being initialized.</li><li><code>enqueue_unused</code>: currently unused.</li><li><code>copystack</code>: goroutine’s stack is being moved.</li><li><code>preempted</code>: goroutine stopped itself for a suspendG preemption.</li></ul><p>And the wait reasons are the reason a goroutine is in waiting status, which are defined in <a href="https://github.com/golang/go/blob/8faefcbfce6d2b2875ab74d81bb4e94b2e3adaf5/src/runtime/runtime2.go#L1014-L1042">go runtime</a> too. The most common patterns we can observe from goroutine dump are G status(including <code>runnable</code>, <code>running</code>, <code>syscall</code>) and many kinds of wait reasons, and wait reasons are often the key information to locate problems.</p><h3 id="Waiting-time"><a href="#Waiting-time" class="headerlink" title="Waiting time"></a>Waiting time</h3><p>When a goroutine is blocking for long time, the goroutine dump will have blocing duration record, as the first line <code>goroutine 1 [IO wait, 11 minutes]:</code> in following goroutine dump. This stack trace is triggered by a MySQL database ping operation via a TCP proxy, but adding a delay in the response from TCP proxy to program, which can be treated as a Network IO blocking case.</p><details class="note info no-icon"><summary><p>A network IO blocking goroutine dump</p></summary><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">goroutine <span class="number">1</span> [IO wait, <span class="number">11</span> minutes]:</span><br><span class="line">internal/poll.runtime_pollWait(<span class="number">0x261bfb8</span>, <span class="number">0x72</span>, <span class="number">0xffffffffffffffff</span>)</span><br><span class="line">        runtime/netpoll.<span class="keyword">go</span>:<span class="number">222</span> +<span class="number">0x55</span></span><br><span class="line">internal/poll.(*pollDesc).wait(<span class="number">0xc000148698</span>, <span class="number">0x72</span>, <span class="number">0x1000</span>, <span class="number">0x1000</span>, <span class="number">0xffffffffffffffff</span>)</span><br><span class="line">        internal/poll/fd_poll_runtime.<span class="keyword">go</span>:<span class="number">87</span> +<span class="number">0x45</span></span><br><span class="line">internal/poll.(*pollDesc).waitRead(...)</span><br><span class="line">        internal/poll/fd_poll_runtime.<span class="keyword">go</span>:<span class="number">92</span></span><br><span class="line">internal/poll.(*FD).Read(<span class="number">0xc000148680</span>, <span class="number">0xc000162000</span>, <span class="number">0x1000</span>, <span class="number">0x1000</span>, <span class="number">0x0</span>, <span class="number">0x0</span>, <span class="number">0x0</span>)</span><br><span class="line">        internal/poll/fd_unix.<span class="keyword">go</span>:<span class="number">166</span> +<span class="number">0x1d5</span></span><br><span class="line">net.(*netFD).Read(<span class="number">0xc000148680</span>, <span class="number">0xc000162000</span>, <span class="number">0x1000</span>, <span class="number">0x1000</span>, <span class="number">0x230b100</span>, <span class="number">0x20300000000000</span>, <span class="number">0x24fffff</span>)</span><br><span class="line">        net/fd_posix.<span class="keyword">go</span>:<span class="number">55</span> +<span class="number">0x4f</span></span><br><span class="line">net.(*conn).Read(<span class="number">0xc0000100a0</span>, <span class="number">0xc000162000</span>, <span class="number">0x1000</span>, <span class="number">0x1000</span>, <span class="number">0x0</span>, <span class="number">0x0</span>, <span class="number">0x0</span>)</span><br><span class="line">        net/net.<span class="keyword">go</span>:<span class="number">183</span> +<span class="number">0x91</span></span><br><span class="line">github.com/<span class="keyword">go</span>-sql-driver/mysql.(*buffer).fill(<span class="number">0xc0001126c0</span>, <span class="number">0x4</span>, <span class="number">0x2049f60</span>, <span class="number">0x2049f60</span>)</span><br><span class="line">        github.com/<span class="keyword">go</span>-sql-driver/mysql@v1<span class="number">.6</span><span class="number">.0</span>/buffer.<span class="keyword">go</span>:<span class="number">90</span> +<span class="number">0x142</span></span><br><span class="line">github.com/<span class="keyword">go</span>-sql-driver/mysql.(*buffer).readNext(<span class="number">0xc0001126c0</span>, <span class="number">0x4</span>, <span class="number">0x2049f60</span>, <span class="number">0x0</span>, <span class="number">0x203000</span>, <span class="number">0xc00010f830</span>, <span class="number">0x0</span>)</span><br><span class="line">        github.com/<span class="keyword">go</span>-sql-driver/mysql@v1<span class="number">.6</span><span class="number">.0</span>/buffer.<span class="keyword">go</span>:<span class="number">119</span> +<span class="number">0x9c</span></span><br><span class="line">github.com/<span class="keyword">go</span>-sql-driver/mysql.(*mysqlConn).readPacket(<span class="number">0xc0001126c0</span>, <span class="number">0x2049f60</span>, <span class="number">0xc00010f948</span>, <span class="number">0x100f09b</span>, <span class="number">0x2040108</span>, <span class="number">0x133bd59</span>)</span><br><span class="line">        github.com/<span class="keyword">go</span>-sql-driver/mysql@v1<span class="number">.6</span><span class="number">.0</span>/packets.<span class="keyword">go</span>:<span class="number">32</span> +<span class="number">0x91</span></span><br><span class="line">github.com/<span class="keyword">go</span>-sql-driver/mysql.(*mysqlConn).readHandshakePacket(<span class="number">0xc0001126c0</span>, <span class="number">0x1000</span>, <span class="number">0x1000</span>, <span class="number">0xc000162000</span>, <span class="number">0x0</span>, <span class="number">0x135d292</span>, <span class="number">0xf</span>, <span class="number">0x13b6d48</span>)</span><br><span class="line">        github.com/<span class="keyword">go</span>-sql-driver/mysql@v1<span class="number">.6</span><span class="number">.0</span>/packets.<span class="keyword">go</span>:<span class="number">188</span> +<span class="number">0x45</span></span><br><span class="line">github.com/<span class="keyword">go</span>-sql-driver/mysql.(*connector).Connect(<span class="number">0xc000010098</span>, <span class="number">0x13b51d0</span>, <span class="number">0xc00001a0c0</span>, <span class="number">0x0</span>, <span class="number">0x0</span>, <span class="number">0x0</span>, <span class="number">0x0</span>)</span><br><span class="line">        github.com/<span class="keyword">go</span>-sql-driver/mysql@v1<span class="number">.6</span><span class="number">.0</span>/connector.<span class="keyword">go</span>:<span class="number">81</span> +<span class="number">0x44b</span></span><br><span class="line">database/sql.(*DB).conn(<span class="number">0xc000079450</span>, <span class="number">0x13b51d0</span>, <span class="number">0xc00001a0c0</span>, <span class="number">0x13b2601</span>, <span class="number">0xc000010098</span>, <span class="number">0x0</span>, <span class="number">0x0</span>)</span><br><span class="line">        database/sql/sql.<span class="keyword">go</span>:<span class="number">1301</span> +<span class="number">0x184</span></span><br><span class="line">database/sql.(*DB).PingContext(<span class="number">0xc000079450</span>, <span class="number">0x13b51d0</span>, <span class="number">0xc00001a0c0</span>, <span class="number">0x2e</span>, <span class="number">0xc000079450</span>)</span><br><span class="line">        database/sql/sql.<span class="keyword">go</span>:<span class="number">799</span> +<span class="number">0x90</span></span><br><span class="line">database/sql.(*DB).Ping(...)</span><br><span class="line">        database/sql/sql.<span class="keyword">go</span>:<span class="number">817</span></span><br><span class="line">main.queryMySQL(<span class="number">0x0</span>, <span class="number">0x0</span>)</span><br><span class="line">        command-line-arguments/main.<span class="keyword">go</span>:<span class="number">20</span> +<span class="number">0xe9</span></span><br><span class="line">main.main()</span><br><span class="line">        command-line-arguments/main.<span class="keyword">go</span>:<span class="number">45</span> +<span class="number">0x3e</span></span><br></pre></td></tr></table></figure></details><p>But when using waiting time to diagnose blocking issues, we should pay attention to the blocking duration is not counted from the very beginning of the process. Given the following code snippet as an example and dump golang routines every one minute, we will find the waiting time will be observed after 4 minutes. Besides if the blocking code is terminated by some cancel mechanism such as <code>context.WithTimeout</code> and retried later in a new goroutine, the waiting duration won’t be accumulated, so it is not enough to detect blocking issues just relying on the waiting time. It is better to start with the goroutine state and be familiar with some common patterns.</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">        <span class="string">&quot;net/http&quot;</span></span><br><span class="line">        _ <span class="string">&quot;net/http/pprof&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">//go:noinline</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">sendBlock</span><span class="params">(ch <span class="keyword">chan</span>&lt;- <span class="type">bool</span>)</span></span> &#123;</span><br><span class="line">        ch &lt;- <span class="literal">true</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">                http.ListenAndServe(<span class="string">&quot;0.0.0.0:9200&quot;</span>, <span class="literal">nil</span>)</span><br><span class="line">        &#125;()</span><br><span class="line">        ch := <span class="built_in">make</span>(<span class="keyword">chan</span> <span class="type">bool</span>)</span><br><span class="line">        sendBlock(ch)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">➜ grep -E --with-filename <span class="string">&quot;goroutine [0-9]+ \[chan send&quot;</span> goroutines*</span><br><span class="line">goroutines.2021-12-05.18:59:32.log:goroutine 1 [chan send]:</span><br><span class="line">goroutines.2021-12-05.19:00:32.log:goroutine 1 [chan send]:</span><br><span class="line">goroutines.2021-12-05.19:01:32.log:goroutine 1 [chan send]:</span><br><span class="line">goroutines.2021-12-05.19:02:32.log:goroutine 1 [chan send]:</span><br><span class="line">goroutines.2021-12-05.19:03:32.log:goroutine 1 [chan send, 2 minutes]:</span><br><span class="line">goroutines.2021-12-05.19:04:32.log:goroutine 1 [chan send, 3 minutes]:</span><br><span class="line">goroutines.2021-12-05.19:05:32.log:goroutine 1 [chan send, 4 minutes]:</span><br><span class="line">goroutines.2021-12-05.19:06:32.log:goroutine 1 [chan send, 5 minutes]:</span><br></pre></td></tr></table></figure><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">goroutine <span class="number">1</span> [<span class="keyword">chan</span> send, <span class="number">11</span> minutes]:</span><br><span class="line">main.sendBlock(<span class="number">0xc000110240</span>)</span><br><span class="line">        command-line-arguments/select_on_chan_block.<span class="keyword">go</span>:<span class="number">10</span> +<span class="number">0x37</span></span><br><span class="line">main.main()</span><br><span class="line">        command-line-arguments/select_on_chan_block.<span class="keyword">go</span>:<span class="number">18</span> +<span class="number">0x5c</span></span><br></pre></td></tr></table></figure><h2 id="Common-patterns-for-diagnosing"><a href="#Common-patterns-for-diagnosing" class="headerlink" title="Common patterns for diagnosing"></a>Common patterns for diagnosing</h2><p>To be added.</p><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li><a href="https://pkg.go.dev/runtime/pprof#Profile">golang official docs about pprof</a></li><li><a href="https://github.com/linuxerwang/goroutine-inspect">goroutine-inspect, an interactive tool to analyze Golang goroutine dump</a></li><li><a href="https://www.ardanlabs.com/blog/2015/01/stack-traces-in-go.html">Stack Traces In Go, talking about information the stack trace provides, including how to identify the value for each parameter that was passed into each function</a></li><li><a href="https://github.com/DataDog/go-profiler-notes">go-profiler-notes, summarize of go profiler</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;Go runtime provides a convenient way to dump stack traces of all current goroutines via &lt;a href=&quot;https://pkg.go.dev/runtime/pprof#Profile&quot;&gt;pprof&lt;/a&gt;, which can save developers a lot time to diagnose the programming problems including deadlock, goroutine pause(such as IO wait, blocking chan receive etc.), goroutine leak. In a long running go process, there could be thousands of goroutines, it takes some time to find the susceptible stack trace from large amount of lines, this article concludes some common methods to discovery suspectable stack trace&amp;#x2F;goroutine quickly.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="system diagnose" scheme="http://amyangfei.me/tags/system-diagnose/"/>
    
    <category term="goroutine" scheme="http://amyangfei.me/tags/goroutine/"/>
    
  </entry>
  
  <entry>
    <title>Memory models notes</title>
    <link href="http://amyangfei.me/2021/10/07/memory-models/"/>
    <id>http://amyangfei.me/2021/10/07/memory-models/</id>
    <published>2021-10-06T16:00:00.000Z</published>
    <updated>2022-03-26T11:43:57.637Z</updated>
    
    <content type="html"><![CDATA[<p>I have read the <a href="https://research.swtch.com/mm">three articles about memory models</a> by Russ Cox in the last week, the following mind mapping summaries the core concepts of memory models.</p><span id="more"></span><h2 id="Mind"><a href="#Mind" class="headerlink" title="Mind"></a>Mind</h2><p><img src="/images/20211007_memory_models.png" alt="mind of memory models"></p><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li>Memory models posts<ul><li><a href="https://research.swtch.com/hwmm">Hardware Memory Models</a></li><li><a href="https://research.swtch.com/plmm">Programming Language Memory Models</a></li><li><a href="https://research.swtch.com/gomm">Updating the Go Memory Model</a></li></ul></li><li><a href="https://github.com/golang/go/discussions/47141">Updating the Go memory model(golang discussion)</a></li><li><a href="https://golang.org/ref/mem">The Go Memory Model</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;I have read the &lt;a href=&quot;https://research.swtch.com/mm&quot;&gt;three articles about memory models&lt;/a&gt; by Russ Cox in the last week, the following mind mapping summaries the core concepts of memory models.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="memory models" scheme="http://amyangfei.me/tags/memory-models/"/>
    
    <category term="concurrent programming" scheme="http://amyangfei.me/tags/concurrent-programming/"/>
    
  </entry>
  
  <entry>
    <title>Latency numbers of different golang operations</title>
    <link href="http://amyangfei.me/2021/05/03/golang-operation-latency/"/>
    <id>http://amyangfei.me/2021/05/03/golang-operation-latency/</id>
    <published>2021-05-02T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>Latency is one of the most important metrics in system performance, different systems have various latency requirements, such as the read latency of a relation database maybe less than 50ms, the GC latency of a programming language should be less than 10ms or 1ms, while the latency requirement of two micro services under the same data center could be less than 0.2ms. It is not always latency sensitive in every single part of a system, but as a matter of fact there do exist many components that are latency sensitive and we must be very careful when we design and implement these components or systems.</p><p>A lot of articles have talked about system latency, from both the high level, macroscopic perspective, such as the latency of a complex architecture; the latency from systemic interaction such as http API invocation, database read and write, cache access; the latency of operation in programming language such as memory allocation or function call. And the low level, or the underlying system, such as the latency in memory access, IO access, TCP packet transmit, etc. The following latency table is from book <a href="https://www.amazon.com/Systems-Performance-Enterprise-Brendan-Gregg/dp/0133390098">Systems Performance</a>, and the project <a href="https://github.com/sirupsen/napkin-math#numbers">napking-math</a> also provides a table about latency numbers.</p><span id="more"></span><p><img src="/images/20210513_system_latencies.png" alt="Time scale of system latencies"></p><p>In this article I will focus on the latency in Golang programming language, including API in some golang libraries; golang specific feature such as goroutine create and destroy, channel access; golang runtime latency such as GC latency etc.</p><h2 id="The-latency-numbers-table"><a href="#The-latency-numbers-table" class="headerlink" title="The latency numbers table"></a>The latency numbers table</h2><table><thead><tr><th>Operation type</th><th>Golang latency</th><th>Benchmark environment</th><th>Benchmark source</th></tr></thead><tbody><tr><td>Empty function call</td><td>0.4 ns</td><td>Based on concurrent count and cpu count, benchmark run with cpu Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz, go version 1.16.3</td><td>A pure go empty function call</td></tr><tr><td>RWMutex RLock + RUlock</td><td>15-40 ns</td><td>Based on concurrent count and cpu count, benchmark run with cpu Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz, go version 1.16.3</td><td>ref: <a href="https://github.com/golang/go/issues/17973">go issue, RWMutex scales poorly with CPU count</a></td></tr><tr><td>Cgo function call</td><td>70 ns</td><td>Benchmark run with cpu Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz, go version 1.16.3</td><td>ref: <a href="https://github.com/changkun/cgo-benchmarks">cgo benchmarks</a></td></tr><tr><td>Select on a channel</td><td>10-100 ns (case1)<br>100-700 ns (case2)</td><td>Based on the lock contention in <code>runtime.sellock</code> and <code>runtime.selunlock</code>, benchmark run with cpu Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz, go version 1.16.3</td><td>ref: <a href="https://github.com/golang/go/issues/20351">go issue runtime: select on a shared channel is slow with many Ps</a><br>case1: private channel<br>case2: shared channel</td></tr><tr><td>Thread-safe buffer to simulate a channel</td><td>100 ns (case1)<br>400-500 ns (case2)<br>400-500 ns (case3)</td><td>Benchmark run with cpu Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz, go version 1.16.3</td><td>ref: <a href="https://syslog.ravelin.com/so-just-how-fast-are-channels-anyway-4c156a407e45">So just how fast are channels anyway</a><br>case1: single writer and reader<br>case2: single writer, multiple readers<br>case3: multiple writer and readers</td></tr><tr><td>Create a goroutine and call WaitGroup done once</td><td>300-800 ns</td><td>Benchmark run with cpu Intel(R) Xeon(R) CPU E5-2630 v3 @ 2.40GHz, go version 1.16.3</td><td>ref: <a href="https://gist.github.com/amyangfei/7318dc0d3c6a59c9a3c1a185c153d024">benchmark code</a></td></tr><tr><td>Golang grpc: unary secure ping pong</td><td>200-300 us</td><td>8-core systems on GCE, gRPC official benchmark</td><td>netperf: 70-80us <br>c++: 130-200us <br>ref: <a href="https://performance-dot-grpc-testing.appspot.com/explore?dashboard=5652536396611584">grpc testing dashboard</a> and <a href="https://grpc.io/docs/guides/benchmarking/">grpc benchmarking</a></td></tr><tr><td>Golang grpc: streaming secure ping pong</td><td>150-200 us</td><td>8-core systems on GCE, gRPC official benchmark</td><td>netperf: 70-80us<br>c++: 100-140us<br>ref: <a href="https://performance-dot-grpc-testing.appspot.com/explore?dashboard=5652536396611584">grpc testing dashboard</a> and <a href="https://grpc.io/docs/guides/benchmarking/">grpc benchmarking</a></td></tr><tr><td>Go 1.8-1.9, STW pauses per GC</td><td>&lt; 2*500 us</td><td>Golang official benchmark</td><td>ref: <a href="https://blog.golang.org/ismmkeynote">Getting to Go: The Journey of Go’s Garbage Collector</a></td></tr><tr><td>Go 1.7-1.8 GC</td><td>1.5 ms</td><td>Golang official benchmark</td><td>ref: <a href="https://blog.golang.org/ismmkeynote">Getting to Go: The Journey of Go’s Garbage Collector</a></td></tr><tr><td>Go 1.5 GC, STW pauses every 50ms</td><td>10 ms</td><td>Golang official benchmark</td><td>ref: <a href="https://blog.golang.org/go15gc">Go GC: Prioritizing low latency and simplicity</a></td></tr></tbody></table><style>table th:nth-of-type(1){width: 30%;}table th:nth-of-type(2){width: 20%;}table th:nth-of-type(3){width: 25%;}table th:nth-of-type(3){width: 25%;}</style><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>In the real world system could be far more complicated than the above cases, latency of the whole system is contributed by pieces of code&#x2F;logic, knowing the latency of each single part is not the silver bullet, but the foundation of performance tuning. Besides we can use some profile and trace tools to diagnose the system performance, such as the cpu profile and trace tools shipped in golang pprof. At last I will quote some advice about performance tuning given by Dave Cheney in the High Performance Go Workshop in a gopher conference.</p><blockquote><p>Start with the simplest possible code.</p><p>Measure. Profile your code to identify the bottlenecks, do not guess.</p><p>If performance is good, stop. You don’t need to optimise everything, only the hottest parts of your code.</p><p>As your application grows, or your traffic pattern evolves, the performance hot spots will change.</p><p>Don’t leave complex code that is not performance critical, rewrite it with simpler operations if the bottleneck moves elsewhere.</p><p>Always write the simplest code you can, the compiler is optimised for normal code.</p><p>Shorter code is faster code; Go is not C++, do not expect the compiler to unravel complicated abstractions.</p><p>Shorter code is smaller code; which is important for the CPU’s cache.</p><p>Pay very close attention to allocations, avoid unnecessary allocation where possible.</p></blockquote><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li><a href="https://syslog.ravelin.com/so-just-how-fast-are-channels-anyway-4c156a407e45">So just how fast are channels anyway</a></li><li><a href="https://grpc.io/docs/guides/benchmarking/">grpc benchmarking</a></li><li><a href="https://blog.golang.org/go15gc">Go GC: Prioritizing low latency and simplicity</a></li><li><a href="https://blog.golang.org/ismmkeynote">Getting to Go: The Journey of Go’s Garbage Collector</a></li><li><a href="https://dave.cheney.net/high-performance-go-workshop/gopherchina-2019.html">High Performance Go Workshop</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;Latency is one of the most important metrics in system performance, different systems have various latency requirements, such as the read latency of a relation database maybe less than 50ms, the GC latency of a programming language should be less than 10ms or 1ms, while the latency requirement of two micro services under the same data center could be less than 0.2ms. It is not always latency sensitive in every single part of a system, but as a matter of fact there do exist many components that are latency sensitive and we must be very careful when we design and implement these components or systems.&lt;/p&gt;
&lt;p&gt;A lot of articles have talked about system latency, from both the high level, macroscopic perspective, such as the latency of a complex architecture; the latency from systemic interaction such as http API invocation, database read and write, cache access; the latency of operation in programming language such as memory allocation or function call. And the low level, or the underlying system, such as the latency in memory access, IO access, TCP packet transmit, etc. The following latency table is from book &lt;a href=&quot;https://www.amazon.com/Systems-Performance-Enterprise-Brendan-Gregg/dp/0133390098&quot;&gt;Systems Performance&lt;/a&gt;, and the project &lt;a href=&quot;https://github.com/sirupsen/napkin-math#numbers&quot;&gt;napking-math&lt;/a&gt; also provides a table about latency numbers.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="performance" scheme="http://amyangfei.me/tags/performance/"/>
    
    <category term="system latency" scheme="http://amyangfei.me/tags/system-latency/"/>
    
  </entry>
  
  <entry>
    <title>Dive into usage with proxy</title>
    <link href="http://amyangfei.me/2021/03/07/dive-into-proxy-usage/"/>
    <id>http://amyangfei.me/2021/03/07/dive-into-proxy-usage/</id>
    <published>2021-03-06T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>Recently I met a <code>context deadline exceeded</code> error when using gRPC client to call <code>DialContext</code> to a gRPC server, which was in a customer’s internal environment. After some investigation I found out the root cause, the gRPC client was behind an HTTP proxy and the proxy has no permission to access the gRPC server. It is a common trouble shooting, however I am interested in how we can force a program to use http or socks proxy, I will dive into it and compare the pros and cons among different solutions.</p><h2 id="Ways-to-enable-a-proxy"><a href="#Ways-to-enable-a-proxy" class="headerlink" title="Ways to enable a proxy"></a>Ways to enable a proxy</h2><p>There exist many ways to let an application use a proxy, these ways can be classified into three types as follows, and I will talk about these methods briefly.</p><ul><li>Explicit environment variable to active transport feature which is builtin in the application.</li><li>Use a hook method to hijack network calls from the application, without changing the program code.</li><li>Use a network packet hijacking way such as the kernel netfilter module to inspect and modify network packets.</li></ul><span id="more"></span><h3 id="Configure-proxy-via-environment-variables"><a href="#Configure-proxy-via-environment-variables" class="headerlink" title="Configure proxy via environment variables"></a>Configure proxy via environment variables</h3><p>Setting environment variable <code>http_proxy</code> or <code>https_proxy</code> may be the most common way to configure a proxy in Linux, however we must notice this is not a global proxy configuration on Linux, whether these two variables can enable proxy for an application depends on the application itself, which means only the application reads the environment variable and uses it explicitly as transport can make proxy available. Taking the implementation of go command line tool (go 1.16) as an example, the <code>impatientInsecureHTTPClient</code> (which is used in command line tool such as <code>go get</code>) always <a href="https://github.com/golang/go/blob/f21be2fdc6f1becdbed1592ea0b245cdeedc5ac8/src/cmd/go/internal/web/http.go#L36">initializes a <code>Proxy</code> field</a> by <code>http.ProxyFromEnvironment</code>, which is provided in <a href="https://github.com/golang/go/blob/f21be2fdc6f1becdbed1592ea0b245cdeedc5ac8/src/net/http/transport.go#L421-L439">net&#x2F;http&#x2F;transport.go</a>, if <code>http_proxy</code> or <code>https_proxy</code> is provided in environment variable, then the proxy will take effect. However, not all applications use these two env variables, such as golang standard http client doesn’t consider these two env variables by default.</p><h3 id="Hook-libc-functions-in-dynamically-linked-program"><a href="#Hook-libc-functions-in-dynamically-linked-program" class="headerlink" title="Hook libc functions in dynamically linked program"></a>Hook libc functions in dynamically linked program</h3><p>Comparing with the env variables way which is limited to some programs, there exist some tools that can perform TCP redirection for more general applications, such as <a href="https://linux.die.net/man/8/tsocks">tsocks</a> and <a href="https://github.com/rofl0r/proxychains-ng">proxychains-ng</a>. Since the tsocks is not active now, I will talk about proxychains-ng mainly. Proxychains-ng is a UNIX program that hooks network-related libc functions in dynamically linked programs via a preloaded DLL (dlsym(), LD_PRELOAD) and redirects the connections through SOCKS4a&#x2F;5 or HTTP proxies. Proxychains-ng works well in many scenarios (Maybe the most widely usage scenario is as a ladder to climb the GFW, but it can actually be used in production environment to redirect necessary network traffic, we did use it in some projects), but it has problem to work with a golang binary. When golang program is built with Golang Compiler (instead of the <a href="https://golang.org/doc/install/gccgo">GCCGO</a>), the binary uses the syscall wrappers of golang itself and static linking is used. So the LD_PRELOAD way for shared library way doesn’t work with golang binary. There are some articles to discuss this topic, such as <a href="https://github.com/rofl0r/proxychains-ng/issues/199">proxychains-ng&#x2F;issues&#x2F;199</a> and <a href="https://void-shana.moe/linux/proxychains-ng.html">proxychains-ng principle analytic</a>.</p><h3 id="Use-ptrace-to-intercept-syscall"><a href="#Use-ptrace-to-intercept-syscall" class="headerlink" title="Use ptrace to intercept syscall"></a>Use ptrace to intercept syscall</h3><p>In this part I will talk about <a href="https://github.com/hmgle/graftcp">graftcp</a>, which can redirect the TCP connection made by any program [application, script, shell, etc.] to a SOCKS5 or HTTP proxy, no matter whether the target program is a dynamic executable or not. The principle of this tool is detailed described <a href="https://github.com/hmgle/graftcp#how-does-it-work">here</a>, the core principle is to trace and modify the given program’s <a href="https://man7.org/linux/man-pages/man2/connect.2.html">connect(2)</a> by <a href="https://man7.org/linux/man-pages/man2/ptrace.2.html">ptrace(2)</a>. The idea of this tool is amazing and it works very well under the Linux platform. However I have some concern with this method to use proxy, since it introduces the overhead of ptrace and one more network traffic between <code>graftcp</code> and <code>graftcp-local</code> server, whether the program&#x2F;application performance will decrease needs to be taken into consideration.</p><h3 id="Global-proxy-via-underlying-network-packets-inspect-and-modify"><a href="#Global-proxy-via-underlying-network-packets-inspect-and-modify" class="headerlink" title="Global proxy via underlying network packets inspect and modify"></a>Global proxy via underlying network packets inspect and modify</h3><p>This method often uses system firewall such as iptables to redirect specific network traffic to a transparent proxy, which will then uses HTTP or SOCKS proxy. One popular solution is to combine iptables and <a href="https://github.com/darkk/redsocks">redsocks</a>. Many articles have described how to deploy with redsocks. such as <a href="https://blog.lilydjwg.me/tag/redsocks">Linux global http proxy strategy</a>, <a href="https://medium.datadriveninvestor.com/how-to-transparently-use-a-proxy-with-any-application-docker-using-iptables-and-redsocks-b8301ddc4e1e">How to transparently use a proxy with any application (Docker) using Iptables and RedSocks</a>. I also found an article that <a href="https://hev.cc/2813.html">combines iptables and cgroup to make a transparent proxy</a>.</p><h2 id="Performance-overhead"><a href="#Performance-overhead" class="headerlink" title="Performance overhead"></a>Performance overhead</h2><p>In this part I have a simple benchmark to measure the performance degradation when using proxy, it is a python3 code snippet, which sends HTTP1.1 GET request to a given URL, the given URL is served with an Nginx and returns a json response simply. Besides the http proxy is served by <a href="https://github.com/cyfdecyf/cow">cow</a>. The test code and benchmark result are as follows.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/python3</span></span><br><span class="line"><span class="keyword">from</span> urllib <span class="keyword">import</span> request</span><br><span class="line"></span><br><span class="line">N = <span class="number">1000</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">bench</span>():</span><br><span class="line">    url = <span class="string">&#x27;http://bench.test/&#x27;</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(N):</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            resp = request.urlopen(url).read()</span><br><span class="line">        <span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">            <span class="built_in">print</span>(e)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    bench()</span><br></pre></td></tr></table></figure><table><thead><tr><th>type</th><th>command</th><th>bench result</th><th>change N to 10000, bench result</th></tr></thead><tbody><tr><td>no proxy</td><td>time .&#x2F;py_read.py</td><td>0.25s user 0.18s system 84% cpu 0.503 total</td><td>2.65s user 1.36s system 72% cpu 5.505 total</td></tr><tr><td>env variable active</td><td>export http_proxy&#x3D;<a href="http://127.0.0.1:7777/">http://127.0.0.1:7777</a> &amp;&amp; time .&#x2F;py_read.py</td><td>0.45s user 0.23s system 56% cpu 1.192 total</td><td>3.48s user 2.12s system 44% cpu 12.613 total</td></tr><tr><td>hook DLL function</td><td>time proxychains -f proxychains4.conf -q .&#x2F;py_read.py</td><td>0.40s user 0.30s system 51% cpu 1.365 total</td><td>2.45s user 1.92s system 37% cpu 11.786 total</td></tr><tr><td>ptrace way</td><td>time .&#x2F;graftcp -n .&#x2F;py_read.py</td><td>0.67s user 1.51s system 0% cpu 8:42.22 total</td><td>not test</td></tr></tbody></table><p>From the benchmark above we can conclude the <code>environment variable active</code> way and <code>DLL hook</code> way have similar performance, the total execution time is increased by 2 times comparing to no proxy execution, which also means the throughput of network requests will decrease by half. On the other hand, the <code>ptrace</code> way has very poor performance, the throughput is only 2 requests&#x2F;s, and execution time increase is 1000 times. Considering this is a network request bound benchmark, I conduct another experiment to check whether there exists performance decreases when we use these ways with code logic that is not network request bound. In the following benchmark, the test code just opens a local file and write N strings into the file.</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/python3</span></span><br><span class="line"></span><br><span class="line">N = <span class="number">2000000</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    <span class="keyword">with</span> <span class="built_in">open</span>(<span class="string">&quot;test.log&quot;</span>, <span class="string">&quot;w&quot;</span>) <span class="keyword">as</span> writter:</span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(N):</span><br><span class="line">            writter.write(<span class="string">f&quot;<span class="subst">&#123;i*i&#125;</span>\n&quot;</span>)</span><br></pre></td></tr></table></figure><table><thead><tr><th>type</th><th>command</th><th>bench result</th></tr></thead><tbody><tr><td>no proxy</td><td>time .&#x2F;py_write.py</td><td>0.36s user 0.05s system 90% cpu 0.449 total</td></tr><tr><td>env variable</td><td>export http_proxy&#x3D;<a href="http://127.0.0.1:7777/">http://127.0.0.1:7777</a> &amp;&amp; time .&#x2F;py_write.py</td><td>0.38s user 0.03s system 90% cpu 0.453 total</td></tr><tr><td>proxychains</td><td>time proxychains -q .&#x2F;py_write.py</td><td>0.36s user 0.04s system 89% cpu 0.452 total</td></tr><tr><td>graftcp</td><td>time .&#x2F;graftcp -n .&#x2F;py_write.py</td><td>0.40s user 0.08s system 48% cpu 1.008 total</td></tr></tbody></table><p>The benchmark result shows both the <code>environment variable active</code> way and <code>DDL hook</code> way have no side effect to application performance when there is no network request. But the <code>ptrace</code> way still have performance overhead even there is no network request, which is reasonable, because of the overhead of ptrace.</p><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>There are many ways to use an HTTP or SOCKS proxy, but before we adopt a solution, we should not only consider whether the solution can work, but also think about more aspects, including the performance, stability and even usability. As for performance, the above benchmark can give a simple conclusion, but in the real world the usage scenario could be complex, the best way to decide which solution is the most appropriate is to test and benchmark with real workload and usage scenarios.</p><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li><a href="https://void-shana.moe/linux/proxychains-ng.html">PROXYCHAINS-NG principle analytic</a></li><li><a href="https://blog.lilydjwg.me/tag/redsocks">Linux global http proxy strategy</a></li><li><a href="https://medium.datadriveninvestor.com/how-to-transparently-use-a-proxy-with-any-application-docker-using-iptables-and-redsocks-b8301ddc4e1e">How to transparently use a proxy with any application (Docker) using Iptables and RedSocks</a></li><li><a href="https://hev.cc/2813.html">Transparent proxy per application on Linux</a></li><li><a href="https://github.com/rofl0r/proxychains-ng">proxychains-ng</a></li><li><a href="https://github.com/hmgle/graftcp">graftcp</a></li><li><a href="https://github.com/darkk/redsocks">redsocks</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;Recently I met a &lt;code&gt;context deadline exceeded&lt;/code&gt; error when using gRPC client to call &lt;code&gt;DialContext&lt;/code&gt; to a gRPC server, which was in a customer’s internal environment. After some investigation I found out the root cause, the gRPC client was behind an HTTP proxy and the proxy has no permission to access the gRPC server. It is a common trouble shooting, however I am interested in how we can force a program to use http or socks proxy, I will dive into it and compare the pros and cons among different solutions.&lt;/p&gt;
&lt;h2 id=&quot;Ways-to-enable-a-proxy&quot;&gt;&lt;a href=&quot;#Ways-to-enable-a-proxy&quot; class=&quot;headerlink&quot; title=&quot;Ways to enable a proxy&quot;&gt;&lt;/a&gt;Ways to enable a proxy&lt;/h2&gt;&lt;p&gt;There exist many ways to let an application use a proxy, these ways can be classified into three types as follows, and I will talk about these methods briefly.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Explicit environment variable to active transport feature which is builtin in the application.&lt;/li&gt;
&lt;li&gt;Use a hook method to hijack network calls from the application, without changing the program code.&lt;/li&gt;
&lt;li&gt;Use a network packet hijacking way such as the kernel netfilter module to inspect and modify network packets.&lt;/li&gt;
&lt;/ul&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="proxy" scheme="http://amyangfei.me/tags/proxy/"/>
    
    <category term="ptrace" scheme="http://amyangfei.me/tags/ptrace/"/>
    
  </entry>
  
  <entry>
    <title>Nil and zero value in Golang</title>
    <link href="http://amyangfei.me/2021/02/17/golang-nil-panic/"/>
    <id>http://amyangfei.me/2021/02/17/golang-nil-panic/</id>
    <published>2021-02-16T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>It is well known in golang that when allocating storage for a new variable and no explicit initialization is provided, the variable is given to a default value, either <strong>zero value</strong> for primitive types or <strong>nil</strong> for nullable types such as pointers, functions, maps etc. More details can be found in <a href="https://golang.org/ref/spec#The_zero_value">go sepc</a>. Some of the nullable types can cause panic when accessing them without initialization. Some examples are as follows.</p><span id="more"></span><p>Access a nil pointer</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p *<span class="type">int</span></span><br><span class="line">*p = <span class="number">2</span> <span class="comment">// panic: runtime error: invalid memory address or nil pointer dereference</span></span><br></pre></td></tr></table></figure><p>Assignment to entry in nil map</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> m <span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span></span><br><span class="line">m[<span class="string">&quot;foo&quot;</span>] = <span class="string">&quot;bar&quot;</span> <span class="comment">// panic: assignment to entry in nil map</span></span><br></pre></td></tr></table></figure><p>Access to a nil interface</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> p <span class="type">error</span></span><br><span class="line"><span class="type">error</span>.Error() <span class="comment">// panic: runtime error: invalid memory address or nil pointer dereference</span></span><br></pre></td></tr></table></figure><p>Golang developers have to pay attention to check whether a nullable structure has been initialized before using it. This has been discussed in many articles, such as <a href="https://bluxte.net/musings/2018/04/10/go-good-bad-ugly/#zero-values-that-panic">Go: the Good, the Bad and the Ugly</a> and <a href="https://nilsmagnus.github.io/post/nillability-in-go/">Nillability and zero-values in go</a>. Since this check is a lot of burden to developers, is there any way to check the potential risk, such as compile time check or static analysis tool.</p><h2 id="Try-to-check-nil-pointer-before-panic"><a href="#Try-to-check-nil-pointer-before-panic" class="headerlink" title="Try to check nil pointer before panic"></a>Try to check nil pointer before panic</h2><h3 id="Compiler-checkers"><a href="#Compiler-checkers" class="headerlink" title="Compiler checkers"></a>Compiler checkers</h3><p>In Go1 the compiler can’t detect nil pointer since it is legal to pass a <strong>nil</strong> variable when a pointer, interface, function or anything nullable types is needed. <a href="https://getstream.io/blog/fixing-the-billion-dollar-mistake-in-go-by-borrowing-from-rust/#solution">This article</a> proposes a solution to check nil pointer during compile time by borrowing a pointer type that can never be nil, which is like the idea used in Rust and C++. Code sample is as follows.</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> myNumber <span class="keyword">struct</span> &#123;</span><br><span class="line">    n <span class="type">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">TestNil</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> number *myNumber</span><br><span class="line">    plusOne(number) <span class="comment">// compile error: cannot use *myNumber as &amp;myNumber, *myNumber can be nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">TestPointer</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> number *myNumber = &amp;myNumber&#123;n: <span class="number">5</span>&#125;</span><br><span class="line">    plusOne(number) <span class="comment">// compile error: cannot use *myNumber as &amp;myNumber, *myNumber can be nil</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">TestNonNilablePointer</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> number &amp;myNumber = &amp;myNumber&#123;n: <span class="number">5</span>&#125;</span><br><span class="line">    plusOne(number)</span><br><span class="line">    fmt.Println(number.n) <span class="comment">// output: 6</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h3 id="Static-analysis-tools"><a href="#Static-analysis-tools" class="headerlink" title="Static analysis tools"></a>Static analysis tools</h3><p><a href="https://golangci-lint.run/">golangci-lint</a> is a Go linters aggregator, it includes many linters, some useful static analysis tools are also integrated, is it possible to find the nil pointer problem via it? Let’s run linters with the following code</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">        <span class="string">&quot;fmt&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">funcRecover</span><span class="params">(f <span class="type">string</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">if</span> err := <span class="built_in">recover</span>(); err != <span class="literal">nil</span> &#123;</span><br><span class="line">                fmt.Printf(<span class="string">&quot;func: %s, panic: %s\n&quot;</span>, f, err)</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test1</span><span class="params">(m1 <span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">defer</span> funcRecover(<span class="string">&quot;test1&quot;</span>)</span><br><span class="line">        m1[<span class="string">&quot;foo&quot;</span>] = <span class="string">&quot;bar&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test2</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">defer</span> funcRecover(<span class="string">&quot;test2&quot;</span>)</span><br><span class="line">        <span class="keyword">var</span> m2 <span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span></span><br><span class="line">        m2[<span class="string">&quot;foo&quot;</span>] = <span class="string">&quot;bar&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test3</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">defer</span> funcRecover(<span class="string">&quot;test3&quot;</span>)</span><br><span class="line">        <span class="keyword">var</span> err <span class="type">error</span></span><br><span class="line">        fmt.Println(err.Error())</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">test4</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">defer</span> funcRecover(<span class="string">&quot;test4&quot;</span>)</span><br><span class="line">        <span class="keyword">var</span> i *<span class="type">int</span></span><br><span class="line">        *i = <span class="number">12</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">var</span> m <span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span></span><br><span class="line">        test1(m)</span><br><span class="line">        test2()</span><br><span class="line">        test3()</span><br><span class="line">        test4()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>From the result of lint, we can see only one possible nil variable access is detected. What’s more, the <code>SA5000</code> detector is only concerned with local variables that don’t escape, global variables or function call with nil map access also doesn’t work. The static check logic can be found in <a href="https://github.com/dominikh/go-tools/blob/b9870cd46be0932ed7caa95b567e096c932f9a00/staticcheck/lint.go#L1916-L1936">source code of staticcheck tool</a>.</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">➜  ./golangci-lint-1.36.0-linux-amd64/golangci-lint run niltype.go</span><br><span class="line">niltype.go:21:2: SA5000: assignment to nil map (staticcheck)</span><br><span class="line">        m2[<span class="string">&quot;foo&quot;</span>] = <span class="string">&quot;bar&quot;</span></span><br><span class="line">        ^</span><br></pre></td></tr></table></figure><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">➜  go run niltype.go</span><br><span class="line">func: test1, panic: assignment to entry <span class="keyword">in</span> nil map</span><br><span class="line">func: test2, panic: assignment to entry <span class="keyword">in</span> nil map</span><br><span class="line">func: test3, panic: runtime error: invalid memory address or nil pointer dereference</span><br><span class="line">func: test4, panic: runtime error: invalid memory address or nil pointer dereference</span><br></pre></td></tr></table></figure><p>As far as I know there doesn’t exist a tool that can detect nil pointer risk with every single nullable type just by static analysis. The best way to avoid nil pointer panic is to check the nullable type is not nil before using it.</p><h2 id="Be-careful-when-checking-nil-interface"><a href="#Be-careful-when-checking-nil-interface" class="headerlink" title="Be careful when checking nil interface"></a>Be careful when checking nil interface</h2><p>Interface in Go contains both type and value, when checking whether nil with an interface, there are two cases</p><ol><li>Interface has nullable type(like pointer, map, etc) and value is nil</li><li>Interface itself has a nil type.</li></ol><p>Let’s use the following code as an example to explain the above two cases.</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">        <span class="string">&quot;fmt&quot;</span></span><br><span class="line">        <span class="string">&quot;reflect&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> MyError <span class="keyword">struct</span> &#123;</span><br><span class="line">        Err <span class="type">error</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="params">(me MyError)</span></span> Error() <span class="type">string</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> me.Err.Error()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">check</span><span class="params">(err <span class="type">error</span>)</span></span> &#123;</span><br><span class="line">        fmt.Printf(<span class="string">&quot;type: %v value: %v\n&quot;</span>, reflect.TypeOf(err), reflect.ValueOf(err))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">var</span> e *MyError</span><br><span class="line">        check(e)</span><br><span class="line">        check(<span class="literal">nil</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">➜  go run nil_check.go</span><br><span class="line"><span class="built_in">type</span>: *main.MyError value: &lt;nil&gt;</span><br><span class="line"><span class="built_in">type</span>: &lt;nil&gt; value: &lt;invalid reflect.Value&gt;</span><br></pre></td></tr></table></figure><ol><li>When passing a nil pointer of <code>MyError</code> to function <code>check</code>, the <code>err</code> contains type <code>*MyError</code> and nil value.</li><li>When passing a nil to function <code>check</code> directly, the <code>err</code> is a nil type itself.</li></ol><p>So when we check the <code>nil</code> of an interface passed from some other place, either returned by a function or passed in from the function parameter, we must be aware there exist two cases. If we don’t want to check whether it is a nil type or only nil value, we can put the check logic before golang type inference, in the above example, we can check whether it is a nil <code>*MyError</code> type before calling function <code>check</code>.</p><p>Besides, if we have to check the nil of an interface, the article <a href="https://mangatmodi.medium.com/go-check-nil-interface-the-right-way-d142776edef1">Go: Check Nil interface the right way</a> has a detailed introduction about it.</p><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>To summarize, in every case that we don’t want a nil structure, we must check it manually, there is no easy way to detect nil pointers automatically in golang, and we must be carefull when checking nil with an interface because ther interface could be nil type or not-nil type but nil value.</p><h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul><li><a href="https://golang.org/ref/spec#The_zero_value">Go sepc about zero value</a></li><li><a href="https://bluxte.net/musings/2018/04/10/go-good-bad-ugly/#zero-values-that-panic">Go: the Good, the Bad and the Ugly</a></li><li><a href="https://nilsmagnus.github.io/post/nillability-in-go/">Nillability and zero-values in go</a></li><li><a href="https://getstream.io/blog/fixing-the-billion-dollar-mistake-in-go-by-borrowing-from-rust/#solution">Fixing the billion dollar mistake in Go by borrowing from Rust</a></li><li><a href="https://mangatmodi.medium.com/go-check-nil-interface-the-right-way-d142776edef1">Go: Check Nil interface the right way</a></li></ul>]]></content>
    
    
    <summary type="html">&lt;p&gt;It is well known in golang that when allocating storage for a new variable and no explicit initialization is provided, the variable is given to a default value, either &lt;strong&gt;zero value&lt;/strong&gt; for primitive types or &lt;strong&gt;nil&lt;/strong&gt; for nullable types such as pointers, functions, maps etc. More details can be found in &lt;a href=&quot;https://golang.org/ref/spec#The_zero_value&quot;&gt;go sepc&lt;/a&gt;. Some of the nullable types can cause panic when accessing them without initialization. Some examples are as follows.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="static analysis" scheme="http://amyangfei.me/tags/static-analysis/"/>
    
  </entry>
  
  <entry>
    <title>Compare concepts described in Streaming Systems and real usage in a cdc project</title>
    <link href="http://amyangfei.me/2021/01/23/streaming-systems/"/>
    <id>http://amyangfei.me/2021/01/23/streaming-systems/</id>
    <published>2021-01-22T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>I have read the first part of book <a href="https://www.oreilly.com/library/view/streaming-systems/9781491983867/">Streaming Systems</a> recently and learned quite a lot of high level concepts and many useful tips about streaming systems. Many topics that this book discusses are very instructive to the <a href="https://github.com/pingcap/ticdc">TiCDC</a> project that I was focusing on in the past year, which is a change data capture system that supports to replicate change data from a distributed NewSQL database to various downstreams. In this article I will talk about some core concepts that a streaming system should pay attention to, comparing the opinion that the book Streaming Systems expresses, to some practical experience from the CDC project I participated.</p><h2 id="Concepts-in-change-data-capture-system"><a href="#Concepts-in-change-data-capture-system" class="headerlink" title="Concepts in change data capture system"></a>Concepts in change data capture system</h2><p>The book Stream Systems introduces many concepts to describe a streaming system from different dimensions. I will map these concepts to the change data capture system roughly.</p><span id="more"></span><h3 id="Event-time-versus-processing-time"><a href="#Event-time-versus-processing-time" class="headerlink" title="Event time versus processing time"></a>Event time versus processing time</h3><blockquote><p>Event time is time at which events actually occurred and processing time is the time at which events are observed in the system.</p></blockquote><p>In the real world, the skew between these two values always exists, and may be affected by various characteristics. Which one will be used when system processes with the event is highly related with the use scenario. As for the CDC of TiDB, we can use both the <code>start-ts</code> or <code>commit-ts</code> of a row change as event time, where <code>start-ts</code> and <code>commit-ts</code> can be treated as the prewrite and commit timestamp roughly (In fact in TiDB there exists a strict 2PC theory, and we can simplify the model that each transaction has a unique, incremental global logic timestamp, in TiDB it is called timestamp oracle, TSO for short). In TiCDC <code>start-ts</code> of a row change is used for data processing, with the help of event time, we can easily restore the row changed sequence in upstream, which can meet the requirement of consistent replication.</p><h3 id="Windowing"><a href="#Windowing" class="headerlink" title="Windowing"></a>Windowing</h3><blockquote><p>Windowing is the notion of taking a data source (either unbounded or bounded), and chopping it up along temporal boundaries into finite chunks for processing.</p></blockquote><p>Window is a common approach used to cope with unbounded data, in my opinion it can be a logic concept that tries to split data into determinate boundaries. The way how a streaming system cuts data into windows leads to different data processing strategies. In TiCDC, window is more like an adaptive size window, where the size is determined by the watermark and trigger.</p><h3 id="Triggers"><a href="#Triggers" class="headerlink" title="Triggers"></a>Triggers</h3><blockquote><p>A trigger is a mechanism for declaring when the output for a window should be materialized relative to some external signal.</p></blockquote><p>The streaming system can contain multiple components and forms a data flow chain, each component has an upstream and a downstream. Here materialized means output to the downstream of the current component. Trigger is the decision maker of when to output for a window, the choice of trigger will affect the processing quality in many aspects, including latency, correctness, throughput etc. In real world, streaming data is not stable all the time, there could exist late data, traffic peak, data re-delivery, data source panic and recovery etc. All these abnormal conditions should be taken into consideration when we design a proper trigger mechanism. In TiCDC, the trigger mechanism is highly relying on the watermark, which is a perfect watermark that can ensure a window closed. Since the transaction sequence in the upstream must be kept in TiCDC (which will enable sink or downstream consumer to recover transaction and keep data consistent), TiCDC adopts the same mechanism used in <a href="https://www.cockroachlabs.com/blog/change-data-capture/">CockroachDB CDC</a>, which is also the theory from paper <a href="https://www.microsoft.com/en-us/research/publication/naiad-a-timely-dataflow-system-2/">Naiad: A Timely Dataflow System</a>. The core idea of this mechanism is the trigger in each component can’t materialize data that is later than the perfect watermark to downstream, in another word, in order to output data best effort, the trigger should materialize all data before the perfect watermark.</p><h3 id="Watermarks"><a href="#Watermarks" class="headerlink" title="Watermarks"></a>Watermarks</h3><blockquote><p>Watermarks are temporal notions of input completeness in the event-time domain. Worded differently, they are the way the system measures progress and completeness relative to the event times of the records being processed in a stream of events. Depending upon the type of watermark, perfect or heuristic, that assertion may be a strict guarantee or an educated guess, respectively.</p></blockquote><p>How to choose a suitable watermark is decided by the usage scenario, which is also a tradeoff between performance and correctness as well as scalability and availability. Supposing we have a system that requires low latency of streaming data subscription, can tolerate with late data (data out of the scope of a closed window, tolerate means the system can ignore the late data or has method to amend correctness with late data), then a heuristic watermark is better than a perfect watermark. In another situation, if a system requires to keep the event sequence strictly, such as a database replication system must keep transaction serializable when replicating to downstream (Transaction isolation is a complicated topic in database system, here serializable is not the same thing as the serializable isolation level, but means the transaction applied sequence in downstream is the same as the event time sequence in upstream. Yet this serializable could be strict or loose, such as table level serializable or transaction level serializable), then the heuristic watermark could lead to inconsistent state between upstream and downstream, if this inconsistency is not acceptable, perfect watermark is a better choice than heuristic watermark.</p><h3 id="Accumulation"><a href="#Accumulation" class="headerlink" title="Accumulation"></a>Accumulation</h3><blockquote><p>An accumulation mode specifies the relationship between multiple results that are observed for the same window. There exists multiple ways to refine or relate results, including discarding, accumulating or accumulating and retracting.</p></blockquote><p>Different accumulations have different semantics, and will output different results with the same window&#x2F;watermark strategy. However in CDC no specific accumulation is used, since the row changed event in CDC is atomistic, the only existing results relate maybe transaction oriented events grouping, which means events in the same window can be grouped by transaction identification(events with the same start-ts will be treated in a same transaction).</p><h2 id="Tradeoffs-in-streaming-systems"><a href="#Tradeoffs-in-streaming-systems" class="headerlink" title="Tradeoffs in streaming systems"></a>Tradeoffs in streaming systems</h2><p>In this part I will focus on some key indicators in streaming systems and how to make a good tradeoff among these indicators.</p><h3 id="Latency-and-precision"><a href="#Latency-and-precision" class="headerlink" title="Latency and precision"></a>Latency and precision</h3><p>In theory, the strategy with watermark has a direct impact on latency. Besides the stages of data flow and how watermarks propagating is implemented also have a big impact on latency. As for precision, it is mostly decided by watermark mechanism.</p><p>As discussed in part one, perfect watermark can ensure a 100% precision of results materializing, well perfect watermark is impractical for many real world distributed input sources. However in some known scenarios, it is possible to define a perfect watermark, such as</p><ul><li>Distributed system with a single, monotonically increasing timestamp allocator (The <a href="https://en.pingcap.com/blog/Time-in-Distributed-Systems">TSO in TiDB</a> and <a href="https://www.cockroachlabs.com/docs/stable/architecture/transaction-layer.html">HLC in CockroachDB</a> are all this mechanism)</li><li>A statically sized input source of time-ordered input, such as Apache Kafka topic with a static set of partitions, each partition of source can be consumed with monotonically increasing event time.</li></ul><p>If a streaming system adopts the above-mentioned perfect watermark, the latency is determined by the latency of input source. Supposing there exist N nodes in input source, and the logical timestamp forwards to T, the streaming system must wait for each of the N nodes has sent event equal or greater than T. Based on this point, if the upstream input source suffers an accident, saying partial of N nodes crash and restart, the events of these fault nodes will be delayed and latency in streaming system will be increased remarkably until the upstream recover. In the real world most upstreams have some rebalance strategies when disaster happens, the data flow of down nodes will be transferred to normal nodes to decrease the recovery time, which is also known as RTO in distributed systems. To decrease latency as far as possible, the streaming system must be awareness to upstream fault recovery or rebalance, however the latency lag won’t be less than the RTO in upstream.</p><p>In real world most streaming systems contain multiple stages, watermarks are propagated across each independent stage. As for each stage, it has an input watermark and an output watermark, the output watermark is later than input watermark and the latency is contributed by the processing time of this stage. So it is obvious that the more stages in a pipeline, the more latency will be gained. As for each stage, the processing is not always monotonic because we can segment the processing within one stage into a flow with several conceptual components, each of which contributes to the output watermark. This is a common optimization, which aims to decrease processing time by dividing jobs into parallel sub jobs.</p><h3 id="Latency-and-throughput"><a href="#Latency-and-throughput" class="headerlink" title="Latency and throughput"></a>Latency and throughput</h3><p>Latency and throughput sometimes look like two incompatible things, however high throughput as well as low latency are often declared to be features that are provided by many streaming systems. So what is the real situation? To clarify this complicated problem, we must have a clear definition of latency and throughput, and have a knowledge about how these metrics affect the performance a streaming system. The paper <a href="https://ieeexplore.ieee.org/document/8509390">Benchmarking Distributed Stream Data Processing Systems</a> which is published in 2018 ICDE has a good explanation about key indicators of distributed streaming systems, it has two types for both latency and throughput, event-time latency, processing-time latency, maximum throughput and sustainable throughput respectively, the finer granularity of latency measure, the better observability can gain of a system, which also makes it easier for message tracking and stuckness diagnosis. In fact both latency and throughput are in the performance scope, whether they interact each other has many factors, a good designed streaming system should be able to achieve a liner sustainable throughput along with extensible processing nodes, provide a reasonable latency for data processing and materializing, and what’s more, the throughput and latency can be tuned (such as increasing throughput with acceptable latency increasing, or decreasing acceptable throughput to reduce latency) based on the requirement.</p><h3 id="Performance-and-delivery-guarantee"><a href="#Performance-and-delivery-guarantee" class="headerlink" title="Performance and delivery guarantee"></a>Performance and delivery guarantee</h3><p>Guaranteeing fault-tolerant and performant stream processing is hard because most streaming processing is stateful (which means it is expensive to replay from some old points) and distributed (which means node failure happens a lot). Due to the complexity of the problem, there are many approaches to fault tolerance in the open source ecosystem. Such as the following strategies used by open source projects compared in <a href="https://www.ververica.com/blog/high-throughput-low-latency-and-exactly-once-stream-processing-with-apache-flink">this article</a>.</p><ul><li>Record acknowledgements (Apache Storm)</li><li>Micro batching used (Apache Storm Trident, Apache Spark Streaming)</li><li>Transactional updates (Google Cloud Dataflow)</li><li>Distributed Snapshots (Apache Flink)</li></ul><p>In the real implementation of TiCDC, we choose at least once delivery strategy, for two reasons</p><ul><li>Sink is robust in the face of replay: For the sink type of message queue, TiCDC can output a perfect watermark, in each sized window with watermark, data integrity is guaranteed even redundant data exists; For the sink type of relation database, TiCDC can output idempotent SQL statements event data is re-delivery.</li><li>We adopt a checkpoint mechanism in sink, which means sink maintains a global output watermark and saves it into persistent storage periodically, with the checkpoint we can replay whenever error happens, which makes the system fault tolerable and fast recoverable.</li></ul><p>Combining with the checkpoint mechanism, the system can achieve better performance, since the loose of delivery guarantee makes it easy to use batch mechanism and fast delivery strategy.</p><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>To design a general streaming system is tough stuff, mostly because the workflow and data processing pattern can be various and complex. And in many scenarios, a general streaming system may not work better than a customized system, how to choose an appropriate framework is always controversial in software engineering. This article just has a limited view of streaming systems, the evolution of streaming architectures never stops, what we should do is to keep learning, thinking and practising.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;I have read the first part of book &lt;a href=&quot;https://www.oreilly.com/library/view/streaming-systems/9781491983867/&quot;&gt;Streaming Systems&lt;/a&gt; recently and learned quite a lot of high level concepts and many useful tips about streaming systems. Many topics that this book discusses are very instructive to the &lt;a href=&quot;https://github.com/pingcap/ticdc&quot;&gt;TiCDC&lt;/a&gt; project that I was focusing on in the past year, which is a change data capture system that supports to replicate change data from a distributed NewSQL database to various downstreams. In this article I will talk about some core concepts that a streaming system should pay attention to, comparing the opinion that the book Streaming Systems expresses, to some practical experience from the CDC project I participated.&lt;/p&gt;
&lt;h2 id=&quot;Concepts-in-change-data-capture-system&quot;&gt;&lt;a href=&quot;#Concepts-in-change-data-capture-system&quot; class=&quot;headerlink&quot; title=&quot;Concepts in change data capture system&quot;&gt;&lt;/a&gt;Concepts in change data capture system&lt;/h2&gt;&lt;p&gt;The book Stream Systems introduces many concepts to describe a streaming system from different dimensions. I will map these concepts to the change data capture system roughly.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="streaming system" scheme="http://amyangfei.me/tags/streaming-system/"/>
    
    <category term="change data capture" scheme="http://amyangfei.me/tags/change-data-capture/"/>
    
    <category term="book reading notes" scheme="http://amyangfei.me/tags/book-reading-notes/"/>
    
  </entry>
  
  <entry>
    <title>Thinking about etcd lease</title>
    <link href="http://amyangfei.me/2020/12/27/thinking-about-etcd-lease/"/>
    <id>http://amyangfei.me/2020/12/27/thinking-about-etcd-lease/</id>
    <published>2020-12-26T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>This article will first talk about a wrong use case with etcd lease, and then based on that case, I will dig into the design principle of etcd lease and some use scenario with etcd lease.</p><h2 id="A-wrong-use-case-with-etcd-lease"><a href="#A-wrong-use-case-with-etcd-lease" class="headerlink" title="A wrong use case with etcd lease"></a>A wrong use case with etcd lease</h2><p>There exist two roles in the following scenario, one is client and the other one is coordinator. More than one clients could exist at the same time. Each of them has an unique ID, and when a new client starts it applies a new lease from etcd and puts a key corresponding to the client ID with lease as option. The client must call <code>KeepAlive</code> of its lease periodically to keep lease not timeout. Once the lease is timeout and deleted by etcd server, the client becomes illegal and should not access the etcd resource anymore. The coordinator monits the client ID key, when a new client registers, it allocates new resource&#x2F;task to this client, which can be represented by a client ID relevant key value. And when it detects client ID key deleted (which means the client lease timeout), it will recycle the allocated resource of this client.</p><p>Here we use a etcd session to maintain client lease and lease keepalive, a simple work model of client is as follows</p><span id="more"></span><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">session, err := concurrency.NewSession(etcdCli, concurrency.WithTTL(<span class="number">10</span>))</span><br><span class="line"><span class="keyword">for</span> &#123;</span><br><span class="line">    <span class="keyword">select</span> &#123;</span><br><span class="line">    <span class="keyword">case</span> &lt;-session.Done():</span><br><span class="line">        <span class="comment">// lease is timeout, client exits</span></span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">case</span> ev := &lt;-etcdCli.Watch(ctx, resourceKey):</span><br><span class="line">        <span class="comment">// process resource update, mainly some etcd key value operations</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>In the above code, <code>session.Done</code> is used for lease aliveness check. However this is not a strict aliveness protection for resource access for two reasons.</p><ol><li><p>After client receives a new update from watch chan, during the process procedure of resource update, the client’s lease could be timeout, which means the client could still access the resource after it is illegal.</p></li><li><p>The <code>session.Done</code> for a lease is not triggered in real-time, which means when the lease is timeout and revoked by etcd server, the <code>session.Done</code> channel may not be fired immediately. This is because <code>session.Done</code> is only notified after the etcd client establish a new keepalive request, there could be a time window as long as 1&#x2F;3 of session ttl that <code>session.Done</code> is not notified.</p></li></ol><p>The goal of aliveness guarantee for resource access can be achieved by using etcd <code>Txn</code> simply. As there exists a key bounded with client lease, the client can make use of this key to guarantee lease is timeout during other etcd key value operations. The main logic can be as follows.</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">ErrLeaseTimeout := errors.New(<span class="string">&quot;lease associated key is deleted&quot;</span>)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">alivenessGuaranteeAccess</span><span class="params">(ctx context.Context, leasedKey, resourceKey <span class="type">string</span>)</span></span> <span class="type">error</span> &#123;</span><br><span class="line">    resp, err := cli.Get(ctx, leasedKey)</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> err</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> resp.Count == <span class="number">0</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> ErrLeaseTimeout</span><br><span class="line">    &#125;</span><br><span class="line">    revision := resp.Kvs[<span class="number">0</span>].ModRevision</span><br><span class="line">    txnResp, err := etcdCli.Txn(ctx).If(</span><br><span class="line">        clientv3.Compare(clientv3.ModRevision(leasedKey), <span class="string">&quot;=&quot;</span>, revision),</span><br><span class="line">    ).Then(</span><br><span class="line">        clientv3.OpPut(resourceKey, <span class="string">&quot;new value&quot;</span>),</span><br><span class="line">    ).Commit()</span><br><span class="line">    <span class="keyword">if</span> err != <span class="literal">nil</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> err</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> !txnResp.Succeeded &#123;</span><br><span class="line">        <span class="keyword">return</span> ErrLeaseTimeout</span><br><span class="line">    &#125;</span><br><span class="line">    log.Info(<span class="string">&quot;update resource key successfully&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="Dig-into-the-implement-principle-of-etcd-lease"><a href="#Dig-into-the-implement-principle-of-etcd-lease" class="headerlink" title="Dig into the implement principle of etcd lease"></a>Dig into the implement principle of etcd lease</h2><p>In this part I will talk about the implement principle of etcd lease based on code in <a href="https://github.com/etcd-io/etcd/tree/v3.4.14">tag-3.4.14</a>. Basically, each etcd server runs a lease manager which implements the <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L82">Lessor</a> interface. Most of the lease management is via raft to keep lease information consistent among multiple etcd servers. Take the lease grant operation as an example. When a <code>LeaseGrantRequest</code> is received by etcd server, the gRPC request will be processed in <a href="https://github.com/etcd-io/etcd/blob/v3.4.14/etcdserver/api/v3rpc/lease.go#L39">LeaseGrant</a> of a lease server and return <code>LeaseRevokeResponse</code> after processing. When processing the LeaseGrantRequest, it will be passed to <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/etcdserver/v3_server.go#L247">LeaseGrant</a> function of <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/etcdserver/v3_server.go#L53">EtcdServer&#x2F;Lessor</a> to trigger an internal raft request. Then raft message will be applied via the <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/etcdserver/v3_server.go#L609">internal raft mechanism</a> to all servers. When <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/etcdserver/apply.go#L137">applying the <code>LeaseGrant</code> message</a> in each etcd server, The <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L258">Grant</a> function of a <code>Lessor</code> will be finally called.</p><p>The main event loop of a <code>Leasor</code> contains two periodic jobs, <code>revokeExpiredLeases</code> and <code>checkpointScheduledLeases</code>, both of them <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L587-L596">run every 500ms</a>.</p><ul><li><a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L601">revokeExpiredLeases</a> finds all leases past their expiry and sends them to an expired channel for revoking, the channel is consumed in <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/etcdserver/server.go#L1061">etcd server’s main loop</a>. Each lease is associated with a <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lease_queue.go#L22">LeaseItem</a> and all lease items are stored in a <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lease_queue.go#L63">min heap</a>, the heap item is sorted by the expiration time of lease. When I was reading the code about iterating the expiration heap, I found an interesting code snippet, each time the lessor pops an expired item from the heap, it will <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L679-L681">put back a new lease item with the same lease ID but adding an <code>expiredLeaseRetryInterval</code> to the expired time</a>. This is a patched logic to fix a bug that if the receiver of expired channel does not revoke lease successfully, the lease will be never revoked because it can’t be retrieved from lease expiration heap anymore. More details can be found in <a href="https://github.com/etcd-io/etcd/pull/10693">this PR</a>.</li><li><a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L589">checkpointScheduledLeases</a> was introduced since etcd 3.4 in <a href="https://github.com/etcd-io/etcd/pull/9924">this PR</a>, this PR has described the requirement and mechanism of <code>lease checkpointing</code> detailedly. It is designed for the scenario that one etcd leader is transfered, the new leader will rebuild lease information and inherit the remaining ttl of existing leases instead of auto-renew to their full TTL.</li></ul><h2 id="Precision-of-etd-lease"><a href="#Precision-of-etd-lease" class="headerlink" title="Precision of etd lease"></a>Precision of etd lease</h2><p>In short, the precision of etcd lease is <strong>second level</strong>, which is reflected in two aspects:</p><ul><li>When a lease is granted, the time unit for ttl is second. Besides there exists a <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L283-L285">minimum ttl mechanism</a> in etcd.</li><li>Since etcd server uses a lazy way to determine which lease is timeout, instead of some more precise notification mechanism, it adds a latency for lease timeout. This means when we grant a new lease with TTL &#x3D; N second, and don’t send any keepalive request for this lease, the time window that this lease will be revoked in etcd server is about [N, N + delta second], where delta is generally 0.5, but considering some time cost of other logic, the delta could be more than 0.5. Taking a <a href="https://gist.github.com/amyangfei/23346332933d833fc42bd0c7d9406a67">sample code</a> as example, this code snippet grants a new lease with TTL&#x3D;5s every 50ms, 20 leases totally. For each lease attaches a key on it and sends a keepalive request to etcd server to refresh lease. Then watches for the key delete operation and records the duration for each lease timeout. From the <a href="https://gist.github.com/amyangfei/23346332933d833fc42bd0c7d9406a67#gistcomment-3578996">testing result</a>, the duration of lease revoked is between [5s, 5.6s], which is as expected.</li></ul><p>What’s more, etcd server has a <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L44-L45">hard code limit when revoking lease</a>, <strong>each round of expired lease revoking, at most 500 leases can be revoked</strong>. This can be easily verified by <a href="https://gist.github.com/amyangfei/23346332933d833fc42bd0c7d9406a67#file-large_amount_lease_expired-go">the code snippet</a>. In this scenario the lease expiry duration will have more latency, a test result is as follows:</p><table><thead><tr><th>duration(s)</th><th>5</th><th>5.1</th><th>5.2</th><th>5.3</th><th>5.4</th><th>5.5</th><th>5.7</th><th>5.8</th><th>6</th><th>6.1</th><th>6.4</th><th>6.5</th><th>6.8</th><th>6.9</th><th>7.2</th><th>7.3</th><th>7.7</th><th>8.1</th><th>8.2</th></tr></thead><tbody><tr><td>lease count</td><td>23</td><td>2</td><td>40</td><td>147</td><td>346</td><td>29</td><td>470</td><td>30</td><td>125</td><td>375</td><td>1</td><td>499</td><td>21</td><td>479</td><td>1</td><td>499</td><td>500</td><td>265</td><td>148</td></tr></tbody></table><p>In most cases, making a large amount of keys expire at the same time is not a good design. And when we use etcd lease, we must be aware of the <strong>lazy</strong> expiration mechanism.</p><h2 id="Tolerance-with-clock-drift"><a href="#Tolerance-with-clock-drift" class="headerlink" title="Tolerance with clock drift"></a>Tolerance with clock drift</h2><p>Operating systems provide both a “wall clock” which is subject to changes for clock synchronization, and a “monotonic clock” which is not. The general rule is that the wall clock is for telling time and the monotonic clock is for measuring time. Is the etcd lease reliable if the system’s wall clock is updated by NTP service? The answer is yes, both in the etcd server side and etcd client side, the lease implementation is reliable because monotonic clock is used. Since <a href="https://golang.org/doc/go1.9#monotonic-time">Go 1.9 builtin monotonic time library</a> is provided, etcd makes use of this feature to ensure the safety of time comparison.</p><ul><li>For the server side, both the <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L853-L858">expiry time setter</a> of a lease and <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L879-L886">expired checker</a> are using monotonic time.</li><li>For the client side, it uses <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L565">Time.Before()</a> API to check whether a keepalive request should be sent, which is also clock drift tolerable.</li></ul><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>Etcd lease is powerful but has some restrictions, it is better to know the underlying principle of etcd lease, which will help to use it correctly and reasonably.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;This article will first talk about a wrong use case with etcd lease, and then based on that case, I will dig into the design principle of etcd lease and some use scenario with etcd lease.&lt;/p&gt;
&lt;h2 id=&quot;A-wrong-use-case-with-etcd-lease&quot;&gt;&lt;a href=&quot;#A-wrong-use-case-with-etcd-lease&quot; class=&quot;headerlink&quot; title=&quot;A wrong use case with etcd lease&quot;&gt;&lt;/a&gt;A wrong use case with etcd lease&lt;/h2&gt;&lt;p&gt;There exist two roles in the following scenario, one is client and the other one is coordinator. More than one clients could exist at the same time. Each of them has an unique ID, and when a new client starts it applies a new lease from etcd and puts a key corresponding to the client ID with lease as option. The client must call &lt;code&gt;KeepAlive&lt;/code&gt; of its lease periodically to keep lease not timeout. Once the lease is timeout and deleted by etcd server, the client becomes illegal and should not access the etcd resource anymore. The coordinator monits the client ID key, when a new client registers, it allocates new resource&amp;#x2F;task to this client, which can be represented by a client ID relevant key value. And when it detects client ID key deleted (which means the client lease timeout), it will recycle the allocated resource of this client.&lt;/p&gt;
&lt;p&gt;Here we use a etcd session to maintain client lease and lease keepalive, a simple work model of client is as follows&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="etcd" scheme="http://amyangfei.me/tags/etcd/"/>
    
  </entry>
  
  <entry>
    <title>Some best practices with go etcd library</title>
    <link href="http://amyangfei.me/2020/12/19/best-practice-with-go-etcd/"/>
    <id>http://amyangfei.me/2020/12/19/best-practice-with-go-etcd/</id>
    <published>2020-12-18T16:00:00.000Z</published>
    <updated>2022-07-16T14:47:53.937Z</updated>
    
    <content type="html"><![CDATA[<p>Etcd is a distributed reliable key-value store written by golang and native golang client binding is provided in its official repository, which makes it very convenient as well as robust to write golang code to communicate with etcd server. Here robust means the etcd client should guarantee correctness and high availability under faulty conditions, more details can be found in <a href="https://etcd.io/docs/v3.4.0/learning/design-client/">etcd official client design document</a>. This article summarizes some best practises with etcd client library from the lessons I learned from the production environment. To explain some implementation mechanisms I will also link to etcd source code (mainly based on branch release-3.4).</p><h2 id="Consume-data-from-the-watch-response-channel-ASAP"><a href="#Consume-data-from-the-watch-response-channel-ASAP" class="headerlink" title="Consume data from the watch response channel ASAP"></a>Consume data from the watch response channel ASAP</h2><p><a href="https://etcd.io/docs/v3.4.0/learning/api/#watch-streams">Watch</a> works with a bi-directional gRPC stream between watch client and etcd server, the most common way to use watch is as follows, receive keyspace changed result from the watch channel and consume these KV events one by one.</p><span id="more"></span><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">cli, err := clientv3.New(clientv3.Config&#123;</span><br><span class="line">    Endpoints:   []<span class="type">string</span>&#123;<span class="string">&quot;127.0.0.1:2379&quot;</span>&#125;,</span><br><span class="line">    Context:     ctx,</span><br><span class="line">    DialTimeout: <span class="number">3</span> * time.Second,</span><br><span class="line">    DialOptions: []grpc.DialOption&#123;&#125;,</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// handle error</span></span><br><span class="line">ch := cli.Watch(ctx, <span class="string">&quot;/some/keyspace&quot;</span>, clientv3.WithPrefix())</span><br><span class="line"><span class="keyword">for</span> resp := <span class="keyword">range</span> ch &#123;</span><br><span class="line">    <span class="keyword">for</span> _, event = <span class="keyword">range</span> resp.Events &#123;</span><br><span class="line">        <span class="keyword">switch</span> event.Type &#123;</span><br><span class="line">        <span class="keyword">case</span> mvccpb.PUT:</span><br><span class="line">            <span class="comment">// process with put event</span></span><br><span class="line">        <span class="keyword">case</span> mvccpb.DELETE:</span><br><span class="line">            <span class="comment">// process with delete event</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>Supposing the process throughput for changed KV events is less than the watched keyspace changed frequency, it is <strong>easy</strong> to find the delay between consumption and keyspace update in etcd, with the help of monitoring system or some data comparison, etc. If we can’t reduce the update frequency of etcd keyspace, then we must ensure the process throughput can match the keyspace update frequency, by either increasing the consume speed of consumer or cache the KV changed events from watch channel and consume data asynchronously.</p><p>There exist other ways to use watch, for example, multiple clients change the same key randomly, in an atomic way by using Txn API. Another client wants to subscribe to the update event of this key as soon as possible, but when it knows the key has changed, it doesn’t need to know data for each MVCC version exactly. Such as three clients, each of them updates the key once, and the key has three versions: v1, v2, v3. The subscribe client wants to know the key is updated and queries the data in v3 is enough. The logic for subscribe client can be as follows. It creates a channel to receive keyspace change notification from the watch channel and the outer code consumes this channel continually.</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">output := <span class="built_in">make</span>(channel <span class="keyword">struct</span>&#123;&#125;, <span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">    ctx, cancel := context.WithCancel(parentCtx)</span><br><span class="line">    ch := cli.Watch(ctx, <span class="string">&quot;/some/key&quot;</span>)</span><br><span class="line">    <span class="keyword">for</span> resp := <span class="keyword">range</span> ch &#123;</span><br><span class="line">        <span class="keyword">if</span> resp.Err() != <span class="literal">nil</span> &#123;</span><br><span class="line">            <span class="comment">// error processing</span></span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">select</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> &lt;-ctx.Done():</span><br><span class="line">        <span class="keyword">case</span> output &lt;- <span class="keyword">struct</span>&#123;&#125;&#123;&#125;:</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    cancel()</span><br><span class="line">&#125;()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> &#123;</span><br><span class="line">    <span class="keyword">select</span> &#123;</span><br><span class="line">    <span class="keyword">case</span> &lt;-parentCtx.Done():</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    <span class="keyword">case</span> &lt;-output:</span><br><span class="line">        <span class="comment">// some logic code here</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>This is a real production scenario and the subscribe client works <em>well</em> (But in fact it is not accurate, I will explain later), and we can always get the keyspace update notification in time. However we observed a slowly increment with heap memory, and a heap pprof shows large amount of inuse memory with <code>go.etcd.io/etcd/mvcc/mvccpb.(*KeyValue).Unmarshal</code> and <code>go.etcd.io/etcd/clientv3.(*watchGrpcStream).dispatchEvent</code>. After simplifying the working model to the above code we find out the root cause is consume throughput of output channel is less then keyspace update frequent, which is the same thing as the first scenario! Since the buffer size of output channel is 1, KV changed events are accumulated in etcd client, and the notification from output channel is out of date, the subscribe client works well is just because the keyspace is keeping updated, but the notification is out of date already. The fix for this scenario is quite simple, we change the notification to a non-blocking way by adding a default branch in select.</p><figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">     select &#123;</span><br><span class="line"><span class="deletion">-    case &lt;-ctx.Done():</span></span><br><span class="line">     case output &lt;- struct&#123;&#125;&#123;&#125;:</span><br><span class="line"><span class="addition">+    default:</span></span><br><span class="line">     &#125;</span><br></pre></td></tr></table></figure><p>From etcd source code we can know each <a href="https://github.com/etcd-io/etcd/blob/release-3.4/clientv3/watch.go#L219"><code>watcherStream</code></a> holds <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/watch.go#L234-L235">an unlimited <code>WatchResponse</code> buffer</a>, and the watched result is <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/watch.go#L234-L235">appended to this buffer</a> no matter how large it is. So if the watched keyspace keeps changing, and the consume speed from the watch channel is slow, large amount of <code>WatchResponse</code> objects will be accumulated in etcd client. This is the lesson we learn from this case, when using etcd watch, we should consume data from the watch response channel as soon as possible in order to keep the keyspace change notification up to date, and prevent unnecessary memory consumption.</p><p>Besides if a watch client just wants to subscribe to the keyspace change notification, but doesn’t care about the content of key and value, is there any <code>OpOption</code> in etcd client library to ignore key or value. Unfortunately, there is no such option for watch API in golang etcd library currently.</p><h2 id="Tips-for-using-a-lease-Session"><a href="#Tips-for-using-a-lease-Session" class="headerlink" title="Tips for using a lease Session"></a>Tips for using a lease Session</h2><p><a href="https://etcd.io/docs/v3.4.0/learning/api/#lease-api">Lease</a> is a mechanism for detecting client liveness in etcd. The etcd golang library defines an <a href="https://github.com/etcd-io/etcd/blob/release-3.4/clientv3/lease.go#L108"><code>Lease</code> interface</a> and provides a <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L136"><code>KeepAlive</code></a> API which will try to keep the given lease alive forever. The <code>KeepAlive</code> API returns a <code>*LeaseKeepAliveResponse</code> chan, we can read from this channel to know the latest TTL for given leaseID. The common way to create a new Lease and set keepalive for it is as follows.</p><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ignore error handling</span></span><br><span class="line">cli, err := clientv3.New(clientv3.Config&#123;Endpoints: []<span class="type">string</span>&#123;<span class="string">&quot;127.0.0.1:2379&quot;</span>&#125;&#125;)</span><br><span class="line">leaseResp, err := cli.Grant(ctx, <span class="number">10</span> <span class="comment">/*ttl*/</span>)</span><br><span class="line">ch, err := cli.KeepAlive(ctx, leaseResp.ID)</span><br><span class="line"></span><br><span class="line"><span class="keyword">go</span> <span class="function"><span class="keyword">func</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">for</span> &#123;</span><br><span class="line">        <span class="keyword">select</span> &#123;</span><br><span class="line">        <span class="keyword">case</span> &lt;-ctx.Done():</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">case</span> resp := &lt;-ch:</span><br><span class="line">            <span class="comment">// process lease response</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;()</span><br></pre></td></tr></table></figure><p>Note the response channel size of <code>KeepAlive</code> has a <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L267">buffer size of 16</a>, if the channel is not consumed promptly the channel may become full. After channel is full, the lease client will continue sending keepalive requests to the etcd server, but will <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L519-L532">drop responses</a> until there is capacity on the channel to send more responses.</p><p>If we don’t want to maintain the keepalive for a lease manually, the etcd golang library also provides a powerful <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/concurrency/session.go#L28">Leased Session</a> encapsulation. When creating a session via <code>NewSession</code> API, it grants a new Lease and setup <code>KeepAlive</code> for the binding client automatically, more details can be found in <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/concurrency/session.go#L38-L72">the etcd source code</a>.</p><p>Lease TTL is the most important option when we interact with Lease, it is necessary to know how keepalive works with TTL. The first question is how often will a client send the keepalive request to etcd server. It is easy to find in source code, the lessor uses a time barrier mechanism to determine when to send a keepalive message. For each time a keepalive response is received, the lessor sets the <code>nextKeepAlive</code> time to <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L517"><code>1/3</code> of keepalive TTL</a>. After each round of keepalive request the <code>sendKeepAliveLoop</code> will <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L580">sleep 500ms</a> before the next keepalive round.</p><p>There is another question, what will happen when network is not stable between etcd client and etcd server? In this scenario the keepalive request message could be blocked because there is no sufficient flow control to schedule messages with the gRPC transport, and the lease could be timeout, the timeout will be detected in the <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/clientv3/lease.go#L537"><code>deadlineLoop</code></a>.</p><p>Lease TTL should be set carefully, according to <a href="https://github.com/etcd-io/etcd/issues/6025">the discussion in github</a>, the minimum TTL needs to be larger than the election timeout of etcd server, which is 1s by default, and can be 3-5s usually. What’s more, etcd server has a minimum lease TTL restriction, <a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/lease/lessor.go#L283-L285">any requests for shorter TTLs will be extended to the minimum TTL</a>. The value of minimum lease TTL is based on <code>election-timeout</code> of etcd server, and it equals to <code>math.Ceil(3 * election-timeout / 2)</code>(<a href="https://github.com/etcd-io/etcd/blob/8a03d2e9614b8192ebaa5a25ef92f6ff62e3593c/etcdserver/server.go#L539">ref</a>). For example, if <code>election-timeout</code> is 3s, the minimum lease TTL is <code>math.Ceil(3 * 3 / 2) = 5</code>s.</p><h2 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h2><p>The etcd source code has good readability, detail comments and full completed test cases, and I have also learned many use tips from the etcd source code. If you also use etcd golang library in your code, I strongly recommend reading the source code of etcd to know exactly how it works and what we need to pay attention to.</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;Etcd is a distributed reliable key-value store written by golang and native golang client binding is provided in its official repository, which makes it very convenient as well as robust to write golang code to communicate with etcd server. Here robust means the etcd client should guarantee correctness and high availability under faulty conditions, more details can be found in &lt;a href=&quot;https://etcd.io/docs/v3.4.0/learning/design-client/&quot;&gt;etcd official client design document&lt;/a&gt;. This article summarizes some best practises with etcd client library from the lessons I learned from the production environment. To explain some implementation mechanisms I will also link to etcd source code (mainly based on branch release-3.4).&lt;/p&gt;
&lt;h2 id=&quot;Consume-data-from-the-watch-response-channel-ASAP&quot;&gt;&lt;a href=&quot;#Consume-data-from-the-watch-response-channel-ASAP&quot; class=&quot;headerlink&quot; title=&quot;Consume data from the watch response channel ASAP&quot;&gt;&lt;/a&gt;Consume data from the watch response channel ASAP&lt;/h2&gt;&lt;p&gt;&lt;a href=&quot;https://etcd.io/docs/v3.4.0/learning/api/#watch-streams&quot;&gt;Watch&lt;/a&gt; works with a bi-directional gRPC stream between watch client and etcd server, the most common way to use watch is as follows, receive keyspace changed result from the watch channel and consume these KV events one by one.&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="source code reading" scheme="http://amyangfei.me/tags/source-code-reading/"/>
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="etcd" scheme="http://amyangfei.me/tags/etcd/"/>
    
  </entry>
  
  <entry>
    <title>使用 Go 编写 Redis Loadable Modules</title>
    <link href="http://amyangfei.me/2016/08/03/redis-module-with-cgo/"/>
    <id>http://amyangfei.me/2016/08/03/redis-module-with-cgo/</id>
    <published>2016-08-02T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>本文会介绍如何使用 go 编写 redis loadable modules，并分析编写模块和使用cgo可能遇到的坑。</p><h2 id="什么是redis-loadable-modules"><a href="#什么是redis-loadable-modules" class="headerlink" title="什么是redis loadable modules"></a>什么是redis loadable modules</h2><p>可加载模块是redis最新加入的功能，目前需要在<code>unstable</code>分支才可以使用。简单说模块系统是redis的C代码暴露出一些API，定义在头文件<a href="https://github.com/antirez/redis/blob/unstable/src/redismodule.h">redismodule.h</a>中，外部模块引用该头文件即可访问所有的API函数，这些API提供了包括访问redis的字典空间、调用redis命令、向客户端返回数据等诸多功能。外部模块是以动态库的形式被redis server加载并使用，可以在redis server启动时加载，也可以在启动后动态加载。更多的细节可以参考文档<a href="https://github.com/antirez/redis/blob/unstable/src/modules/INTRO.md">redis module INTRO</a>。</p><p>在此之前想对redis扩展有两种方案：一是利用lua脚本；另一种则需要修改redis源码，类似于<a href="https://github.com/mattsta/krmt">Kit of Redis Module Tools</a>提供的方案。lua脚本的扩展性有限，并且lua是通过redis的上层API来调用redis命令的，无法直接访问底层的存储数据，调用redis更底层的API；修改源码的方案就更加hack，是没有办法不断与上游分支合并的。</p><span id="more"></span><p>显然心的模块系统明显优于以上两种方案，优点包括：</p><ul><li>直接访问redis存储的各种数据结构；</li><li>直接对存储数据的内存进行操作；</li><li>模块仅依赖<code>redismodule.h</code>暴露的接口函数，而不依赖redis本身的实现，因此可以兼容redis的版本升级。</li></ul><p>模块系统也有缺点，比如模块中的代码bug引发的异常会直接导致redis server crash掉；模块的问题譬如引入的内存泄漏，代码执行阻塞都会影响redis服务的正常运行。这些缺点不是模块系统本身的问题，而是这种扩展的灵活性和系统稳定性的权衡，是可以通过优质的扩展模块来避免的。</p><p>使用C来编写redis扩展模块很简单，参考文档<a href="https://github.com/antirez/redis/blob/unstable/src/modules/INTRO.md">redis module INTRO</a>，你可以在5分钟内学会编写一个redis扩展模块。Redis Lab官方也提供了很多有趣的模块 <a href="http://redismodules.com/">Module Hub</a>。在文档中同样提到可以用其它语言来编写redis扩展模块。</p><blockquote><p>it will be possible to use C++ or other languages that have C binding functionalities.</p></blockquote><p>go语言的<a href="https://golang.org/cmd/cgo/">cgo</a>提供了Go和C互相调用的支持，因此本文来尝试通过go语言编写redis的扩展模块。下文所有的代码都可以在<a href="https://github.com/amyangfei/RedisModules-Go">RedisModules-Go</a>这个仓库找到，仓库里还提供了redis module lab的两个模块<a href="http://redismodules.com/modules/password/">password</a>，<a href="http://redismodules.com/modules/graphicsmagick-2/">graphicsmagick</a>的go版本，以及一些简单的benchmark。</p><p>redis扩展模块的形式是很固定的，需要编写且只编写两个部分：注册命令的函数和具体实现命令的函数。我们分两个阶段来编写redis的go扩展模块：第一阶段是通过go编写逻辑代码，即go代码拿到数据、处理、返回处理结果；第二阶段是go代码直接访问redismodule.h提供的API获取数据、处理、返回。先看看第一种类型。</p><h2 id="通过go编写逻辑处理"><a href="#通过go编写逻辑处理" class="headerlink" title="通过go编写逻辑处理"></a>通过go编写逻辑处理</h2><p>基本思路是使用go编写逻辑处理，go的函数接收的输入是C的数据类型，可以是指向C内存空间的指针；在C代码中调用由go编写的逻辑处理函数，具体的调用方式是go代码编译时指定<code>buildmode=c-shared</code>得到动态库和相关头文件，在C代码中引用头文件并调用。最简单的实现代码如下所示：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* ECHO1 &lt;string&gt; - Echo back a string sent from the client */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">Echo1Command</span><span class="params">(RedisModuleCtx *ctx, RedisModuleString **argv, <span class="type">int</span> argc)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (argc &lt; <span class="number">2</span>) <span class="keyword">return</span> RedisModule_WrongArity(ctx);</span><br><span class="line">    RedisModule_AutoMemory(ctx);</span><br><span class="line"></span><br><span class="line">    <span class="type">size_t</span> len;</span><br><span class="line">    <span class="type">char</span> *dst = RedisModule_Strdup(RedisModule_StringPtrLen(argv[<span class="number">1</span>], &amp;len));</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">GoEcho1_return</span> <span class="title">r</span> =</span> GoEcho1(dst);</span><br><span class="line">    RedisModuleString *rm_str = RedisModule_CreateString(ctx, r.r0, r.r1);</span><br><span class="line">    <span class="built_in">free</span>(r.r0);</span><br><span class="line">    RedisModule_Free(dst);</span><br><span class="line"></span><br><span class="line">    RedisModule_ReplyWithString(ctx, rm_str);</span><br><span class="line">    <span class="keyword">return</span> REDISMODULE_OK;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="comment">// #include &lt;stdlib.h&gt;</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;C&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//export GoEcho1</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GoEcho1</span><span class="params">(s *C.char)</span></span> (*C.char, <span class="type">int</span>) &#123;</span><br><span class="line">    gostr := (C.GoString(s) + <span class="string">&quot; from golang1&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> C.CString(gostr), <span class="built_in">len</span>(gostr)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;&#125;</span><br></pre></td></tr></table></figure><p>具体实现中涉及到申请的内存空间是在C的运行环境还是go的运行环境，因为go的运行时提供了gc，而C则需要手动管理内存，因此这其中有很多细节需要注意；同时go和C之间可以传递的数据也有一些限制，后文会详细叙述。</p><h2 id="通过go调用redismodule-h定义的API"><a href="#通过go调用redismodule-h定义的API" class="headerlink" title="通过go调用redismodule.h定义的API"></a>通过go调用redismodule.h定义的API</h2><p>第一步中所做的是提供数据给go代码进行逻辑处理并返回数据，那么如果希望在go代码中也可以调用redismodule.h定义的API，又需要如何处理？</p><p>直观的想通过go调用C代码，在go中直接<code>#include &quot;redismodule.h&quot;</code>就可以了嘛，于是我们编写如下的go代码：</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="comment">// #include &quot;redismodule.h&quot;</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">typedef RedisModuleString *(*redis_func) (RedisModuleCtx *ctx, char *ptr, size_t len);</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">inline RedisModuleString *redis_bridge_func(redis_func f, RedisModuleCtx *ctx, char *ptr, size_t len)</span></span><br><span class="line"><span class="comment">&#123;</span></span><br><span class="line"><span class="comment">    return f(ctx, ptr, len);</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;C&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//export GoEcho</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GoEcho</span><span class="params">(ctx *C.RedisModuleCtx, s *C.char)</span></span> *C.RedisModuleString &#123;</span><br><span class="line">    gostr := (C.GoString(s) + <span class="string">&quot; from golang&quot;</span>)</span><br><span class="line">    f := C.redis_func(C.RedisModule_CreateString)</span><br><span class="line">    <span class="keyword">return</span> C.redis_bridge_func(f, ctx, C.CString(gostr), C.size_t(<span class="built_in">len</span>(gostr)))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;&#125;</span><br></pre></td></tr></table></figure><p><code>redismodule.h</code>定义的API函数都是函数指针，由于go不支持直接调用C的函数指针，所以通过通过go的变量保存C的函数指针，并将该变量作为参数调用C的<code>bridge_function</code>，在<code>bridge_function</code>中调用目标函数指针。编译是可以通过的，但实际运行就会crash。通过调试很容易发现<code>C.RedisModule_CreateString</code>的值是<code>nil</code>，它没有指向正确的函数地址。那换一种方式使用一个C的函数来调用<code>RedisModule_CreateString</code>呢？</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">#include &quot;redismodule.h&quot;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">inline RedisModuleString *RedisModule_CreateString_Wrap(RedisModuleCtx *ctx, char *ptr, size_t len) &#123;</span></span><br><span class="line"><span class="comment">    void *getapifuncptr = ((void**)ctx)[0];</span></span><br><span class="line"><span class="comment">    RedisModule_GetApi = (int (*)(const char *, void *)) (unsigned long)getapifuncptr;</span></span><br><span class="line"><span class="comment">    RedisModule_GetApi(&quot;RedisModule_CreateString&quot;, (void **)&amp;RedisModule_CreateString);</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    RedisModuleString *rms = RedisModule_CreateString(ctx, ptr, len);</span></span><br><span class="line"><span class="comment">    return rms;</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;C&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//export GoEcho</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GoEcho</span><span class="params">(ctx *C.RedisModuleCtx, s *C.char)</span></span> *C.RedisModuleString &#123;</span><br><span class="line">        gostr := (C.GoString(s) + <span class="string">&quot; from golang version bridge&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> C.RedisModule_CreateString_Wrap(ctx, C.CString(gostr), C.size_t(<span class="built_in">len</span>(gostr)))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;&#125;</span><br></pre></td></tr></table></figure><p>实际运行时依然会在调用<code>RedisModule_CreateString</code>函数时crash掉，跟进gdb调试可以看到该函数指针并没有指向正确的内存地址。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">(gdb) l</span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">3</span>       <span class="comment">/*</span></span><br><span class="line"><span class="comment">4       #include &quot;redismodule.h&quot;</span></span><br><span class="line"><span class="comment">5</span></span><br><span class="line"><span class="comment">6       inline RedisModuleString *RedisModule_CreateString_Wrap(RedisModuleCtx *ctx, char *ptr, size_t len) &#123;</span></span><br><span class="line"><span class="comment">7           RedisModuleString *rms = RedisModule_CreateString(ctx, ptr, len);</span></span><br><span class="line"><span class="comment">8           return rms;</span></span><br><span class="line"><span class="comment">9       &#125;</span></span><br><span class="line"><span class="comment">10      */</span></span><br><span class="line"><span class="number">11</span>      import <span class="string">&quot;C&quot;</span></span><br><span class="line">(gdb) p RedisModule_CreateString</span><br><span class="line">$<span class="number">1</span> = (RedisModuleString *(*)(RedisModuleCtx *, <span class="type">const</span> <span class="type">char</span> *, <span class="type">size_t</span>)) <span class="number">0x0</span></span><br></pre></td></tr></table></figure><p>那么<code>redismodule.h</code>对外提供的函数指针是在何时指向实际的函数内存地址呢？从<code>redismodule.h</code>文件本身就会得到答案：加载一个外部模块都需要调用<code>RedisModule_Init</code>函数，在这个函数中会通过<code>RedisModuleCtx *ctx</code>变量定位到在redis代码<code>module.c</code>内提供的实际API函数，然后将函数指针指向真正的函数地址。由于在上述的go模块中，没有调用<code>RedisModule_Init</code>，<code>RedisModule_CreateString</code>自然指向的是非法的内存地址。所以简单改动一下代码，主动注册一下函数指针的地址即可在go的模块中调用<code>redismodule.h</code>提供的API。</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">#include &quot;redismodule.h&quot;</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">inline RedisModuleString *RedisModule_CreateString_Wrap(RedisModuleCtx *ctx, char *ptr, size_t len) &#123;</span></span><br><span class="line"><span class="comment">    void *getapifuncptr = ((void**)ctx)[0];</span></span><br><span class="line"><span class="comment">    RedisModule_GetApi = (int (*)(const char *, void *)) (unsigned long)getapifuncptr;</span></span><br><span class="line"><span class="comment">    RedisModule_GetApi(&quot;RedisModule_CreateString&quot;, (void **)&amp;RedisModule_CreateString);</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">    RedisModuleString *rms = RedisModule_CreateString(ctx, ptr, len);</span></span><br><span class="line"><span class="comment">    return rms;</span></span><br><span class="line"><span class="comment">&#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;C&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//export GoEcho</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GoEcho</span><span class="params">(ctx *C.RedisModuleCtx, s *C.char)</span></span> *C.RedisModuleString &#123;</span><br><span class="line">        gostr := (C.GoString(s) + <span class="string">&quot; from golang version bridge&quot;</span>)</span><br><span class="line">        <span class="keyword">return</span> C.RedisModule_CreateString_Wrap(ctx, C.CString(gostr), C.size_t(<span class="built_in">len</span>(gostr)))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;&#125;</span><br></pre></td></tr></table></figure><h2 id="一些细节"><a href="#一些细节" class="headerlink" title="一些细节"></a>一些细节</h2><p>编写模块的过程中关于内存使用发现不少有趣的地方。</p><h3 id="1-Go和C之间传递指针的规则和限制"><a href="#1-Go和C之间传递指针的规则和限制" class="headerlink" title="1. Go和C之间传递指针的规则和限制"></a>1. Go和C之间传递指针的规则和限制</h3><p>在<a href="https://github.com/amyangfei/RedisModules-Go/blob/master/example/basic/go1dot5/hello_module.go">go1.5&#x2F;hello_module.go</a>这个文件中可以看到export给C的go函数的返回值很多返回了go的指针，在C代码中调用go函数之后可以直接访问go的内存，这在go1.5是支持的，但是从go1.6之后加入了Go和C之间传递指针的限制，明确指出：</p><blockquote><p>A Go function called by C code may not return a Go pointer.</p></blockquote><p>go1.6对go和C的互相调用进行了大量的规范，有编译层面的也有在运行时的检查，详细可以参考<a href="https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md">12416-cgo-pointers</a>。规范的出发点有两点：一是更便于go的内存管理，总所周知go提供了gc，所以有一些破坏了gc规则的使用需要禁止；二是尽可能减少程序运行时内存访问出现的未知错误。</p><p>那么回到我们的redis go模块，如果不能从go函数返回go指针给C代码使用，那么从go如何返回数据给C代码呢？目前有两种，一是返回完整的C数据，二是返回C的指针。以hello.echo模块为例，对应的两种返回形式分别是：</p><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GoEcho1</span><span class="params">(s *C.char)</span></span> (*C.char, <span class="type">int</span>) &#123;</span><br><span class="line">    gostr := (C.GoString(s) + <span class="string">&quot; from golang1&quot;</span>)</span><br><span class="line">    <span class="keyword">return</span> C.CString(gostr), <span class="built_in">len</span>(gostr)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">GoEcho6</span><span class="params">(s *C.char, length, capacity C.<span class="type">int</span>)</span></span> (unsafe.Pointer, <span class="type">int</span>) &#123;</span><br><span class="line">    incr := <span class="string">&quot; from golang6&quot;</span></span><br><span class="line">    zslice := cgoutils.ZeroCopySlice(unsafe.Pointer(s), <span class="type">int</span>(capacity), <span class="type">int</span>(capacity), <span class="literal">false</span>)</span><br><span class="line">    <span class="built_in">copy</span>(zslice.Data[<span class="type">int</span>(length):], incr)</span><br><span class="line">    <span class="keyword">return</span> unsafe.Pointer(&amp;zslice.Data[<span class="number">0</span>]), <span class="type">int</span>(length) + <span class="built_in">len</span>(incr)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>echo1就是直接通过<code>C.String</code>生成C的<code>char *</code>并进行一次内存复制，将<code>gostr</code>的内容复制到C的内存空间。echo6的例子则是现将从C代码传来的内存地址直接映射到go的slice（这里在C代码已经为待处理的数据申请了足够多的内存空间），然后直接在go中直接操作这部分内存，最后返回这部分内存的C指针。显然，echo6比echo1减少了<code>gostr</code>的一次内存复制。使用较大的echo string进行benchmark可以很明显看到echo6比echo1更快。</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Benchmark_Echo1     2000            815435 ns/op</span><br><span class="line">Benchmark_Echo6     2000            575206 ns/op</span><br></pre></td></tr></table></figure><h3 id="2-内存管理"><a href="#2-内存管理" class="headerlink" title="2. 内存管理"></a>2. 内存管理</h3><p>在使用cgo时一定需要区分变量是在go的内存空间还是在C的内存空间，尤其注意在go代码中申请的C的数据一定需要手动释放内存，因为go的gc并不会回收这部分内存。所以譬如通过<code>C.Cstring()</code>生成的数据、通过<code>C.malloc()</code>申请的内存在使用后都需要手动回收。</p><h3 id="3-Go直接映射C的内存空间"><a href="#3-Go直接映射C的内存空间" class="headerlink" title="3. Go直接映射C的内存空间"></a>3. Go直接映射C的内存空间</h3><p>在go代码中C的数据类型会映射成为C.x，可以直接访问C数据类型的变量，但是如果想要对变量进行go代码的逻辑操作，就必须先转换成为go的数据类型，譬如希望对一个C的<code>char *</code>进行处理，需要现转换成为go的<code>slice</code>。转换有两种方法：一是直接调用<code>C.GoBytes</code>方法，另一种是利用反射构造<code>slice</code>，具体的使用方法参考<a href="https://github.com/amyangfei/RedisModules-Go/blob/master/cgoutils/sharemem.go">sharemem.go</a>。使用<code>C.GoBytes</code>会将C数据结构的内存复制到go的内存空间。而第二种方法则是直接映射，没有内存复制。</p><p>在直接映射C内存的使用场景下，对go对象slice的一些操作可以直接作用于C的内存空间，譬如在echo6中使用<code>copy(zslice.Data[int(length):], incr)</code>。这里就需要注意，如果一开始C申请的内存空间不足，但是强制增大go中slice的capacity，然后进行copy操作，结果会发现程序运行中会crash掉。这种用法的问题在于不能区分slice增加的capacity内存是位于C代码还是go代码的运行环境；如果不是copy而是使用slice的append操作，由于capacity不足go的slice会重新申请内存空间，那么对应的内存都位于go的运行环境，与原来C运行环境中的数据就没有关系了。</p><h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>后续还会对比使用go和C编写同样的扩展模块在性能方面会有怎样的差距，这里就不再继续讨论。redis计划会在4.0版本中合并模块系统的功能，这还是很值得期待的。使用cgo来完成go和C的交互也十分常见，go标准库本身就有很多地方使用到了cgo来使用C的代码，本文编写的<a href="https://github.com/amyangfei/RedisModules-Go/tree/master/modules/graphicsmagick">graphicsmagick</a>模块使用的<a href="https://github.com/gographics/imagick">imagick</a>库本身也是通过cgo对ImageMagick MagickWand C API的封装。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;本文会介绍如何使用 go 编写 redis loadable modules，并分析编写模块和使用cgo可能遇到的坑。&lt;/p&gt;
&lt;h2 id=&quot;什么是redis-loadable-modules&quot;&gt;&lt;a href=&quot;#什么是redis-loadable-modules&quot; class=&quot;headerlink&quot; title=&quot;什么是redis loadable modules&quot;&gt;&lt;/a&gt;什么是redis loadable modules&lt;/h2&gt;&lt;p&gt;可加载模块是redis最新加入的功能，目前需要在&lt;code&gt;unstable&lt;/code&gt;分支才可以使用。简单说模块系统是redis的C代码暴露出一些API，定义在头文件&lt;a href=&quot;https://github.com/antirez/redis/blob/unstable/src/redismodule.h&quot;&gt;redismodule.h&lt;/a&gt;中，外部模块引用该头文件即可访问所有的API函数，这些API提供了包括访问redis的字典空间、调用redis命令、向客户端返回数据等诸多功能。外部模块是以动态库的形式被redis server加载并使用，可以在redis server启动时加载，也可以在启动后动态加载。更多的细节可以参考文档&lt;a href=&quot;https://github.com/antirez/redis/blob/unstable/src/modules/INTRO.md&quot;&gt;redis module INTRO&lt;/a&gt;。&lt;/p&gt;
&lt;p&gt;在此之前想对redis扩展有两种方案：一是利用lua脚本；另一种则需要修改redis源码，类似于&lt;a href=&quot;https://github.com/mattsta/krmt&quot;&gt;Kit of Redis Module Tools&lt;/a&gt;提供的方案。lua脚本的扩展性有限，并且lua是通过redis的上层API来调用redis命令的，无法直接访问底层的存储数据，调用redis更底层的API；修改源码的方案就更加hack，是没有办法不断与上游分支合并的。&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="golang" scheme="http://amyangfei.me/tags/golang/"/>
    
    <category term="redis" scheme="http://amyangfei.me/tags/redis/"/>
    
    <category term="redis module" scheme="http://amyangfei.me/tags/redis-module/"/>
    
  </entry>
  
  <entry>
    <title>RQ (Redis Queue) 使用的一些思考</title>
    <link href="http://amyangfei.me/2016/01/30/redis-queue-rethink/"/>
    <id>http://amyangfei.me/2016/01/30/redis-queue-rethink/</id>
    <published>2016-01-29T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>最近使用了 <a href="http://python-rq.org/">rq</a> 这个简单的队列处理库，其中有一些任务需要使用MySQL的连接或者redis的连接，对此有一些思考。</p><h2 id="MySQL-x2F-redis的连接复用"><a href="#MySQL-x2F-redis的连接复用" class="headerlink" title="MySQL&#x2F;redis的连接复用"></a>MySQL&#x2F;redis的连接复用</h2><p>rq 提供了两种 worker 模型：基于 <code>fork</code> 的 worker 模型和直接在主线程执行任务的 worker 模型。基于 fork 的 worker 在执行任务之前先 fork 一个子进程，在子进程中执行具体的任务，父进程等待子进程执行返回。在基于 fork 的 worker 模型下，如果在父进程有一个 MySQL&#x2F;redis 连接，由于子进程会继承父进程的地址空间，具有相同的打开文件、socket、管道等，所以子进程中也有同样的 MySQL&#x2F;redis 连接，那么在这种情况下这个连接可以直接使用么？通过以下代码简单测试一下，连接 MySQL 使用 <a href="https://github.com/bdarnell/torndb">torndb</a> ，连接 redis 使用 <a href="https://github.com/andymccurdy/redis-py">redis-py</a>：</p><span id="more"></span><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"><span class="comment"># encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> redis</span><br><span class="line"><span class="keyword">import</span> torndb</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">init_redis_conn</span>():</span><br><span class="line">    <span class="keyword">return</span> redis.StrictRedis(port=<span class="number">6380</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">init_mysql_conn</span>():</span><br><span class="line">    <span class="keyword">return</span> torndb.Connection(</span><br><span class="line">        host=<span class="string">&#x27;127.0.0.1&#x27;</span>, user=<span class="string">&#x27;root&#x27;</span>, password=<span class="string">&#x27;password&#x27;</span>, database=<span class="string">&#x27;test&#x27;</span>)</span><br><span class="line"></span><br><span class="line">_redis_conn = init_redis_conn()</span><br><span class="line">_mysql_conn = init_mysql_conn()</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">get_redis_conn</span>():</span><br><span class="line">    <span class="keyword">global</span> _redis_conn</span><br><span class="line">    <span class="keyword">if</span> _redis_conn <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        _redis_conn = init_redis_conn()</span><br><span class="line">    <span class="keyword">return</span> _redis_conn</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">get_mysql_conn</span>():</span><br><span class="line">    <span class="keyword">global</span> _mysql_conn</span><br><span class="line">    <span class="keyword">if</span> _mysql_conn <span class="keyword">is</span> <span class="literal">None</span>:</span><br><span class="line">        _mysql_conn = init_mysql_conn()</span><br><span class="line">    <span class="keyword">return</span> _mysql_conn</span><br></pre></td></tr></table></figure><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"><span class="comment"># encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> errno</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> mconn</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">redis_op</span>():</span><br><span class="line">    conn = mconn.get_redis_conn()</span><br><span class="line">    k = <span class="built_in">int</span>(time.time())</span><br><span class="line">    conn.<span class="built_in">set</span>(k, k)</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">mysql_op</span>():</span><br><span class="line">    conn = mconn.get_mysql_conn()</span><br><span class="line">    sql = <span class="string">&#x27;INSERT INTO users (name) values (%s)&#x27;</span></span><br><span class="line">    conn.insert(sql, <span class="built_in">str</span>(<span class="built_in">int</span>(time.time())))</span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">fork_test</span>(<span class="params">func</span>):</span><br><span class="line">    child_pid = os.fork()</span><br><span class="line">    <span class="keyword">if</span> child_pid == <span class="number">0</span>:</span><br><span class="line">        func()</span><br><span class="line">        os._exit(<span class="number">0</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            os.waitpid(child_pid, <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">except</span> OSError <span class="keyword">as</span> e:</span><br><span class="line">            <span class="keyword">if</span> e.errno != errno.EINTR:</span><br><span class="line">                <span class="keyword">raise</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        time.sleep(<span class="number">0.5</span>)</span><br><span class="line">        <span class="comment"># fork_test(mysql_op)</span></span><br><span class="line">        fork_test(redis_op)</span><br></pre></td></tr></table></figure><p>执行 main.py，观察3306端口和6380端口的连接数，发现 MySQL 的连接会被复用，但是在 redis 的连接并没有复用，产生了大量到 redis 的 TCP 连接。查看一下 redis-py 的代码，很容易发现为什么每个工作子进程都新建了一个到 redis 的连接。redis-py 通过 <code>StrictRedis</code> 对象向 redis 发起命令时，首先调用 ConnectionPool 对象的 get_connection 方法获取一个可用的连接。在 <code>get_connection</code> 方法中，会首先调用 <code>_checkpid</code> 函数。<code>_checkpid</code> 检查 connnection_pool 的 pid与当前进程的pid是否一致，如果不相同，会关闭 connection_pool 中的所有连接，然后重新建立到 redis 的 TCP 连接。相关代码如下所示：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">StrictRedis</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">execute_command</span>(<span class="params">self, *args, **options</span>):</span><br><span class="line">        <span class="string">&quot;Execute a command and return a parsed response&quot;</span></span><br><span class="line">        pool = self.connection_pool</span><br><span class="line">        connection = pool.get_connection(command_name, **options)</span><br><span class="line">        <span class="comment"># connection send_command ...</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">ConnectionPool</span>(<span class="title class_ inherited__">object</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">get_connection</span>(<span class="params">self, command_name, *keys, **options</span>):</span><br><span class="line">        <span class="string">&quot;Get a connection from the pool&quot;</span></span><br><span class="line">        self._checkpid()</span><br><span class="line">        <span class="comment"># get connection ...</span></span><br><span class="line">        <span class="keyword">return</span> connection</span><br><span class="line"></span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">_checkpid</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">if</span> self.pid != os.getpid():</span><br><span class="line">            <span class="keyword">with</span> self._check_lock:</span><br><span class="line">                <span class="keyword">if</span> self.pid == os.getpid():</span><br><span class="line">                    <span class="comment"># another thread already did the work while we waited</span></span><br><span class="line">                    <span class="comment"># on the lock.</span></span><br><span class="line">                    <span class="keyword">return</span></span><br><span class="line">                self.disconnect()</span><br><span class="line">                self.reset()</span><br></pre></td></tr></table></figure><p>通过上述代码就很清楚为什么在 fork 工作模式下 redis 连接没有复用了，ConnectPool 对象的 pid 是父进程的 pid，在子进程中与子进程的 pid不同，于是到 redis 的连接被重置。</p><h2 id="fork-模型下共享-MySQL-连接合理么"><a href="#fork-模型下共享-MySQL-连接合理么" class="headerlink" title="fork 模型下共享 MySQL 连接合理么"></a>fork 模型下共享 MySQL 连接合理么</h2><p>不合理，会有很多问题。比如在子进程中到 MySQL 的 TCP 连接因为异常关闭（或者主动调用 <code>db.close()</code>），由于 copy-on-write 的特性，子进程中修改 *db &#x3D; None (*db 是 torndb 中保存到 MySQL连接的对象)并不会影响父进程的值，父进程再次 fork 出的子进程使用该 torndb 连接对象时就会出现 <code>OperationalError: (OperationalError) (2006, &#39;MySQL server has gone away&#39;)</code> 的错误。使用 uWSGI 就会有这样的使用场景，于是 uWSGI 有了 <code>lazy-apps</code> 的选项。</p><h2 id="为什么-rq-提供了基于-fork-的-worker-模型"><a href="#为什么-rq-提供了基于-fork-的-worker-模型" class="headerlink" title="为什么 rq 提供了基于 fork 的 worker 模型"></a>为什么 rq 提供了基于 fork 的 worker 模型</h2><p>回到最初的问题，现在需要在 rq 的任务中使用 MySQL 或者 redis 连接，如果使用 fork 模型的 worker，就需要每次重建一个 TCP 连接，这会带来很大的性能开销，通常是不可接受的。直接使用另外一种在主线程执行任务的 worker 似乎是更好的方案。那么为什么 rq 提供了基于 fork 的 worker 模型？rq 的作者给出了这样的理由：</p><blockquote><p>This mainly has to do with stability. When you spawn a child process (with fork(), or multiprocessing, or whatever) you get an isolated execution context, which has a few nice benefits. Some of which are: 1. If a process crashes (by a segfault in a C module for example), only the child crashes; 2. Additionally, the worker will always be responsive and can easily kill the child after a time out; 3. Also, memory leaks caused in the child can never affect the main worker. The child is killed after every job, so memory should never grow, even when running rqworker for long periods of time.</p></blockquote><p>rq 所看到的任务是一个可加载的 python 函数对象，执行任务时加载该对象并传入参数执行，对于可能出现的任务执行崩溃或内存泄漏等情况 rq 本身并不能处理（比如提到的 C 模块段错误，python 的 try-except 是无法捕捉的）。作为一个执行任务的通用库，fork-based worker 采用了一种保守的手段，通过进程级别的隔离保证了主进程的稳定运行。</p><h2 id="关于-rq-的使用场景"><a href="#关于-rq-的使用场景" class="headerlink" title="关于 rq 的使用场景"></a>关于 rq 的使用场景</h2><p>最后，谈一谈 rq 在不同场景下的使用。</p><p>当有很多小任务、每个任务可能需要等待IO，这种情况下使用非阻塞模型最适合了，比如 gevent。那么 rq 是否支持 gevent？目前是没有官方支持的，当然有一些第三方的扩展，需要注意的是使用 gevent 时最好是重写worker执行的入口，即 rqworker，因为如果只是在 -w 对应的 worker 类中使用 gevent，在 monkey patch 之前已经引用了一些模块，可能会有未知的问题。一些实现参考：<a href="https://github.com/zhangliyong/rq-gevent-worker">rq-gevent-worker</a>, <a href="https://gist.github.com/jhorman/e16ed695845fca683057">gevent_rqworker.py</a></p><p>另外一种场景，执行的任务是 CPU 密集型的，通常使用多进程比较合适。rq 对于支持使用多进程并发执行任务的 worker 也没有官方支持，一种解决方案是启动多个 rqorker 进程来从同一个任务队列消费任务；当然，也可以自己去扩展 rqworker。</p><p>总体而言，rq 代码本身实现得比较简洁，只支持 redis 作为队列存储任务，比较适合一些轻量级的异步任务处理。另一方面由于是一个通用库，一些具体场景下的需求就需要使用者自己来定制。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;最近使用了 &lt;a href=&quot;http://python-rq.org/&quot;&gt;rq&lt;/a&gt; 这个简单的队列处理库，其中有一些任务需要使用MySQL的连接或者redis的连接，对此有一些思考。&lt;/p&gt;
&lt;h2 id=&quot;MySQL-x2F-redis的连接复用&quot;&gt;&lt;a href=&quot;#MySQL-x2F-redis的连接复用&quot; class=&quot;headerlink&quot; title=&quot;MySQL&amp;#x2F;redis的连接复用&quot;&gt;&lt;/a&gt;MySQL&amp;#x2F;redis的连接复用&lt;/h2&gt;&lt;p&gt;rq 提供了两种 worker 模型：基于 &lt;code&gt;fork&lt;/code&gt; 的 worker 模型和直接在主线程执行任务的 worker 模型。基于 fork 的 worker 在执行任务之前先 fork 一个子进程，在子进程中执行具体的任务，父进程等待子进程执行返回。在基于 fork 的 worker 模型下，如果在父进程有一个 MySQL&amp;#x2F;redis 连接，由于子进程会继承父进程的地址空间，具有相同的打开文件、socket、管道等，所以子进程中也有同样的 MySQL&amp;#x2F;redis 连接，那么在这种情况下这个连接可以直接使用么？通过以下代码简单测试一下，连接 MySQL 使用 &lt;a href=&quot;https://github.com/bdarnell/torndb&quot;&gt;torndb&lt;/a&gt; ，连接 redis 使用 &lt;a href=&quot;https://github.com/andymccurdy/redis-py&quot;&gt;redis-py&lt;/a&gt;：&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="python" scheme="http://amyangfei.me/tags/python/"/>
    
    <category term="redis" scheme="http://amyangfei.me/tags/redis/"/>
    
    <category term="job queue" scheme="http://amyangfei.me/tags/job-queue/"/>
    
  </entry>
  
  <entry>
    <title>SSH through different kinds of proxy</title>
    <link href="http://amyangfei.me/2015/01/24/ssh-and-proxy/"/>
    <id>http://amyangfei.me/2015/01/24/ssh-and-proxy/</id>
    <published>2015-01-23T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>有时候因为网络、安全等原因，我们不能通过 ssh 直接连接到目标主机，而是需要通过代理服务器或跳板机实现连接。本文总结通过代理或跳板机使用 ssh 的各种方法，并且分析这些方法的基本原理。</p><p>我们设定本地主机的地址为 homepc，绑定有公网 ip；运行有各类代理的代理服务器或跳板机地址为 proxy-server，proxy-server 上绑定一个公网 ip，同时绑定一个内网 ip（假定为10.0.10.252）；需要连接的目标主机 target-server，绑定内网 ip（假定为 10.0.10.25）。所有的用户名、登录用户名使用 apple。</p><span id="more"></span><p>首先我们介绍一些常见的连接方法</p><h3 id="登录跳板机，在跳板机上连接目标主机"><a href="#登录跳板机，在跳板机上连接目标主机" class="headerlink" title="登录跳板机，在跳板机上连接目标主机"></a>登录跳板机，在跳板机上连接目标主机</h3><hr><ul><li>方法A：直接登录，可以通过 <code>-A</code> 选项利用Agent forwarding 特性</li></ul><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># now on homepc</span></span><br><span class="line">apple@homepc</span><br><span class="line">➜ ssh -A apple@proxy-server</span><br><span class="line"></span><br><span class="line"><span class="comment"># now on proxy-server</span></span><br><span class="line">apple@proxy-server</span><br><span class="line">➜ ssh apple@10.0.10.25</span><br></pre></td></tr></table></figure><ul><li>方法B：A useful trick，通过 <code>-tt</code> 强制分配 tty，直接执行 ssh 命令</li></ul><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">apple@homepc</span><br><span class="line">➜  ssh -A -tt apple@proxy-server ssh apple@10.0.10.25</span><br></pre></td></tr></table></figure><ul><li>方法C：利用 netcat 在跳板机上建立 tunnel，通过此 tunnel 连接目标主机</li></ul><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">apple@homepc</span><br><span class="line">➜  ssh -oProxyCommand=<span class="string">&#x27;ssh apple@proxy-server nc %h %p&#x27;</span> apple@10.0.10.25</span><br></pre></td></tr></table></figure><h3 id="借助-proxy-连接目标主机"><a href="#借助-proxy-连接目标主机" class="headerlink" title="借助 proxy 连接目标主机"></a>借助 proxy 连接目标主机</h3><hr><ul><li>方法D：本地 ssh 代理，在 proxy-server 上用户 apple 设有 nologin 的 shell 权限，不能通过 ssh 登录 proxy-server 但是可以进行 ssh 连接，通过 <code>-D</code> 进行本地的端口转发，详情可以查看 man ssh。</li></ul><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># run ssh daemon on homepc for local “dynamic” application-level port forwarding</span></span><br><span class="line">apple@homepc</span><br><span class="line">➜  ssh -N -D 12171 apple@proxy-server &amp;</span><br><span class="line"></span><br><span class="line">apple@homepc</span><br><span class="line">➜  ssh -oProxyCommand=<span class="string">&#x27;nc -x 127.0.0.1:12171 %h %p&#x27;</span> apple@10.0.10.25</span><br></pre></td></tr></table></figure><ul><li><p>方法E：类似于本地 ssh 代理的方式，可以在 proxy-server 上运行任何协议类型的代理，在 homepc 本地运行代理客户端连接 proxy-server 上的 proxy，在 ssh 的 ProxyCommand 指定为本地代理客户端的连接点即可。</p></li><li><p>方法F：利用 <a href="http://www.agroman.net/corkscrew/">corkscrew</a> ，<a href="https://packages.debian.org/source/sid/connect-proxy">connect-proxy</a>，<a href="https://github.com/rofl0r/proxychains-ng">proxychains</a> 等直接连接 proxy-server 上的代理。假定 proxy-server 上运行有 squid http 代理，代理使用用户名&#x2F;密码这种基本验证方式。corkscrew 仅支持 http 代理，connect-proxy 和 proxychains 支持 http, socks4, socks5 代理。proxychains 还支持 shell 内所有流量都通过代理，提供了更过的功能，这里不展开叙述。只简单看一下通过它们使用 http 代理连接 ssh 的情况。</p></li></ul><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># corkscrew can specify authfile with pattern of username:password for http proxy authentication</span></span><br><span class="line">apple@homepc</span><br><span class="line">➜  ssh -oProxyCommand=<span class="string">&#x27;corkscrew proxy-server 3128 %h %p ~/.ssh/authfile&#x27;</span> apple@10.0.10.25</span><br><span class="line"></span><br><span class="line"><span class="comment"># use connect-proxy</span></span><br><span class="line">apple@homepc</span><br><span class="line">➜  ssh -oProxyCommand=<span class="string">&#x27;connect -H apple@proxy-server:3128 %h %p&#x27;</span> apple@10.0.10.25</span><br><span class="line"></span><br><span class="line"><span class="comment"># use proxychains</span></span><br><span class="line"><span class="comment"># add &quot;http xxx.yyy.zzz.www 3128 apple apple&quot; to &quot;[ProxyList]&quot; node in proxychains config file</span></span><br><span class="line"><span class="comment"># xxx.yyy.zzz.www is the WAN ip of proxy-server. proxychains doesn&#x27;t support dns lookup for proxy server</span></span><br><span class="line"><span class="comment"># more details: https://github.com/rofl0r/proxychains-ng/issues/25</span></span><br><span class="line">apple@homepc</span><br><span class="line">➜  proxychains4 ssh apple@10.0.10.25</span><br></pre></td></tr></table></figure><h3 id="ProxyCommand"><a href="#ProxyCommand" class="headerlink" title="ProxyCommand"></a>ProxyCommand</h3><hr><p>关于 ProxyCommand 在此不多叙述，详情参考 <code>man ssh_config</code>。可以在 ~&#x2F;.ssh&#x2F;config 中配置 ProxyCommand，还可以根据不同的 host 配置不同的 ProxyCommand。</p><h3 id="原理分析"><a href="#原理分析" class="headerlink" title="原理分析"></a>原理分析</h3><hr><p>这些方法看起来有些眼花缭乱，但其实原理都很简单，除去登录到跳板机的情形，剩下场景的都是通过某种形式连接到代理服务器上的代理（或通过更多层的代理连接到代理服务器上的代理，形成一个代理链），由代理转发数据到目标服务器。</p><p>首先看方法C 的场景，参考<a href="http://backdrift.org/transparent-proxy-with-ssh">transparent-proxy-with-ssh</a></p><pre><code>    +--------+                  +--------------+                +---------------+    | homepc |                  | proxy-server |                | target-server |    |        | ===ssh=over=netcat=tunnel======================&gt; | 10.0.10.25    |    +--------+                  +--------------+                +---------------+</code></pre><p>该场景中，proxy-server 上实际运行有 <code>nc 10.0.10.25 22</code> 进程，该进程将会完成数据在 homepc 和 target-server 之间的转发。</p><p>方法D, E, F 中包含有明显的代理，以方法F 中的 corkscrew + squid http proxy 进行分析。</p><p>ssh 指定使用 ProxyCommand 之后，在建立连接时有这样一段关键代码：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// from openssh-5.9p1, sshconnect.c</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">ssh_connect</span><span class="params">(<span class="type">const</span> <span class="type">char</span> *host, <span class="keyword">struct</span> sockaddr_storage * hostaddr,</span></span><br><span class="line"><span class="params">    u_short port, <span class="type">int</span> family, <span class="type">int</span> connection_attempts, <span class="type">int</span> *timeout_ms,</span></span><br><span class="line"><span class="params">    <span class="type">int</span> want_keepalive, <span class="type">int</span> needpriv, <span class="type">const</span> <span class="type">char</span> *proxy_command)</span></span><br><span class="line">&#123;</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment">/* If a proxy command is given, connect using it. */</span></span><br><span class="line">        <span class="keyword">if</span> (proxy_command != <span class="literal">NULL</span>)</span><br><span class="line">            <span class="keyword">return</span> ssh_proxy_connect(host, port, proxy_command);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在 ssh_proxy_connect 中会 fork 出子进程来执行 ProxyCommand 中的命令，同时会重定向子进程的标准输入和标准输出，子进程的标准输入重定向到 pin[0]，所以子进程会通过 pin[1] 获得父进程标准输出的内容；子进程的标准输出重定向到 pout[1]，所以写到子进程标准输出的内容可以在父进程通过读取 pout[0] 获得。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// from openssh-5.9p1, sshconnect.c</span></span><br><span class="line"><span class="type">static</span> <span class="type">int</span></span><br><span class="line"><span class="title function_">ssh_proxy_connect</span><span class="params">(<span class="type">const</span> <span class="type">char</span> *host, u_short port, <span class="type">const</span> <span class="type">char</span> *proxy_command)</span></span><br><span class="line">&#123;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Fork and execute the proxy command. */</span></span><br><span class="line"><span class="keyword">if</span> ((pid = fork()) == <span class="number">0</span>) &#123;</span><br><span class="line">        ...</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Redirect stdin and stdout. */</span></span><br><span class="line">close(pin[<span class="number">1</span>]);</span><br><span class="line"><span class="keyword">if</span> (pin[<span class="number">0</span>] != <span class="number">0</span>) &#123;</span><br><span class="line"><span class="keyword">if</span> (dup2(pin[<span class="number">0</span>], <span class="number">0</span>) &lt; <span class="number">0</span>)</span><br><span class="line">perror(<span class="string">&quot;dup2 stdin&quot;</span>);</span><br><span class="line">close(pin[<span class="number">0</span>]);</span><br><span class="line">&#125;</span><br><span class="line">close(pout[<span class="number">0</span>]);</span><br><span class="line"><span class="keyword">if</span> (dup2(pout[<span class="number">1</span>], <span class="number">1</span>) &lt; <span class="number">0</span>)</span><br><span class="line">perror(<span class="string">&quot;dup2 stdout&quot;</span>);</span><br><span class="line"><span class="comment">/* Cannot be 1 because pin allocated two descriptors. */</span></span><br><span class="line">close(pout[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Stderr is left as it is so that error messages get</span></span><br><span class="line"><span class="comment">   printed on the user&#x27;s terminal. */</span></span><br><span class="line">argv[<span class="number">0</span>] = shell;</span><br><span class="line">argv[<span class="number">1</span>] = <span class="string">&quot;-c&quot;</span>;</span><br><span class="line">argv[<span class="number">2</span>] = command_string;</span><br><span class="line">argv[<span class="number">3</span>] = <span class="literal">NULL</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Execute the proxy command.  Note that we gave up any</span></span><br><span class="line"><span class="comment">   extra privileges above. */</span></span><br><span class="line">signal(SIGPIPE, SIG_DFL);</span><br><span class="line">execv(argv[<span class="number">0</span>], argv);</span><br><span class="line">perror(argv[<span class="number">0</span>]);</span><br><span class="line"><span class="built_in">exit</span>(<span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line">    ...</span><br><span class="line"><span class="comment">/* Close child side of the descriptors. */</span></span><br><span class="line">close(pin[<span class="number">0</span>]);</span><br><span class="line">close(pout[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* Set the connection file descriptors. */</span></span><br><span class="line">packet_set_connection(pout[<span class="number">0</span>], pin[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><pre><code> +----------+             +---------------+               +----------+              +---------------+ | terminal |  --------&gt;  | parent stdout |  ----------&gt;  |  pin[0]  |  ---------&gt;  |  child stdin  | |  input   |             |    pin[1]     |     read      |          |   redirect   |               | +----------+             +---------------+               +----------+              +---------------+ +----------+             +---------------+               +----------+              +---------------+ | terminal |  &lt;--------  | parent stdin  |  &lt;----------  |  pout[1] |  &lt;---------  |  child stdout | | display  |             |    pout[0]    |     read      |          |   redirect   |               | +----------+             +---------------+               +----------+              +---------------+</code></pre><p>上图描述了调用 ProxyCommand 时 ssh 客户端数据的流动情况，在我们的应用场景中，父进程对应 ssh 客户端进程，子进程运行 corkscrew。corkscrew 的实现很简单，它与代理服务器创建 tcp 连接，然后进入一个主循环，通过 select(2) 处理文件事件。<br>（注意 corkscrew 将与代理服务器协商的代码也写在主循环中，通过 setup 标志来确定处于建立连接后的协商阶段还是已经建立好到代理的连接，协商部分的代码可以抽离出来，类似的 connect-proxy 就是抽离出协商阶段和稳定连接阶段。下边分析的主循环略过协商阶段的代码。），这样处理文件读写事件的代码就非常简单：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// from corkscrew2.0, corkscrew.c</span></span><br><span class="line"><span class="keyword">for</span>(;;) &#123;</span><br><span class="line">    FD_ZERO(&amp;sfd);</span><br><span class="line">    FD_ZERO(&amp;rfd);</span><br><span class="line"></span><br><span class="line">    FD_SET(csock, &amp;rfd);</span><br><span class="line">    FD_SET(<span class="number">0</span>, &amp;rfd);</span><br><span class="line"></span><br><span class="line">    tv.tv_sec = <span class="number">5</span>;</span><br><span class="line">    tv.tv_usec = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(select(csock+<span class="number">1</span>,&amp;rfd,&amp;sfd,<span class="literal">NULL</span>,&amp;tv) == <span class="number">-1</span>) <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (FD_ISSET(csock, &amp;rfd)) &#123;</span><br><span class="line">        len = read(csock, buffer, <span class="keyword">sizeof</span>(buffer));</span><br><span class="line">        <span class="keyword">if</span> (len&lt;=<span class="number">0</span>) <span class="keyword">break</span>;</span><br><span class="line">        len = write(<span class="number">1</span>, buffer, len);</span><br><span class="line">        <span class="keyword">if</span> (len&lt;=<span class="number">0</span>) <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (FD_ISSET(<span class="number">0</span>, &amp;rfd)) &#123;</span><br><span class="line">        len = read(<span class="number">0</span>, buffer, <span class="keyword">sizeof</span>(buffer));</span><br><span class="line">        <span class="keyword">if</span> (len&lt;=<span class="number">0</span>) <span class="keyword">break</span>;</span><br><span class="line">        len = write(csock, buffer, len);</span><br><span class="line">        <span class="keyword">if</span> (len&lt;=<span class="number">0</span>) <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>corkscrew 的处理逻辑很清楚，从标准输入读取的数据，write 到 csock 中；从 csock 读取的数据，write 到标准输出。与 ssh 客户端结合起来，就可以得到下边的一张图：</p><pre><code> +--------------+             +------------+               +-----------------+          +---------+ | child stdin  |  --------&gt;  | corkscrew  |  ----------&gt;  | csock           |  -----&gt;  |  proxy  | | corkscrew    |    read     |            |     write     | conn with proxy |          |         | +--------------+             +------------+               +-----------------+          +---------+ +--------------+             +------------+               +-----------------+          +---------+ | child stdout |  &lt;--------  | corkscrew  |  &lt;----------  | csock           |  &lt;-----  |  proxy  | | corkscrew    |    write    |            |     read      | conn with proxy |          |         | +--------------+             +------------+               +-----------------+          +---------+</code></pre><p>从代理到目标服务器的数据收发与上述实现类似，只是 socket 有所不同，不再按照不同代理具体分析。使用不同的代理形式，只是在代理协商阶段有所不同，当稳定连接后，代理的工作就是不停的转发数据了。从数据的发送接收角度，加入代理后不影响 ssh 客户端和服务器之间传输数据的内容和顺序，因而可以将代理看做是透明的，就好像 ssh 客户端直接连接到目标服务器一样。</p><h3 id="问答"><a href="#问答" class="headerlink" title="问答"></a>问答</h3><p>TODO</p><ol><li>使用代理会不会存在安全问题？例如 <a href="http://www.unixwiz.net/techtips/ssh-agent-forwarding.html#sec">Security Issues With Key Agents</a> 提到的安全问题。</li><li>我使用 <a href="https://mosh.mit.edu/">mosh</a>，这些方法是否可以使用？</li><li>如果我使用公私钥登录的方式，代理服务器上需要进行哪些操作？</li></ol><h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><ol><li><a href="http://backdrift.org/transparent-proxy-with-ssh">Using SSH ProxyCommand to Tunnel Connections</a></li><li><a href="http://daniel.haxx.se/docs/sshproxy.html">SSH Through or Over Proxy</a></li><li><a href="http://www.agroman.net/corkscrew/">Corkscrew</a></li><li><a href="http://en.wikibooks.org/wiki/OpenSSH/Cookbook/Proxies_and_Jump_Hosts">OpenSSH&#x2F;Cookbook&#x2F;Proxies and Jump Hosts</a></li><li><a href="http://www.unixwiz.net/techtips/ssh-agent-forwarding.html">An Illustrated Guide to SSH Agent Forwarding</a></li><li><a href="http://www.zeitoun.net/articles/ssh-through-http-proxy/start">SSH through HTTP proxy</a></li><li><a href="http://www.lainme.com/doku.php/blog/2011/01/%E9%80%8F%E8%BF%87%E4%BB%A3%E7%90%86%E8%BF%9E%E6%8E%A5ssh">透过代理连接SSH</a></li></ol>]]></content>
    
    
    <summary type="html">&lt;p&gt;有时候因为网络、安全等原因，我们不能通过 ssh 直接连接到目标主机，而是需要通过代理服务器或跳板机实现连接。本文总结通过代理或跳板机使用 ssh 的各种方法，并且分析这些方法的基本原理。&lt;/p&gt;
&lt;p&gt;我们设定本地主机的地址为 homepc，绑定有公网 ip；运行有各类代理的代理服务器或跳板机地址为 proxy-server，proxy-server 上绑定一个公网 ip，同时绑定一个内网 ip（假定为10.0.10.252）；需要连接的目标主机 target-server，绑定内网 ip（假定为 10.0.10.25）。所有的用户名、登录用户名使用 apple。&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="proxy" scheme="http://amyangfei.me/tags/proxy/"/>
    
    <category term="ssh" scheme="http://amyangfei.me/tags/ssh/"/>
    
  </entry>
  
  <entry>
    <title>python 拾遗2</title>
    <link href="http://amyangfei.me/2014/12/04/python-tips-2/"/>
    <id>http://amyangfei.me/2014/12/04/python-tips-2/</id>
    <published>2014-12-03T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>本文是上一篇文章 <a href="/2014/11/27/python-tips/" target="_blank">python 拾遗</a> 的延续，继续整理 python 的一些使用技巧，以及一些可能被忽略的细节</p><p>注意: 以下讨论主要为 Python2.7 版本， Python 3 的内容有待跟进</p><span id="more"></span><h2 id="Get-MD5-hash-of-big-files"><a href="#Get-MD5-hash-of-big-files" class="headerlink" title="Get MD5 hash of big files"></a>Get MD5 hash of big files</h2><p>当我们需要通过 python 得到一个很大文件的 md5 值的时候，我们可以通过分段读取文件的方法来节约内存，选择合适的分段大小还会适当提高计算效率。<br><a href="https://gist.github.com/amyangfei/37b7d52003f38f8a3877" target="_blank">chksum.py</a> 通过 <code>memory_profiler</code> 统计执行过程中内存的使用情况并统计每一次计算的执行时间，同时给出了1Gb 数据的测试结果。</p><p>stackoverflow 上的一些讨论：<a href="http://stackoverflow.com/questions/1131220/get-md5-hash-of-big-files-in-python" target="_blank">Get MD5 hash of big files in Python</a>, <a href="http://stackoverflow.com/questions/519633/lazy-method-for-reading-big-file-in-python" target="_blank">Lazy Method for Reading Big File in Python</a></p><h2 id="io-BytesIO-vs-cString-StringIO"><a href="#io-BytesIO-vs-cString-StringIO" class="headerlink" title="io.BytesIO vs cString.StringIO"></a>io.BytesIO vs cString.StringIO</h2><p>python2 和 python3 在 StringIO 和 BytesIO 之间有诸多不同，<a href="https://pypi.python.org/pypi/six" target="_blank">six</a> 是一个提供同时兼容 py2 和 py3 的解决方案，这个几个模块的具体区别参考下边的表格。</p><table><thead><tr><th>模块</th><th>Python 2</th><th>Python 3</th></tr></thead><tbody><tr><td>StringIO.StringIO</td><td>内存中的字符串缓存，可以存储字符串或Unicode 类型</td><td>删除</td></tr><tr><td>cStringIO.StringIO</td><td>基于C实现提供类似StringIO.StringIO的接口且更高效，但是相比StringIO.StringIO使用有一定限制</td><td>删除</td></tr><tr><td>io.StringIO</td><td>对 Unicode文本内容的内存缓存，只能存储 Unicode 对象</td><td>对文本数据的内存缓存，不能接收 Unicode 类型</td></tr><tr><td>io.BytesIO</td><td>存储字节的内存缓存</td><td>存储字节的内存缓存</td></tr><tr><td>six.StringIO</td><td>StringIO.StringIO</td><td>io.StringIO</td></tr><tr><td>six.BytesIO</td><td>StringIO.StringIO</td><td>io.BytesIO</td></tr></tbody></table><p>在性能上：通常 cStringIO.StringIO 是最快的。io.Bytes 同样是通过 C 实现的，但是例如通过 <code>io.BytesIO(b'data')</code> 初始化 BytesIO 对象时会对数据进行一次复制，这会引起性能上的损失。</p><p>关于 StringIO 和 BytesIO 的性能区别，对于 IO 性能敏感的场景还是有很大影响，例如在 <a href="https://github.com/tornadoweb/tornado/issues/1110" target="_blank">tornado</a>，<a href="https://github.com/scrapy/scrapy/pull/803" target="_blank">scrapy</a> 的项目中以及 <a href="https://mail.python.org/pipermail//python-dev/2014-July/135542.html" target="_blank">Python 邮件列表</a> 中都有相关讨论。<br>在未来 Python3.5 版本中将会对 io.BytesIO 进行 copy-on-write 的优化，详见：<a href="http://bugs.python.org/issue22003" target="_blank">Python Issue22003</a>。</p><p>当具体需要创建 file-like 的数据流时并且需要考虑对 Python2 和 Python3 代码的兼容性时，我们需要根据具体的数据类型（字符串或者 Unicode 或者 Bytes），以及使用场景对性能的要求选择合适的模块。</p><h2 id="List-comprehensions-leak-the-loop-control-variable"><a href="#List-comprehensions-leak-the-loop-control-variable" class="headerlink" title="List comprehensions leak the loop control variable"></a>List comprehensions leak the loop control variable</h2><p>看一段很简单的列表生成的代码：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = <span class="string">&#x27;before&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>)]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x</span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x = <span class="string">&#x27;before&#x27;</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = (x <span class="keyword">for</span> x <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">5</span>))</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>x</span><br><span class="line"><span class="string">&#x27;before&#x27;</span></span><br></pre></td></tr></table></figure><p>在 python2.x 中，list comprehension 中变量的作用域并不仅限于 [] 中，而是会泄露出来，而 Generator expressions 执行时会创建一个独立的运行域，因而不会发生变量泄露。在 Python3 中 list comprehension 变量泄露已经得到了修改。</p><p>下边是 <a href="http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html" target="_blank">Python History</a> 中的原文</p><blockquote><p>This was an artifact of the original implementation of list comprehensions; it was one of Python’s “dirty little secrets” for years. It started out as an intentional compromise to make list comprehensions blindingly fast, and while it was not a common pitfall for beginners, it definitely stung people occasionally. For generator expressions we could not do this. Generator expressions are implemented using generators, whose execution requires a separate execution frame. Thus, generator expressions (especially if they iterate over a short sequence) were less efficient than list comprehensions.</p></blockquote><h2 id="socket-settimeout-value"><a href="#socket-settimeout-value" class="headerlink" title="socket.settimeout(value)"></a>socket.settimeout(value)</h2><p>socket 设置超时之后，该 socket 就是 non-blocking 模式</p><blockquote><p><strong>Timeout mode internally sets the socket in non-blocking mode.</strong> The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects returned by the makefile() method must only be used when the socket is in blocking mode; in timeout or non-blocking mode file operations that cannot be completed immediately will fail.</p></blockquote>]]></content>
    
    
    <summary type="html">&lt;p&gt;本文是上一篇文章 &lt;a href=&quot;/2014/11/27/python-tips/&quot; target=&quot;_blank&quot;&gt;python 拾遗&lt;/a&gt; 的延续，继续整理 python 的一些使用技巧，以及一些可能被忽略的细节&lt;/p&gt;
&lt;p&gt;注意: 以下讨论主要为 Python2.7 版本， Python 3 的内容有待跟进&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="python" scheme="http://amyangfei.me/tags/python/"/>
    
  </entry>
  
  <entry>
    <title>python 拾遗</title>
    <link href="http://amyangfei.me/2014/11/27/python-tips/"/>
    <id>http://amyangfei.me/2014/11/27/python-tips/</id>
    <published>2014-11-26T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>整理 python 使用的一些技巧，以及一些可能被忽略的细节，很多在文档可以查找到的内容将不会过多的描述，更多以外链的形式存在。</p><p>注意: 以下讨论主要为 Python2.7 版本， Python 3 的内容有待跟进</p><span id="more"></span><h3 id="import"><a href="#import" class="headerlink" title="import"></a>import</h3><p>python 的 import 通过调用 <code>_<em>import</em>_(name[, globals[, locals[, fromlist[, level]]]])</code> 这个函数实现，借助这个函数可以通过 python 模块的名字动态引用模块。来自tornado 的 <a href="http://tornado.readthedocs.org/en/latest/_modules/tornado/util.html#import_object" target="_blank">import_object</a> 是一个很简洁的封装。</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">import_object</span>(<span class="params">name</span>):</span><br><span class="line">    <span class="string">&quot;&quot;&quot;Imports an object by name.</span></span><br><span class="line"><span class="string">    import_object(&#x27;x&#x27;) is equivalent to &#x27;import x&#x27;.</span></span><br><span class="line"><span class="string">    import_object(&#x27;x.y.z&#x27;) is equivalent to &#x27;from x.y import z&#x27;.</span></span><br><span class="line"><span class="string">    &quot;&quot;&quot;</span></span><br><span class="line">    <span class="keyword">if</span> name.count(<span class="string">&#x27;.&#x27;</span>) == <span class="number">0</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">__import__</span>(name, <span class="literal">None</span>, <span class="literal">None</span>)</span><br><span class="line"></span><br><span class="line">    parts = name.split(<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">    obj = <span class="built_in">__import__</span>(<span class="string">&#x27;.&#x27;</span>.join(parts[:-<span class="number">1</span>]), <span class="literal">None</span>, <span class="literal">None</span>, [parts[-<span class="number">1</span>]], <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">getattr</span>(obj, parts[-<span class="number">1</span>])</span><br><span class="line">    <span class="keyword">except</span> AttributeError:</span><br><span class="line">        <span class="keyword">raise</span> ImportError(<span class="string">&quot;No module named %s&quot;</span> % parts[-<span class="number">1</span>])</span><br></pre></td></tr></table></figure><p>除此之外，我们还可以利用 python2.7 开始提供的 <a href="https://docs.python.org/2/library/importlib.html" target="_blank">importlib.import_module</a> （<a href="http://svn.python.org/projects/python/trunk/Lib/importlib/__init__.py" target="_blank">实现代码</a>）来进行动态引用。例如：<code>importlib.import_module('tornado.httpclient')</code></p><h3 id="reload"><a href="#reload" class="headerlink" title="reload"></a>reload</h3><p>当 reload 一个 python 模块之后有两处不会使用新的模块的值：</p><ol><li><p>原来已经使用的实例还是会使用旧的模块，而新生产的实例会使用新的模块；</p></li><li><p>其他模块引用该模块的对象，这些引用不会绑定到新的对象上。</p></li></ol><p><a href="https://github.com/jparise/python-reloader" target="_blank">python-reloader</a> 是一个很有趣的项目，它将 <code>__builtin__.__import__</code> 修改为自定义的 <code>_import</code> 函数，新的 <code>_import</code> 在原有调用 <code>_<em>import</em>_(name[, globals[, locals[, fromlist[, level]]]])</code> 的同时记录下引用模块之间的依赖关系。python-reloader 实现的是 reload 一个模块之后，reload 该模块所依赖的所有模块，而不是 reload 所有依赖该模块的模块。说起来很绕，这里 <a href="https://github.com/jparise/python-reloader/issues/14" target="_blank">issue(It should reload dependants instead of dependencies)</a>有很好的讨论。在实际运行的系统中动态 reload 模块可能并非一种很好的选择。</p><h3 id="Catching-an-exception-while-using-‘with’"><a href="#Catching-an-exception-while-using-‘with’" class="headerlink" title="Catching an exception while using ‘with’"></a>Catching an exception while using ‘with’</h3><p>当我们使用 with 表达式并且需要捕捉异常的时候，我们可以这样做：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    <span class="keyword">with</span> <span class="built_in">open</span>( <span class="string">&quot;foo.txt&quot;</span> ) <span class="keyword">as</span> f :</span><br><span class="line">        <span class="built_in">print</span> f.readlines()</span><br><span class="line"><span class="keyword">except</span> EnvironmentError: <span class="comment"># parent of IOError, OSError</span></span><br><span class="line">    <span class="built_in">print</span> <span class="string">&#x27;oops&#x27;</span></span><br></pre></td></tr></table></figure><p>如果希望捕捉 with 表达式的异常与内部工作代码的异常分离出来，我们可以这样做：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    f = <span class="built_in">open</span>(<span class="string">&#x27;foo.txt&#x27;</span>)</span><br><span class="line"><span class="keyword">except</span> IOError:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&#x27;oops&#x27;</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="keyword">with</span> f:</span><br><span class="line">        <span class="built_in">print</span> f.readlines()</span><br></pre></td></tr></table></figure><p>关于 python 使用 try-except-else, with 的一些讨论：<a href="http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python" target="_blank">Is it a good practice to use try-except-else</a>，<a href="http://stackoverflow.com/questions/3642080/using-python-with-statement-with-try-except-block" target="_blank">Using python “with” statement with try-except block</a></p><h3 id="StringIO"><a href="#StringIO" class="headerlink" title="StringIO"></a>StringIO</h3><p>当我们使用一些接收参数是文件类型的 API 时，我们可能需要使用到 StringIO，例如使用 gzip 模块压缩一个字符串：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> gzip, StringIO</span><br><span class="line"></span><br><span class="line">stringio = StringIO.StringIO()</span><br><span class="line">gzip_file = gzip.GzipFile(fileobj=stringio, mode=<span class="string">&#x27;w&#x27;</span>)</span><br><span class="line">gzip_file.write(<span class="string">&#x27;Hello World&#x27;</span>)</span><br><span class="line">gzip_file.close()</span><br><span class="line"></span><br><span class="line">stringio.getvalue()</span><br></pre></td></tr></table></figure><p>在 Python2.7 中 <a href="https://docs.python.org/2/library/stringio.html#module-cStringIO" target="_blank">cStringIO</a> 提供了与 StringIO 类似的接口，并且运行效率更高。在 Python3.4 中这两者被统一成为了 io.StringIO。</p><p>注意：cStringIO 的使用有一些限制：cStringIO 不能作为基类被继承；cStringIO 不能接收非 ASCII 字符的字符串参数；还有一点与 StringIO 不同的是当使用字符串参数初始化一个 cStringIO 对象时，该对象是只读的。</p><h3 id="Queue-Queue-vs-collections-deque"><a href="#Queue-Queue-vs-collections-deque" class="headerlink" title="Queue.Queue vs collections.deque"></a>Queue.Queue vs collections.deque</h3><p>Queue (python3 重命名为 queue)是一个可用于多线程之间同步、交换数据的队列模块，包括 FIFO，LIFO，优先级队列三个实现。</p><p>collections.deque 是一个双端队列的数据结构，在头和尾的插入、删除、读取操作是O(1)复杂度；在队列中部的随机读取操作是O(n)的。</p><p>reference：<a href="http://stackoverflow.com/questions/717148/python-queue-queue-vs-collections-deque" target="_blank">Python: Queue.Queue vs. collections.deque</a></p><h3 id="heapq"><a href="#heapq" class="headerlink" title="heapq"></a>heapq</h3><p>python 内置的 heapq 是一个小顶堆，并且 <code>heapify</code>, <code>heappush</code>, <code>heappop</code> 操作是不支持传递 <code>key</code> 参数的。如果想实现大顶堆，可以这样 <code>lambda x: -x</code>，或者自己封装一层。例如：<br><a href="http://stackoverflow.com/a/14189741/1115857" target="_blank">python topN max heap</a>。另外，<code>heapq.nlargest</code> 和 <code>heapq.nsmallest</code> 支持 key 参数。<br>邮件列表里的讨论：<a href="http://code.activestate.com/lists/python-list/162387/" target="_blank">为什么 python 的 heapq 没有支持 key 参数</a></p><h3 id="itertools-tee"><a href="#itertools-tee" class="headerlink" title="itertools.tee"></a>itertools.tee</h3><p><code>itertools.tee</code> 从一个迭代器返回 n 个独立的迭代器，原始迭代器将不允许被使用，如果使用，那么可能会导致新的迭代器失效。<a href="http://discontinuously.com/2012/06/inside-python-tee/" target="_blank">Inside Python’s itertools.tee</a> 很详细的探究了 <code>itertools.tee</code> 的实现细节。</p><h3 id="when-should-we-use-operator"><a href="#when-should-we-use-operator" class="headerlink" title="when should we use operator"></a>when should we use operator</h3><p>最常用的就是 <code> operator.itemgetter</code>，例如我们有一个 tuple 列表，需要对这些元组按照第i个元素排序，那么可以这样：<code>lst.sort(key=operator.itemgetter(i))</code>。</p><p><code>operator.add</code> 与 <code>lambda x, y: x+y</code> 具有相同的效果，二者的不同主要有两个方面：一方面是它们的可读性、开发者的使用习惯的差别；另一方面是性能差别。在<a href="https://wiki.python.org/moin/PythonSpeed" target="_blank">python wiki</a> 中有这样一段话：</p><blockquote><p>Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).</p></blockquote><p>我们对二者做一次简单的实验对比：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">➜ python -m timeit <span class="string">&#x27;import operator&#x27;</span> <span class="string">&#x27;map(operator.add, [x for x in range(5000)], [y for y in range(5000)])&#x27;</span></span><br><span class="line"><span class="number">1000</span> loops, best of <span class="number">3</span>: <span class="number">710</span> usec per loop</span><br><span class="line"></span><br><span class="line">➜ python3 -m timeit <span class="string">&#x27;import operator&#x27;</span> <span class="string">&#x27;map(operator.add, [x for x in range(5000)], [y for y in range(5000)])&#x27;</span></span><br><span class="line"><span class="number">1000</span> loops, best of <span class="number">3</span>: <span class="number">401</span> usec per loop</span><br><span class="line"></span><br><span class="line">➜ python -m timeit <span class="string">&#x27;map(lambda x,y:x+y, [x for x in range(5000)], [y for y in range(5000)])&#x27;</span></span><br><span class="line"><span class="number">100</span> loops, best of <span class="number">3</span>: <span class="number">929</span> usec per loop</span><br><span class="line"></span><br><span class="line">➜ python3 -m timeit <span class="string">&#x27;map(lambda x,y:x+y, [x for x in range(5000)], [y for y in range(5000)])&#x27;</span></span><br><span class="line"><span class="number">1000</span> loops, best of <span class="number">3</span>: <span class="number">397</span> usec per loop</span><br></pre></td></tr></table></figure><p>实验结果中，在 Python2.7 环境下 <code>operator.add</code> 稍微快于使用 lambda 表达式，在 Python3 环境下两者几乎没有差别。事实上 Python 并不适合 CPU 密集型的应用场景，当 CPU 不是性能瓶颈时，operator 和 lambda 之间的性能差距基本可以忽略。</p>]]></content>
    
    
    <summary type="html">&lt;p&gt;整理 python 使用的一些技巧，以及一些可能被忽略的细节，很多在文档可以查找到的内容将不会过多的描述，更多以外链的形式存在。&lt;/p&gt;
&lt;p&gt;注意: 以下讨论主要为 Python2.7 版本， Python 3 的内容有待跟进&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="python" scheme="http://amyangfei.me/tags/python/"/>
    
  </entry>
  
  <entry>
    <title>Making Ebooks of Pro Git</title>
    <link href="http://amyangfei.me/2014/01/10/making-progit-ebook/"/>
    <id>http://amyangfei.me/2014/01/10/making-progit-ebook/</id>
    <published>2014-01-09T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<p>Pro Git 是一本用来学习 git 使用很不错的书，从 <a href="https://github.com/progit/progit" target="_blank">progit</a> 这个开源项目可以获得这本书的全部内容，下边介绍在 Ubuntu Server 12.04 环境下制作电子书的过程。</p><h2 id="安装依赖"><a href="#安装依赖" class="headerlink" title="安装依赖"></a>安装依赖</h2><h3 id="1-ruby-rubygems"><a href="#1-ruby-rubygems" class="headerlink" title="1. ruby, rubygems"></a>1. ruby, rubygems</h3><p>参考 Ruby-China 的 <a href="http://ruby-china.org/wiki/install-rails-on-ubuntu-12-04-server" target="_blank">wiki</a></p><h3 id="2-rdiscount"><a href="#2-rdiscount" class="headerlink" title="2. rdiscount"></a>2. rdiscount</h3><p>markdown 使用的模板，通过 rubygems 安装</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">$ gem install rdiscount</span><br><span class="line"></span><br></pre></td></tr></table></figure><h3 id="3-calibre"><a href="#3-calibre" class="headerlink" title="3. calibre"></a>3. calibre</h3><p><a href="http://en.wikipedia.org/wiki/Calibre_(software)" target="_blank">calibre</a> 是一款开源的电子书管理软件，生成 epub 或 mobi 格式需要安装。</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">$ sudo apt-get install calibre</span><br><span class="line"></span><br></pre></td></tr></table></figure><span id="more"></span><h3 id="4-pandoc，xelatex"><a href="#4-pandoc，xelatex" class="headerlink" title="4. pandoc，xelatex"></a>4. pandoc，xelatex</h3><p>生成 pdf 格式需要安装这两个依赖，pandoc 安装比较简单，直接apt；安装 xelatex 则需要首先安装 texlive-xetex，然后打上 LaTeX::Driver 补丁（参考了这个网址 <a href="http://ledgersmb.org/faq/xelatex" target="_blank">Frequently Asked Questions - XeLaTeX</a> ）。</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">$ sudo apt-get install pandoc</span><br><span class="line">$ sudo apt-get install texlive-xetex texlive-latex-base texlive-latex-extra</span><br><span class="line">$ sudo apt-get install liblatex-&#123;driver,encode,table&#125;-perl</span><br><span class="line"></span><br></pre></td></tr></table></figure><h3 id="5-install-font"><a href="#5-install-font" class="headerlink" title="5. install font"></a>5. install font</h3><p>生成 pdf 时读取 latex&#x2F;config.yml 中的配置，使用过程中可能会出现一些字体不存在的错误。比如：</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">./makepdf en</span><br><span class="line">en:</span><br><span class="line">        Parsing markdown... <span class="keyword">done</span></span><br><span class="line">        Creating main.tex <span class="keyword">for</span> en... <span class="keyword">done</span></span><br><span class="line">        Running XeTeX:</span><br><span class="line">                Pass 1... failed with:</span><br><span class="line">                        ! I can<span class="string">&#x27;t find file `Helvetica&#x27;</span>.</span><br><span class="line">        Consider running this again with --debug.</span><br></pre></td></tr></table></figure><p>这个错误的原因是 Ubuntu 系统中 Helvetica 字体名字为 Nimbus Sans L，修改 confi.yml 文件default 节点下的 font 值即可。</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ fc-match <span class="string">&quot;Helvetica Neue&quot;</span></span><br><span class="line">DejaVuSans.ttf: <span class="string">&quot;DejaVu Sans&quot;</span> <span class="string">&quot;Book&quot;</span></span><br><span class="line">$ fc-match <span class="string">&quot;Helvetica&quot;</span></span><br><span class="line">n019003l.pfb: <span class="string">&quot;Nimbus Sans L&quot;</span> <span class="string">&quot;Regular&quot;</span></span><br></pre></td></tr></table></figure><p>生成中文pdf时同样遇到了中文字体不存在的情况，默认的配置文件使用的是 AR PL UMing CN 和 AR PL UKai CN，直接安装即可。但是我个人感觉 AR PL UMing CN 字体太细瘦，换成了文泉驿微米黑字体，圆润多了。</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sudo apt-get install ttf-arphic-ukai    <span class="comment"># &quot;AR PL UKai&quot; 文鼎PL中楷</span></span><br><span class="line">sudo apt-get install ttf-arphic-uming<span class="comment"># &quot;AR PL UMing&quot; 文鼎PL细上海宋</span></span><br><span class="line">sudo apt-get install ttf-wqy-microhei<span class="comment"># &quot;WenQuanYi Micro Hei&quot; 文泉驿微米黑</span></span><br></pre></td></tr></table></figure><h2 id="make"><a href="#make" class="headerlink" title="make"></a>make</h2><p>最后一步，生成电子书，好书一本，细细品读，Enjoy！</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ ./makeebooks en<span class="comment"># 默认生成mobi格式，en英文</span></span><br><span class="line">$ <span class="built_in">export</span> FORMAT=epub<span class="comment"># 设置FORMAT为epub，生成epub格式</span></span><br><span class="line">$ ./makeebooks zh<span class="comment"># 生成epub格式，zh中文</span></span><br><span class="line">$ ./makepdfs zh<span class="comment"># 生成pdf</span></span><br></pre></td></tr></table></figure>]]></content>
    
    
    <summary type="html">&lt;p&gt;Pro Git 是一本用来学习 git 使用很不错的书，从 &lt;a href=&quot;https://github.com/progit/progit&quot; target=&quot;_blank&quot;&gt;progit&lt;/a&gt; 这个开源项目可以获得这本书的全部内容，下边介绍在 Ubuntu Server 12.04 环境下制作电子书的过程。&lt;/p&gt;
&lt;h2 id=&quot;安装依赖&quot;&gt;&lt;a href=&quot;#安装依赖&quot; class=&quot;headerlink&quot; title=&quot;安装依赖&quot;&gt;&lt;/a&gt;安装依赖&lt;/h2&gt;&lt;h3 id=&quot;1-ruby-rubygems&quot;&gt;&lt;a href=&quot;#1-ruby-rubygems&quot; class=&quot;headerlink&quot; title=&quot;1. ruby, rubygems&quot;&gt;&lt;/a&gt;1. ruby, rubygems&lt;/h3&gt;&lt;p&gt;参考 Ruby-China 的 &lt;a href=&quot;http://ruby-china.org/wiki/install-rails-on-ubuntu-12-04-server&quot; target=&quot;_blank&quot;&gt;wiki&lt;/a&gt;&lt;/p&gt;
&lt;h3 id=&quot;2-rdiscount&quot;&gt;&lt;a href=&quot;#2-rdiscount&quot; class=&quot;headerlink&quot; title=&quot;2. rdiscount&quot;&gt;&lt;/a&gt;2. rdiscount&lt;/h3&gt;&lt;p&gt;markdown 使用的模板，通过 rubygems 安装&lt;/p&gt;
&lt;figure class=&quot;highlight bash&quot;&gt;&lt;table&gt;&lt;tr&gt;&lt;td class=&quot;gutter&quot;&gt;&lt;pre&gt;&lt;span class=&quot;line&quot;&gt;1&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;2&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;3&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;code&quot;&gt;&lt;pre&gt;&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;$ gem install rdiscount&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/figure&gt;

&lt;h3 id=&quot;3-calibre&quot;&gt;&lt;a href=&quot;#3-calibre&quot; class=&quot;headerlink&quot; title=&quot;3. calibre&quot;&gt;&lt;/a&gt;3. calibre&lt;/h3&gt;&lt;p&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Calibre_(software)&quot; target=&quot;_blank&quot;&gt;calibre&lt;/a&gt; 是一款开源的电子书管理软件，生成 epub 或 mobi 格式需要安装。&lt;/p&gt;
&lt;figure class=&quot;highlight bash&quot;&gt;&lt;table&gt;&lt;tr&gt;&lt;td class=&quot;gutter&quot;&gt;&lt;pre&gt;&lt;span class=&quot;line&quot;&gt;1&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;2&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;3&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;/td&gt;&lt;td class=&quot;code&quot;&gt;&lt;pre&gt;&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;$ sudo apt-get install calibre&lt;/span&gt;&lt;br&gt;&lt;span class=&quot;line&quot;&gt;&lt;/span&gt;&lt;br&gt;&lt;/pre&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/figure&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
  </entry>
  
  <entry>
    <title>APScheduler 源码阅读笔记</title>
    <link href="http://amyangfei.me/2013/11/06/apscheduler-source-analyse/"/>
    <id>http://amyangfei.me/2013/11/06/apscheduler-source-analyse/</id>
    <published>2013-11-05T16:00:00.000Z</published>
    <updated>2022-02-19T06:30:27.604Z</updated>
    
    <content type="html"><![CDATA[<h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p>APScheduler 是由 python 实现的一个轻量级任务调度器，它可以按照一定间隔（IntervalTrigger）、指定时间（2.1中的SimpleTrigger&#x2F;3.0中的DateTrigger）或者以类似 cron（CronTrigger） 的形式触发待执行任务（即调用函数或者调用 python 的 callable 对象）。现在 pypi 上的稳定版是 <a href="https://pypi.python.org/pypi/APScheduler/2.1.1" target="_blank">APScheduler 2.1.1</a>，3.0 版本在 class Scheduler 中移除了针对不同 trigger 的 add_trigger_job() 接口，统一为 add_job()，但是底层实现变化不大。我主要看了 2.1.1 的代码。代码很简洁，加起来一共2049行。</p><h3 id="模块组织"><a href="#模块组织" class="headerlink" title="模块组织"></a>模块组织</h3><ul><li><p><strong>Scheduler</strong>  调度器的核心部分，负责对 job 的管理和调度，用户使用添加&#x2F;移除任务，启动调度器都通过 Scheduler 提供的接口完成。</p></li><li><p><strong>Job</strong>  封装了需要调度的任务，每一个 Job 实例是在 Scheduler 添加 job 时被初始化，具体的初始化参数决定了调度被触发的形式（3类不同的trigger）。</p></li><li><p><strong>Trigger</strong>  包含 SimpleTrigger，IntervalTrigger和 CronTrigger 三个类。Trigger 的作用就是计算下一次触发任务的时间。</p></li><li><p><strong>JobStore</strong>  抽象基类，针对任务存储的介质有多个实现，包括基于内存（RAMJobStore）、使用shelve的简单持久化存储（ShelveJobStore）、使用数据库存储（RedisJobStore，MongoDBJobStore）等。如果不指定参数默认使用 RAMJobStore，使用持久化的 JobStore 的目的是在 Scheduler 重启之后能够恢复原有的任务调度。</p></li></ul><h3 id="底层实现"><a href="#底层实现" class="headerlink" title="底层实现"></a>底层实现</h3><p>从分析 Scheduler 类入手，首先看项目中自带的example：</p><span id="more"></span><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">from</span> datetime <span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> apscheduler.scheduler <span class="keyword">import</span> Scheduler</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">def</span> <span class="title function_">tick</span>():</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;Tick! The time is: %s&#x27;</span> % datetime.now())</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    scheduler = Scheduler(standalone=<span class="literal">True</span>)</span><br><span class="line">    scheduler.add_interval_job(tick, seconds=<span class="number">3</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;Press Ctrl+C to exit&#x27;</span>)</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        scheduler.start()</span><br><span class="line">    <span class="keyword">except</span> (KeyboardInterrupt, SystemExit):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br></pre></td></tr></table></figure><p>上边代码的最核心的三行就是初始化Scheduler，添加以interval为触发的 job 和启动scheduler。这也是使用APScheduler 最基本也最主要的方式。</p><p>初始化 Scheduler 有很多参数可以选择（详细可以参考 <a href="http://apscheduler.readthedocs.org/en/v2.1.0/#scheduler-configuration-options" target="_blank">scheduler-configuration-options</a>），这里简单介绍 standalone 和 daemonic 两个参数。standalone 设置为 False，那么 scheduler 将会以 embedded 模式运行，该模式下调度器会在一个新的线程中运行调度循环(_main_loop)；如果 standlone 设置为True，那么 scheduler 会阻塞当前线程，执行调度循环，直到不再有调度任务后返回，被阻塞的线程继续运行。daemonic 即是否以守护线程运行 scheduler，与python 守护线程的效果一致，如果 daemonic 设置为 False，显然该参数在 embedded 模式（standalone&#x3D;&#x3D;False）下才有效果。Scheduler 默认的运行参数是 standalone &#x3D;&#x3D; False, daemonic &#x3D;&#x3D; True，即以 embedded 模式的守护线程中运行调度循环。</p><p>start 是启动 scheduler 的方法，如下所示。代码很简洁，启动前读取所有 job_store 中pending job（pending job 是 scheduler 未启动前添加的job），如果为 standalone 模式，会直接进入 _main_loop 调度循环，否则在新的线程中运行调度循环。</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">start</span>(<span class="params">self</span>):</span><br><span class="line">    <span class="keyword">if</span> self.running:</span><br><span class="line">        <span class="keyword">raise</span> SchedulerAlreadyRunningError</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Create a RAMJobStore as the default if there is no default job store</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> <span class="string">&#x27;default&#x27;</span> <span class="keyword">in</span> self._jobstores:</span><br><span class="line">        self.add_jobstore(RAMJobStore(), <span class="string">&#x27;default&#x27;</span>, <span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Schedule all pending jobs</span></span><br><span class="line">    <span class="keyword">for</span> job, jobstore <span class="keyword">in</span> self._pending_jobs:</span><br><span class="line">        self._real_add_job(job, jobstore, <span class="literal">False</span>)</span><br><span class="line">    <span class="keyword">del</span> self._pending_jobs[:]</span><br><span class="line"></span><br><span class="line">    self._stopped = <span class="literal">False</span></span><br><span class="line">    <span class="keyword">if</span> self.standalone:</span><br><span class="line">        self._main_loop()</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        self._thread = Thread(target=self._main_loop, name=<span class="string">&#x27;APScheduler&#x27;</span>)</span><br><span class="line">        self._thread.setDaemon(self.daemonic)</span><br><span class="line">        self._thread.start()</span><br></pre></td></tr></table></figure><p>_main_loop 就是调度循环，主体就是一个 while 循环。</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> <span class="keyword">not</span> self._stopped:</span><br><span class="line">    logger.debug(<span class="string">&#x27;Looking for jobs to run&#x27;</span>)</span><br><span class="line">    now = datetime.now()</span><br><span class="line">    next_wakeup_time = self._process_jobs(now)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Sleep until the next job is scheduled to be run, a new job is added or the scheduler is stopped</span></span><br><span class="line">    <span class="keyword">if</span> next_wakeup_time <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">        wait_seconds = time_difference(next_wakeup_time, now)</span><br><span class="line">        self._wakeup.wait(wait_seconds)</span><br><span class="line">        self._wakeup.clear()</span><br><span class="line">    <span class="keyword">elif</span> self.standalone:</span><br><span class="line">        self.shutdown()</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        self._wakeup.wait()</span><br><span class="line">        self._wakeup.clear()</span><br></pre></td></tr></table></figure><p>进入循环后首先调用 <code>_process_jobs</code> 处理任务，以此处理不同 job_store 中的 每一个 job。在处理 job 过程中首先通过 <code>get_run_times</code> 获取 run_times（<code>get_run_times</code> 很有趣，它获取在 next_run_time 和 now 之间所有需要进行任务调度的时间点，之所以这样做的原因是 APScheduler 允许设定一个 misfire_grace_time 时间，也就是事件执行的延迟时间，因为有很多原因会导致计划调度不能准确在设定好的时间执行。）<code>_process_jobs</code> 处理很简单，将 job 的执行调度交给 scheduler 的线程池，针对每一个 job 的触发会开启一个新的线程（一个疑问：这个线程设置了 <code>t.setDaemon(True)</code>，但是文档上却说”Jobs are always executed in non-daemonic threads.”）来执行，而实际的任务执行发生在 Scheduler 的 <code>_run_job</code> 方法中。</p><p><code>_process_jobs</code> 会返回下次执行调度的时间，调度循环会根据返回值进行相应的处理，wait 指定时间、或一直 wait 等待事件通知唤醒、或退出循环。调度循环的阻塞和唤醒是由 python 原生 Event 的 wait 和 set 来实现的，阻塞结束的方式有两种：一是 wait(wait_seconds) 超时；另一种是在 scheduler 处于 running 状态添加新的任务，添加新任务过程中会自动调用 set()唤醒 event。</p><h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>总体而言 APScheduler 以 <a href="http://docs.python.org/2/library/threading.html#module-threading" target="_blank">threading</a> 模块为基础实现，主要用到了 threading.Event 和 threading.Thread，用到的 ThreadPool 是对 threading.Thread 的简单封装。真是因为此所以 APScheduler 有 “No (hard) external dependencies” 和 “Thread-safe API” 这两项优点。但同时存在一个问题，由于 <a href="https://wiki.python.org/moin/GlobalInterpreterLock" target="_blank">GIL</a> 的存在，任务的执行一定会阻塞主线程，所以如果任务执行时间较长、有更多异步调度的需求，那么可能就会用到另外一个更强大的框架：<a href="http://www.celeryproject.org/" target="_blank">Celery</a>。 Celery 毕竟是一个分布式的任务队列，相比而言 APScheduler 的特点是轻巧，一言以蔽之即: APScheduler is a light but powerful in-process task scheduler.</p>]]></content>
    
    
    <summary type="html">&lt;h3 id=&quot;概述&quot;&gt;&lt;a href=&quot;#概述&quot; class=&quot;headerlink&quot; title=&quot;概述&quot;&gt;&lt;/a&gt;概述&lt;/h3&gt;&lt;p&gt;APScheduler 是由 python 实现的一个轻量级任务调度器，它可以按照一定间隔（IntervalTrigger）、指定时间（2.1中的SimpleTrigger&amp;#x2F;3.0中的DateTrigger）或者以类似 cron（CronTrigger） 的形式触发待执行任务（即调用函数或者调用 python 的 callable 对象）。现在 pypi 上的稳定版是 &lt;a href=&quot;https://pypi.python.org/pypi/APScheduler/2.1.1&quot; target=&quot;_blank&quot;&gt;APScheduler 2.1.1&lt;/a&gt;，3.0 版本在 class Scheduler 中移除了针对不同 trigger 的 add_trigger_job() 接口，统一为 add_job()，但是底层实现变化不大。我主要看了 2.1.1 的代码。代码很简洁，加起来一共2049行。&lt;/p&gt;
&lt;h3 id=&quot;模块组织&quot;&gt;&lt;a href=&quot;#模块组织&quot; class=&quot;headerlink&quot; title=&quot;模块组织&quot;&gt;&lt;/a&gt;模块组织&lt;/h3&gt;&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Scheduler&lt;/strong&gt;  调度器的核心部分，负责对 job 的管理和调度，用户使用添加&amp;#x2F;移除任务，启动调度器都通过 Scheduler 提供的接口完成。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Job&lt;/strong&gt;  封装了需要调度的任务，每一个 Job 实例是在 Scheduler 添加 job 时被初始化，具体的初始化参数决定了调度被触发的形式（3类不同的trigger）。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Trigger&lt;/strong&gt;  包含 SimpleTrigger，IntervalTrigger和 CronTrigger 三个类。Trigger 的作用就是计算下一次触发任务的时间。&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;JobStore&lt;/strong&gt;  抽象基类，针对任务存储的介质有多个实现，包括基于内存（RAMJobStore）、使用shelve的简单持久化存储（ShelveJobStore）、使用数据库存储（RedisJobStore，MongoDBJobStore）等。如果不指定参数默认使用 RAMJobStore，使用持久化的 JobStore 的目的是在 Scheduler 重启之后能够恢复原有的任务调度。&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;底层实现&quot;&gt;&lt;a href=&quot;#底层实现&quot; class=&quot;headerlink&quot; title=&quot;底层实现&quot;&gt;&lt;/a&gt;底层实现&lt;/h3&gt;&lt;p&gt;从分析 Scheduler 类入手，首先看项目中自带的example：&lt;/p&gt;</summary>
    
    
    
    <category term="program" scheme="http://amyangfei.me/categories/program/"/>
    
    
    <category term="python" scheme="http://amyangfei.me/tags/python/"/>
    
    <category term="task scheduler" scheme="http://amyangfei.me/tags/task-scheduler/"/>
    
    <category term="source code reading" scheme="http://amyangfei.me/tags/source-code-reading/"/>
    
  </entry>
  
</feed>
