SYS-CON MEDIA Authors: Zakia Bouachraoui, Liz McMillan, Yeshim Deniz, Elizabeth White, William Schmarzo

Blog Feed Post

20 Lines or Less # 54: Pools, Geo-IP, and Mobile

What could you do with your code in 20 Lines or Less? That's the question I ask (sometimes?) every week for the DevCentral community, and every week I go looking to find cool new examples that show just how flexible and powerful iRules can be without getting in over your head.

This week the forums provide us with more examples of iRules wizardry (or at least apprentice awesomeness) in a scant 20 lines or less each. The credit goes to the awesome community for providing such frequent and awesome examples. This week's installation of iRules goodness in particular is brought to you by hoolio, who despite the snow storm (perhaps because of it?) was iRuling away like the mad man he is. Showing off how to simplify geographical based redirection, how to smoothly access a particular pool given the right configuration, and how to do some fancy matching to search for strings of digits.

Mobile Redirects

In this example user Ruchir is looking to do some matching based on some mobile device needs. They have a somewhat complex set of requirements to strip out a set of 4 or 6 digits from a URI that could take multiple forms. Making clever use of the URI::path depth command and some intelligence built into switch, Aaron shows that this can be near trivial if you know what knobs to turn.


   1: when HTTP_REQUEST {
   2:     # Get the index of the last URI directory
   3:     set depth [URI::path [HTTP::uri] depth]
   5:     # Parse the last directory in the path
   6:     set last_dir [URI::path [HTTP::uri] $depth $depth]
   8:     # Parse everything after the last hyphen in the last directory
   9:     set digits [string trimleft [string range $last_dir [expr {[string last - $last_dir]}] end-1] -/]
  11:     log local0. "URI=[HTTP::uri], \$depth=$depth, \$last_dir=$last_dir, \$digits=$digits"
  13:     # Check if we parsed 4 or 6 digits
  14:     switch $digits {
  15:         [0-9][0-9][0-9][0-9] -
  16:         [0-9][0-9][0-9][0-9][0-9][0-9] {
  17:             # Found 4 or 6 digits, send a redirect
  18:             HTTP::redirect "$digits"
  19:         }
  20:     }
  21: }


Geo-IP Redirection

Geolocation is not a new concept in our products, but it is new to many users out there, and it's fantastic to see people bringing it up in the forums. In this example, the desire was to separate out several countries into their own landing pages. Aaron came through and made a much simpler version using switch and some cleaned up matching logic that shows this can be pretty easy indeed. I removed some of the country cases for brevity, but the idea remains intact.


   1: when HTTP_REQUEST {
   2:     if { [string tolower [HTTP::host]] equals "" && [HTTP::path] eq "/" }{
   3:         # Parse the client IP from the CDN header
   4:         set client_ip [HTTP::header value "Client-IP"]
   5:         if { $client_ip eq "" }{
   6:             # The header was empty/did not exist, so use the actual client IP
   7:             set client_ip [IP::client_addr]
   8:         }
   9:         set country [string tolower [whereis $client_ip abbrev]]
  10:         switch $country {
  11:             "af" -
  12:             "bh" -
  13:             "ye" { HTTP::redirect "${country}" } 
  14:             default {
  15:                 # Redirect all others
  16:                 HTTP::redirect ""
  17:             }
  18:         }
  19:     } else {
  20:         pool example_web_pool
  21:     }
  22: }


Pool Based on Inbound Port

Every so often we get a request from a user that wants to select a pool directly based off of something within the request. I.E. they want to add "/pool1" to the URI or they want to, as in this case, use the port number and append that to a pre-defined pool name and automatically direct traffic to a specific pool. In this case it is a way to specifically select a given node, as the user has one member per pool. That being said, we can do this, but not without one inherent issue in particular. If the pool doesn't exist, the connection will, understandably, fail. So what is a good way around this? The catch command! Aaron demonstrates how this works and gives a way for a backup plan in this snippet.


   3:     # Try assigning the pool based on the client destination port
   4:     # If the pool assignment fails, use the VS default pool
   5:     if {[catch {pool pool_[TCP::local_port]} result]}{
   6:         # Pool did not exist, so log the value for testing
   7:         # The VS default pool will be used
   8:         log local0. "pool_[TCP::local_port] doe not exist"
   9:     } else {
  10:         # Pool assignment succeeded
  11:     }
  12: }


Check back again next week, or better yet subscribe to the feed, for more examples of iRules less than 21 lines that you can add to your bag of tricks.



Read the original blog entry...

More Stories By Colin Walker

Coming from a *Nix Software Engineering background, Colin is no stranger to long hours of coding, testing and deployment. His personal experiences such as on-stage performance and the like have helped to foster the evangelist in him. These days he splits his time between coding, technical writing and evangalism. He can be found on the road to just about anywhere to preach the good word about ADCs, Application Aware networking, Network Side Scripting and geekery in general to anyone that will listen.

