<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joey on Medium]]></title>
        <description><![CDATA[Stories by Joey on Medium]]></description>
        <link>https://medium.com/@joey-dev?source=rss-316ecee6fd61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yxyUHMvS3cqX_yM7</url>
            <title>Stories by Joey on Medium</title>
            <link>https://medium.com/@joey-dev?source=rss-316ecee6fd61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:00:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joey-dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deep Dive into Ruby Internals: From Rails Caching to C-Level Object IDs]]></title>
            <link>https://medium.com/@joey-dev/deep-dive-into-ruby-internals-from-rails-caching-to-c-level-object-ids-9dcb2a24a870?source=rss-316ecee6fd61------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dcb2a24a870</guid>
            <category><![CDATA[debug]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[rdbg]]></category>
            <dc:creator><![CDATA[Joey]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 12:18:15 GMT</pubDate>
            <atom:updated>2024-10-27T12:18:15.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive into Ruby Internals: From Rails Caching to C-Level Object IDs</h3><p>When debugging Rails applications, sometimes we stumble upon fascinating aspects of Ruby’s internal workings. This article shares a journey that started with a simple Rails caching issue and led us deep into Ruby’s object model and memory management system.</p><h3>The Starting Point: Rails Caching and Kaminari</h3><p>It all began with what seemed like a straightforward Rails caching operation:</p><pre>Rails.cache.write(Lesson.page(1))</pre><p>This line threw an unexpected error. We were using Kaminari for pagination, and something wasn’t quite right. The error message was cryptic:</p><pre>TypeError: can&#39;t dump anonymous module #&lt;Module:0x000000012028d860&gt;</pre><h3>Understanding Anonymous Modules</h3><p>To understand what was happening, let’s first look at how anonymous modules are typically created in Ruby:</p><pre># Creating an anonymous module<br>dynamic_module = Module.new do<br>  def some_method<br>    &quot;Hello from anonymous module&quot;<br>  end<br>end</pre><pre># Using the anonymous module<br>class MyClass<br>  include dynamic_module<br>end</pre><p>Anonymous modules are commonly used for:</p><ul><li>Creating dynamic mixins</li><li>Implementing plugin systems</li><li>Metaprogramming scenarios</li></ul><p>However, they come with certain limitations, particularly when it comes to serialization.</p><h3>Debugging with Ruby’s Built-in Debugger (rdbg)</h3><p>To investigate further, we used Ruby’s built-in debugger:</p><pre>require &#39;debug&#39;</pre><pre># Set a breakpoint to catch the TypeError<br>catch TypeError do<br>  Rails.cache.write(Lesson.page(1))<br>end</pre><p>When the error occurred, we were inside the debugger and tried to inspect the module:</p><pre>(rdbg) p self<br>#&lt;Module:0x000000012028d860&gt;</pre><p>Attempting to find the source code or definition of this module led to an interesting discovery — there was none! The module was created at the C level, which explained why we couldn’t access its Ruby source code.</p><h3>Marshal’s Restrictions</h3><p>The error came from Marshal, Ruby’s built-in serialization system. Marshal has specific restrictions, one of which is the inability to dump anonymous modules. Here’s why:</p><pre># This works fine<br>Marshal.dump(String)</pre><pre># This raises TypeError<br>anonymous_module = Module.new<br>Marshal.dump(anonymous_module)  # TypeError: can&#39;t dump anonymous module</pre><p>This restriction exists because:</p><ol><li>Anonymous modules lack persistent names</li><li>They might contain context-dependent behavior</li><li>Their state might be tied to the current runtime</li></ol><h3>Digging Deeper: Module Inspection</h3><p>When debugging modules (named or anonymous), we can gather information using various Ruby methods:</p><pre>module SomeModule<br>  def self.some_method; end<br>end</pre><pre># Basic inspection<br>p SomeModule.name                    # &quot;SomeModule&quot;<br>p SomeModule.instance_methods(false) # [:some_method]<br>p SomeModule.ancestors              # [SomeModule, Object, Kernel, BasicObject]</pre><pre># For anonymous modules<br>anonymous_mod = Module.new<br>p anonymous_mod.name                 # nil<br>p anonymous_mod.object_id            # Some number like 8980</pre><h3>The Connection: Ruby Object IDs and C-Level Memory Addresses</h3><p>During our investigation, we discovered an interesting relationship between Ruby’s object IDs and C-level memory addresses:</p><pre># In debugger:<br>(rdbg) self<br>#&lt;Module:0x000000012029fb50&gt;<br>(rdbg) object_id<br>8980</pre><p>The connection between these identifiers reveals how Ruby manages objects internally:</p><ol><li>The hex address (0x000000012029fb50) is the actual memory location in C</li><li>The object_id (8980) is Ruby’s internal object identifier</li><li>There’s a mathematical relationship between them: object_id * 2 approximates the memory address</li></ol><p>Here’s how we can work with these IDs:</p><pre># Getting object from Ruby object_id<br>obj = ObjectSpace._id2ref(8980)</pre><pre># Getting hex representation of object_id<br>hex_addr = &quot;0x%016x&quot; % (obj.object_id * 2)</pre><pre># For immediate values (small integers, symbols, etc.)<br>num = 42<br>p num.object_id      # Will be 85 (42 * 2 + 1)</pre><h3>Ruby’s Object Model Under the Hood</h3><p>This investigation reveals several important aspects of Ruby’s object model:</p><ol><li>Object Tagging System:</li></ol><ul><li>Regular objects have even-numbered object_ids</li><li>Immediate values (small integers, symbols) have special representations</li><li>The lowest bits are used for type tagging</li></ul><ol><li>Memory Layout: ```plaintext Regular Objects: [ klass | flags | instance variables ] ^ | object_id * 2 points approximately here</li></ol><p>Immediate Values: [ value | tag bits ]</p><pre>3. Garbage Collection Considerations:<br>```ruby<br>require &#39;objspace&#39;</pre><pre># Track object allocation<br>ObjectSpace.trace_object_allocations do<br>  obj = Object.new<br>  p ObjectSpace.allocation_sourcefile(obj)<br>  p ObjectSpace.allocation_sourceline(obj)<br>end</pre><h3>Practical Implications</h3><p>This deep dive has several practical implications for Ruby developers:</p><ol><li>Caching Considerations:</li></ol><ul><li>Be careful when caching objects that might contain anonymous modules</li><li>Consider implementing custom serialization for such cases</li></ul><ol><li>Debugging Strategies:</li></ol><ul><li>Use object_id and hex addresses to track objects across contexts</li><li>Understand when you’re dealing with C-level vs. Ruby-level code</li></ul><ol><li>Memory Management:</li></ol><ul><li>Awareness of how Ruby manages object identity</li><li>Understanding of immediate values vs. regular objects</li></ul><h3>Conclusion</h3><p>What started as a simple Rails caching issue led us through a fascinating journey into Ruby’s internals. We learned about:</p><ul><li>Anonymous modules and their limitations</li><li>Ruby’s debugging capabilities</li><li>Marshal serialization restrictions</li><li>Object identity and memory management</li><li>The connection between Ruby’s object model and C-level implementation</li></ul><p>This kind of deep understanding can be invaluable when debugging complex issues or optimizing Ruby applications. It reminds us that even seemingly simple operations can have complex underpinnings worth understanding.</p><h3>Further Reading</h3><ul><li>Ruby’s source code, particularly the implementation of object_id and Marshal</li><li>Ruby’s garbage collector implementation</li><li>Ruby’s object model documentation</li><li>Rails caching strategies and limitations</li></ul><p>Remember that while this level of detail isn’t necessary for day-to-day Ruby development, understanding these internals can help you make better decisions when designing systems and debugging complex issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dcb2a24a870" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defending Against DOS Attacks: A Comprehensive Guide]]></title>
            <link>https://medium.com/@joey-dev/defending-against-dos-attacks-a-comprehensive-guide-d935b34146ba?source=rss-316ecee6fd61------2</link>
            <guid isPermaLink="false">https://medium.com/p/d935b34146ba</guid>
            <category><![CDATA[rack-attack]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ddos]]></category>
            <dc:creator><![CDATA[Joey]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 22:43:12 GMT</pubDate>
            <atom:updated>2024-10-26T22:43:12.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>Defending Against DOS Attacks: A Comprehensive Guide</h3><h3>Understanding DOS and DDoS Attacks</h3><p>In the digital realm, a Denial of Service (DOS) attack is a malicious attempt to disrupt the normal functioning of a targeted server, service, or network by overwhelming it with traffic. When this attack is distributed from multiple sources, it’s known as a Distributed Denial of Service (DDoS) attack. These attacks aim to exhaust an application’s resources, rendering it unavailable to legitimate users.</p><h3>Common Types of DOS Attacks</h3><ol><li><strong>Volume-Based Attacks:</strong> These floods the network with a high volume of traffic.</li></ol><ul><li>UDP floods</li><li>ICMP floods</li><li>Amplification attacks</li></ul><ol><li><strong>Protocol Attacks:</strong> These exploit vulnerabilities in network protocols.</li></ol><ul><li>SYN floods</li><li>Ping of Death</li><li>Smurf attack</li></ul><ol><li><strong>Application Layer Attacks:</strong> These target vulnerabilities in web applications.</li></ol><ul><li>HTTP floods</li><li>Slowloris</li><li>DNS query floods</li></ul><h3>Strategies for DOS Protection</h3><p>To safeguard against these threats, a multi-layered approach is essential. Here are some effective strategies:</p><h3>Application Level Defenses</h3><h4>Throttling Mechanisms</h4><p>Throttling is a rate-limiting technique that controls the number of requests a user can make to an application within a certain period. This method is crucial for preventing abuse and ensuring that the application can handle legitimate traffic without being overwhelmed.</p><p><strong>Example:</strong> Rack Attack is a Ruby gem that can be used to throttle requests based on IP or other parameters. It’s a middleware for Rack apps that tracks and controls the number of requests an IP can make to prevent your application from being overwhelmed by too many requests.</p><pre># Rack::Attack configuration example<br>Rack::Attack.throttle(&quot;req/ip&quot;, limit: 5, period: 2.minutes) do |req|<br>  req.ip<br>end</pre><h4>Input Validation and Sanitization</h4><p>Properly validating and sanitizing user inputs can prevent application-layer attacks that exploit vulnerabilities in form submissions or API endpoints.</p><p><strong>Example:</strong> Using Rails’ built-in sanitization helpers:</p><pre>&lt;%= sanitize @user_input %&gt;</pre><h4>Rack Attack</h4><p>Rack Attack is a middleware that can be used to mitigate DOS attacks by limiting the number of requests from a single source. It can be configured to block or throttle traffic based on various criteria, such as IP addresses or user agents.</p><p><strong>Example Usage:</strong></p><pre># Allow requests from a certain IP range<br>Rack::Attack.blocklist(&#39;block bad ip addresses&#39;) do |request|<br>  [&#39;192.168.1.1&#39;, &#39;192.168.1.2&#39;].include?(request.ip)<br>end</pre><h3>Network Level Defenses</h3><h4>Firewall Configuration</h4><p>Properly configured firewalls can help filter out malicious traffic before it reaches your application servers.</p><p><strong>Example:</strong> Using iptables to limit connection rate:</p><pre>iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT</pre><h4>Intrusion Detection and Prevention Systems (IDS/IPS)</h4><p>These systems can detect and block suspicious traffic patterns in real-time.</p><p><strong>Example:</strong> Using Suricata, an open-source IDS/IPS:</p><pre># Suricata rule to detect HTTP floods<br>alert http $EXTERNAL_NET any -&gt; $HOME_NET any (msg:&quot;Possible HTTP flood&quot;; flow:to_server; threshold: type both, track by_src, count 100, seconds 60; classtype:attempted-dos; sid:1000001; rev:1;)</pre><h3>Load Balancer Strategies</h3><p>Load balancers distribute incoming network traffic across multiple servers to ensure no single server bears too much demand. This distribution not only improves user experience but also acts as a first line of defense against DOS attacks.</p><p><strong>NGINX Rate Limiting:</strong></p><p>NGINX can be configured to limit the rate of requests to certain locations, effectively acting as a rate limiter and protecting against DOS attacks.</p><pre>http {<br>    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;<br>    server {<br>        location / {<br>            limit_req zone=mylimit burst=5;<br>        }<br>    }<br>}</pre><h3>Cloud-based Solutions</h3><h4>Cloudflare</h4><p>Cloudflare offers a robust DOS protection service that leverages its global network to absorb and mitigate attacks before they reach your origin server. It provides always-on traffic monitoring and adaptive real-time tuning to protect against a variety of DOS attack vectors.</p><p><strong>Example:</strong> Configuring Cloudflare’s WAF rules:</p><pre>{<br>  &quot;description&quot;: &quot;Block requests from suspicious IPs&quot;,<br>  &quot;expression&quot;: &quot;ip.src in { 192.0.2.0/24 192.0.2.1/32 }&quot;,<br>  &quot;action&quot;: &quot;block&quot;<br>}</pre><h4>Google Cloud Armor</h4><p>Google Cloud Armor is a Distributed Denial of Service (DDoS) protection service that can be integrated with Google Cloud Load Balancing. It allows you to create security policies that define how to handle incoming traffic, providing an additional layer of protection against DOS attacks.</p><p><strong>Example:</strong> Creating a Cloud Armor security policy:</p><pre>resources:<br>- name: dos-protection-policy<br>  type: compute.v1.securityPolicy<br>  properties:<br>    rules:<br>    - action: deny(403)<br>      priority: 1000<br>      match:<br>        versionedExpr: SRC_IPS_V1<br>        config:<br>          srcIpRanges:<br>          - 192.0.2.0/24</pre><h3>Advanced Considerations</h3><ul><li><strong>Prioritize Vulnerable Assets:</strong> Focus on protecting the most critical components of your infrastructure first. Conduct regular vulnerability assessments to identify and address potential weaknesses.</li><li><strong>Refine Logic to Avoid False Positives:</strong> Implement smarter logic to distinguish between malicious traffic and legitimate users, reducing the chances of blocking valid users. Use machine learning algorithms to improve detection accuracy over time.</li><li><strong>Behavior-based Detection:</strong> Move beyond simple IP and browser tag-based defenses to behavior-based systems that can adapt to new attack patterns. Analyze traffic patterns, user behavior, and historical data to identify anomalies.</li><li><strong>Regular Security Audits:</strong> Conduct periodic security audits to identify potential vulnerabilities and ensure that all defense mechanisms are up-to-date and functioning correctly.</li><li><strong>Incident Response Plan:</strong> Develop and regularly test an incident response plan to ensure quick and effective action in the event of a DOS attack.</li></ul><h3>Monitoring and Analytics</h3><p>Implementing robust monitoring and analytics tools is crucial for early detection and mitigation of DOS attacks.</p><h3>Prometheus and Grafana</h3><p>Use Prometheus to collect metrics and Grafana to visualize them, allowing for real-time monitoring of traffic patterns and system health.</p><p><strong>Example:</strong> Prometheus configuration to scrape NGINX metrics:</p><pre>scrape_configs:<br>  - job_name: &#39;nginx&#39;<br>    static_configs:<br>      - targets: [&#39;localhost:9113&#39;]</pre><h3>ELK Stack (Elasticsearch, Logstash, Kibana)</h3><p>The ELK stack can be used to aggregate, analyze, and visualize logs from various sources, helping to identify potential attack patterns.</p><p><strong>Example:</strong> Logstash configuration to parse NGINX access logs:</p><pre>input {<br>  file {<br>    path =&gt; &quot;/var/log/nginx/access.log&quot;<br>    start_position =&gt; &quot;beginning&quot;<br>  }<br>}</pre><pre>filter {<br>  grok {<br>    match =&gt; { &quot;message&quot; =&gt; &quot;%{COMBINEDAPACHELOG}&quot; }<br>  }<br>}</pre><pre>output {<br>  elasticsearch {<br>    hosts =&gt; [&quot;localhost:9200&quot;]<br>    index =&gt; &quot;nginx-access-%{+YYYY.MM.dd}&quot;<br>  }<br>}</pre><h3>Conclusion</h3><p>In the face of evolving cyber threats, a proactive and layered approach to DOS attack protection is essential. By combining application-level controls, network defenses, load balancer configurations, and cloud-based solutions with advanced detection methods and robust monitoring, organizations can significantly reduce the risk of service disruptions due to DOS attacks. Regular testing, updating, and refining of these defense mechanisms are crucial to maintaining a strong security posture in an ever-changing threat landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d935b34146ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Funtions to check sidekiq schedules]]></title>
            <link>https://medium.com/@joey-dev/funtions-to-check-sidekiq-schedules-9a9aab6030aa?source=rss-316ecee6fd61------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9aab6030aa</guid>
            <category><![CDATA[script]]></category>
            <category><![CDATA[sidekiq]]></category>
            <dc:creator><![CDATA[Joey]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 22:41:43 GMT</pubDate>
            <atom:updated>2024-10-26T22:41:43.398Z</atom:updated>
            <content:encoded><![CDATA[<pre>def check_queue(queues=[])<br>  if queues.empty?<br><br>    queues = Sidekiq::Queue.all<br>  else<br>    queues = queues.map { |queue| Sidekiq::Queue.new(queue) }<br>  end<br>  queues.each do |queue|<br>    queue.each do |job|<br>      p job<br>      p job.klass, job.args, job.jid<br>    end<br>  end<br>end<br><br><br>def check_schedule<br>  Sidekiq::ScheduledSet.new.each do |job|<br>  puts job.at<br>end<br><br>def check_deadset<br>  Sidekiq::DeadSet.new.each do |job|<br>    puts job<br>  end<br>end<br><br>def check_retryset<br>  Sidekiq::RetrySet.new.each do |job|<br>    puts job<br>  end<br>end<br><br>def check_running_jobs<br>  workers = Sidekiq::Workers.new<br>  workers.each do |process_id, thread_id, work|<br>    p &quot;process_id=#{process_id} thread_id=#{thread_id}&quot;<br>    p work<br>    puts &quot;created_at=#{Time.at(work[&#39;payload&#39;][&#39;created_at&#39;])} enqueued_at=#{Time.at(work[&#39;payload&#39;][&#39;enqueued_at&#39;])} run_at=#{Time.at(work[&#39;run_at&#39;])}&quot;<br>  end<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9aab6030aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into Rufus Scheduler Implementation]]></title>
            <link>https://medium.com/@joey-dev/deep-dive-into-rufus-scheduler-implementation-17f1b6407edb?source=rss-316ecee6fd61------2</link>
            <guid isPermaLink="false">https://medium.com/p/17f1b6407edb</guid>
            <category><![CDATA[scheduler]]></category>
            <category><![CDATA[rufus]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Joey]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 22:38:13 GMT</pubDate>
            <atom:updated>2024-10-26T22:38:13.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive into Rufus Scheduler Implementation</h3><p>In the world of Ruby programming, job scheduling is a crucial aspect of many applications. Let’s take a closer look at one of the most popular schedulers in the Ruby ecosystem.</p><p>Rufus-scheduler is a pure Ruby gem that allows you to schedule jobs (blocks of code) for later execution. It’s a standalone scheduler that doesn’t require any external dependencies.</p><p>This article explores its implementation, focusing on its core mechanisms, handling of long-running jobs, and potential improvements.</p><h3>Core Implementation</h3><h3>Main Scheduling Loop</h3><p>The heart of Rufus Scheduler is its main loop, implemented in the start method:</p><pre>def start<br>  @started_at = EoTime.now<br>  @thread = Thread.new do<br>    while @started_at do<br>      begin<br>        unschedule_jobs<br>        trigger_jobs unless @paused_at<br>        timeout_jobs<br>        sleep(@frequency)<br>      rescue =&gt; err<br>        on_error(nil, err)<br>      end<br>    end<br>    rejoin<br>  end<br>  @thread[@thread_key] = true<br>  @thread[:rufus_scheduler] = self<br>  @thread[:name] = @opts[:thread_name] || &quot;#{@thread_key}_scheduler&quot;<br>end</pre><p>This method:</p><ol><li>Creates a new thread for the scheduler.</li><li>Continuously loops while the scheduler is running.</li><li>In each iteration, it:</li></ol><ul><li>Removes unscheduled jobs</li><li>Triggers due jobs (if not paused)</li><li>Checks for timed-out jobs</li><li>Sleeps for a specified duration</li></ul><h3>Job Triggering</h3><p>The trigger_jobs method is responsible for executing due jobs:</p><pre>def trigger_jobs<br>  now = EoTime.now<br>  @jobs.each(now) do |job|<br>    job.trigger(now)<br>  end<br>end</pre><p>Each job’s trigger method adds the job to the scheduler&#39;s work queue:</p><pre>def trigger(time)<br>  return if @scheduler.down?<br>  @scheduler.work_queue &lt;&lt; self<br>end</pre><h3>Handling Long-Running Jobs</h3><p>Rufus Scheduler employs several strategies to manage long-running jobs:</p><ol><li><strong>Work Threads</strong>: A pool of threads executes jobs concurrently, reducing the risk of blocking.</li><li><strong>Job Timeouts</strong>: The timeout_jobs method enforces time limits on job execution:</li></ol><ul><li>def timeout_jobs work_threads(:active).each do |t| job = t[:rufus_scheduler_job] to = t[:rufus_scheduler_timeout] ts = t[:rufus_scheduler_time] next unless job &amp;&amp; to &amp;&amp; ts to = ts + to unless to.is_a?(EoTime) next if to &gt; EoTime.now t.raise(Rufus::Scheduler::TimeoutError) end end</li></ul><ol><li><strong>Non-blocking Jobs</strong>: Jobs can be scheduled with blocking: false to allow continued processing of other jobs:</li></ol><ul><li>scheduler.every &#39;10s&#39;, blocking: false do # long-running job end</li></ul><h3>Limitations and Potential Improvements</h3><p>While Rufus Scheduler is effective for many use cases, its implementation has some limitations:</p><ol><li><strong>Constant Checking</strong>: The continuous loop can be inefficient, especially for infrequent jobs.</li><li><strong>Scalability</strong>: As job numbers increase, the constant checking can become a bottleneck.</li><li><strong>Single Process</strong>: It typically runs in one process, limiting use in distributed systems.</li></ol><h3>Potential Improvements</h3><ol><li><strong>Timer-based Approach</strong>: Use system timers to wake up the process only when needed:</li></ol><ul><li>loop do next_job_time = calculate_next_job_time() timeout = next_job_time - Time.now IO.select(nil, nil, nil, timeout) run_due_jobs() end</li></ul><ol><li><strong>Tiered Scheduling</strong>: Use different checking frequencies for different time scales.</li><li><strong>Sorted Job List</strong>: Keep jobs sorted by next run time to check only the most imminent ones.</li><li><strong>Dynamic Sleep Duration</strong>: Calculate sleep time based on the next due job:</li></ol><ul><li>def improved_start @thread = Thread.new do while @started_at next_job_time = @jobs.next_job_time now = Time.now if next_job_time &gt; now sleep_duration = [next_job_time - now, MAX_SLEEP].min sleep(sleep_duration) else trigger_due_jobs(now) timeout_jobs end end end end</li></ul><ol><li><strong>System Integration</strong>: For long-running applications, consider integrating with system-level schedulers like systemd timers or cron.</li></ol><h3>Conclusion</h3><p>Rufus Scheduler’s implementation is straightforward and effective for many scenarios. Its use of a main loop with work threads allows for concurrent job execution and handling of long-running tasks. However, for high-performance or large-scale applications, considering alternative approaches or improvements could lead to more efficient scheduling and execution of jobs.</p><p>Understanding these implementation details not only helps in effectively using Rufus Scheduler but also provides insights into designing efficient job scheduling systems in Ruby.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17f1b6407edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Debug Docker Image Builds]]></title>
            <link>https://medium.com/@joey-dev/how-to-debug-docker-image-builds-9d0a2a8f9c33?source=rss-316ecee6fd61------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d0a2a8f9c33</guid>
            <dc:creator><![CDATA[Joey]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 22:30:27 GMT</pubDate>
            <atom:updated>2024-10-26T22:35:40.401Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide covers various techniques to debug Docker image builds, from basic to advanced approaches.</p><h3>Common Debugging Scenarios</h3><h3>1. Using BuildKit’s Enhanced Debugging Features</h3><p>BuildKit (the default builder in modern Docker) offers several powerful debugging options:</p><pre># Enable detailed debugging output<br>BUILDKIT_STEP_LOG_MAX_SIZE=-1 docker build .</pre><pre># Continue build after error (buildx feature)<br>docker buildx build --progress=plain --on-error=continue .</pre><pre># Print verbose output<br>docker buildx build --progress=plain .</pre><h3>2. Debugging Failed Layers</h3><h4>2.1 Remove Problematic Commands</h4><p>If you have a failing command like:</p><pre>FROM busybox<br>RUN echo &#39;hello world&#39; &gt; /tmp/test<br>RUN exit 1  # problematic command<br>RUN echo &#39;ready&#39;</pre><p>Simply remove the failing command and subsequent commands:</p><pre>FROM busybox<br>RUN echo &#39;hello world&#39; &gt; /tmp/test</pre><h4>2.2 Inspect Intermediate Layers</h4><p>Turn off BuildKit to see layer SHA:</p><pre>DOCKER_BUILDKIT=0 docker build -t test .<br># Use the SHA of the last successful layer<br>docker run --rm -it &lt;sha&gt; sh</pre><h3>3. Interactive Debugging with nsenter</h3><h4>3.1 Basic nsenter Debugging</h4><pre>FROM busybox<br>RUN echo &#39;hello world&#39;<br>RUN sleep infinite  # Add this for debugging<br>RUN exit 1</pre><pre># In terminal 1: Start the build<br>docker build -t test .</pre><pre># In terminal 2: Enter the container&#39;s namespace<br>docker run -it --rm --privileged --pid=host justincormack/nsenter1<br>ps -ef | grep sleep<br>nsenter -p -m -u -i -n -t &lt;PID&gt; sh</pre><h4>3.2 Alternative nsenter Approach with Alpine</h4><pre>docker run --privileged --pid=host -it alpine \<br>nsenter -t 1 -m -u -n -i sh</pre><h3>4. Multi-stage Build Debugging</h3><h4>4.1 Basic Target Approach</h4><pre>FROM busybox as working<br>RUN echo &#39;hello world&#39;</pre><pre>FROM working as error<br>RUN exit 1</pre><pre># Build specific target<br>docker build -t test --target working .<br># Debug the working stage<br>docker run --rm -it test sh</pre><h4>4.2 Advanced Multi-stage Debugging</h4><pre># Development stage with debugging tools<br>FROM ruby:3.2 as development<br>RUN apt-get update &amp;&amp; \<br>    apt-get install -y vim curl htop</pre><pre># Production stage<br>FROM ruby:3.2-slim as production<br>COPY --from=development /app /app</pre><h3>5. BuildKit Debug Features</h3><h4>5.1 Mount Cache</h4><pre># Cache apt packages<br>RUN --mount=type=cache,target=/var/cache/apt \<br>    apt-get update &amp;&amp; apt-get install -y build-essential</pre><h4>5.2 Secret Mounting</h4><pre># Mount secrets during build<br>RUN --mount=type=secret,id=mysecret cat /run/secrets/mysecret</pre><h3>6. Debugging Ruby on Rails Specific Issues</h3><p>Here’s an improved version of the Rails Dockerfile with debugging considerations:</p><pre>FROM ruby:3.2</pre><pre># Install essential libraries<br>RUN --mount=type=cache,target=/var/cache/apt \<br>    apt-get update &amp;&amp; \<br>    apt-get install -y \<br>    libssl-dev \<br>    postgresql-client \<br>    nodejs \<br>    npm</pre><pre># Set working directory<br>WORKDIR /app</pre><pre># Install debugging tools in development<br>ARG RAILS_ENV=development<br>RUN if [ &quot;$RAILS_ENV&quot; = &quot;development&quot; ]; then \<br>    gem install debase ruby-debug-ide; \<br>    fi</pre><pre># Copy Gemfile and install dependencies<br>COPY Gemfile Gemfile.lock ./<br>RUN bundle install</pre><pre># Install JavaScript dependencies<br>COPY package.json yarn.lock ./<br>RUN npm install -g yarn &amp;&amp; yarn install</pre><pre># Copy application code<br>COPY . .</pre><pre># Start Rails server<br>CMD [&quot;bundle&quot;, &quot;exec&quot;, &quot;rails&quot;, &quot;server&quot;, &quot;-b&quot;, &quot;0.0.0.0&quot;]</pre><h3>Best Practices</h3><ol><li><strong>Layer Caching</strong></li></ol><ul><li>Use multi-stage builds to separate build dependencies</li><li>Order Dockerfile commands from least to most frequently changing</li><li>Use .dockerignore to exclude unnecessary files</li></ul><ol><li><strong>Debugging Tools</strong></li></ol><ul><li>Include debugging tools only in development stages</li><li>Use BuildKit’s cache mounts for package managers</li><li>Leverage BuildKit’s — progress=plain for detailed build output</li></ul><ol><li><strong>Security</strong></li></ol><ul><li>Never leave debugging tools in production images</li><li>Use secrets mounting for sensitive data</li><li>Regular security scanning of base images</li></ul><h3>Common Issues and Solutions</h3><ol><li><strong>Bundle Install Failures</strong></li></ol><ul><li># Debug bundle install docker run --rm -it &lt;image-id&gt; bundle install --verbose</li></ul><ol><li><strong>Permission Issues</strong></li></ol><ul><li># Fix permission problems RUN chown -R user:user /app USER user</li></ul><ol><li><strong>Network Issues</strong></li></ol><ul><li># Test network connectivity docker run --rm -it &lt;image-id&gt; ping -c 3 google.com</li></ul><h3>Additional Tools</h3><ol><li><strong>Docker Dive</strong></li></ol><ul><li># Analyze image layers dive &lt;image-name&gt;</li></ul><ol><li><strong>Docker History</strong></li></ol><ul><li># View layer history docker history --no-trunc &lt;image-name&gt;</li></ul><p>Remember to always clean up debugging artifacts before pushing to production:</p><pre># Remove debugging layers<br>docker image prune -f</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d0a2a8f9c33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>