Colin currently helps manage and maintain DevCentral ( He is also a contributor in many ways, from Articles to Videos to numerous forum posts, to iRules coding and whatever else he can get his hands on that might benefit the community and allow it to continue to grow.

Latest Stories
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Despite being the market leader, we recognized the need to transform and reinvent our business at Dynatrace, before someone else disrupted the market. Over the course of three years, we changed everything - our technology, our culture and our brand image. In this session we'll discuss how we navigated through our own innovator's dilemma, and share takeaways from our experience that you can apply to your own organization.
Having been in the web hosting industry since 2002, dhosting has gained a great deal of experience while working on a wide range of projects. This experience has enabled the company to develop our amazing new product, which they are now excited to present! Among dHosting's greatest achievements, they can include the development of their own hosting panel, the building of their fully redundant server system, and the creation of dhHosting's unique product, Dynamic Edge.
Cloud Storage 2.0 has brought many innovations, including the availability of cloud storage services that are less expensive and much faster than previous generations of cloud storage. Cloud Storage 2.0 has also delivered new and faster methods for migrating your premises storage environment to the cloud and the concept of multi-cloud. This session will provide technical details on Cloud Storage 2.0 and the methods used to efficiently migrate from premises-to-cloud storage. This session will als...
DXWorldEXPO LLC announced today that Nutanix has been named "Platinum Sponsor" of CloudEXPO | DevOpsSUMMIT | DXWorldEXPO New York, which will take place November 12-13, 2018 in New York City. Nutanix makes infrastructure invisible, elevating IT to focus on the applications and services that power their business. The Nutanix Enterprise Cloud Platform blends web-scale engineering and consumer-grade design to natively converge server, storage, virtualization and networking into a resilient, softwar...
The Transparent Cloud-computing Consortium (T-Cloud) is a neutral organization for researching new computing models and business opportunities in IoT era. In his session, Ikuo Nakagawa, Co-Founder and Board Member at Transparent Cloud Computing Consortium, will introduce the big change toward the "connected-economy" in the digital age. He'll introduce and describe some leading-edge business cases from his original points of view, and discuss models & strategies in the connected-economy. Nowad...
For far too long technology teams have lived in siloes. Not only physical siloes, but cultural siloes pushed by competing objectives. This includes informational siloes where business users require one set of data and tech teams require different data. DevOps intends to bridge these gaps to make tech driven operations more aligned and efficient.
All in Mobile is a mobile app agency that helps enterprise companies and next generation startups build the future of digital. We offer mobile development and design for smartphones, tablets and wearables. Our projects cover the latest and most innovative technologies - voice assistants, AI, AR/VR and more. We excel at solutions for sports, fintech and retail industries.
NanoVMs is the only production ready unikernel infrastructure solution on the market today. Unikernels prevent server intrusions by isolating applications to one virtual machine with no users, no shells and no way to run other programs on them. Unikernels run faster and are lighter than even docker containers.
The dream is universal: heuristic driven, global business operations without interruption so that nobody has to wake up at 4am to solve a problem. Building upon Nutanix Acropolis software defined storage, virtualization, and networking platform, Mark will demonstrate business lifecycle automation with freedom of choice and consumption models. Hybrid cloud applications and operations are controllable by the Nutanix Prism control plane with Calm automation, which can weave together the following: ...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO Silicon Valley 2019 will cover all of these tools, with the most comprehensive program and with 222 rockstar speakers throughout our industry presenting 22 Keynotes and General Sessions, 250 Breakout Sessions along 10 Tracks, as well as our signature Power Panels. Our Expo Floor will bring together the leading global 200 companies throughout the world of Cloud Computing, DevOps, IoT, Smart Cities, FinTech, Digital Transformation, and all they entail. As ...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throughout enterprises of all sizes. We are offering early bird savings...
Crosscode Panoptics Automated Enterprise Architecture Software. Application Discovery and Dependency Mapping. Automatically generate a powerful enterprise-wide map of your organization's IT assets down to the code level. Enterprise Impact Assessment. Automatically analyze the impact, to every asset in the enterprise down to the code level. Automated IT Governance Software. Create rules and alerts based on code level insights, including security issues, to automate governance. Enterpr...
Your job is mostly boring. Many of the IT operations tasks you perform on a day-to-day basis are repetitive and dull. Utilizing automation can improve your work life, automating away the drudgery and embracing the passion for technology that got you started in the first place. In this presentation, I'll talk about what automation is, and how to approach implementing it in the context of IT Operations. Ned will discuss keys to success in the long term and include practical real-world examples. Ge...