Dynamically declaring a class name based on Request info

     It only takes a little bit of time delving into iRules for the value of variables and classes to quickly become tangible. The ability to store and reference data in a scalable, flexible format is vital in the creation of powerful, intricate code, be it iRules or otherwise. Luckily, since we bring a full blown coding language to the table with our rules format, these things are there to be leveraged as needed.

  
  While working with these data formats there are sometimes different methods of entering or extracting data that can become quite useful, depending on the situation. One quite valuable if possibly little-known way of doing so that’s gotten some forums exposure recently is to dynamically select a class.  This not only allows for the re-use of code, but adds rule flexibility as well, which equates to more power for less input.


     Most people that have dealt with iRules in any sort of depth are familiar with the idea of creating and accessing a class of data. It’s usually done in one of many ways, such as a findclass command like so:

 

 set tmp [findclass [HTTP::cookie "cookie_name"] $::myclass " "] 

 

     However, putting to use the same commands we can add an extra layer of abstraction by using a dynamically set class name. By doing this, we open up the ability to use the same rule more widely, and pull in different sets of data as needed.

 
   For instance, as in a great example on the boards, we could use the pool name selected when the load balancing decision was made to determine which class of data to use in our findclass statement. This would mean that for each different pool of servers we would have different information defined in a class, and we could use a single rule to pull in the information from each different class as needed.
This rule would look something like:


when CLIENT_ACCEPTED {
  set defpool [LB::server pool]
  log local0. "defpool selected for -> $defpool"
}

when HTTP_REQUEST {
  if { [HTTP::cookie exists "mycookie"] } {
    set cmd "findclass \[HTTP::cookie \"mycookie\"\] \$::$defpool \" \""
    set tmp [eval $cmd]
    if { $tmp ne "" } {
      log local0. $tmp 
      node $tmp
    } else {
      log local0. "[HTTP::cookie "mycookie"] is not a valid cookie-value!"
      pool $defpool
    }
  } else {
    log local0. "No mycookie cookie found!"
    pool $defpool
  }
}

when LB_FAILED {
  log local0. "LB failed, so chose a new member!"
  pool $defpool
  LB::reselect
}

 

Published Oct 03, 2005
Version 1.0

Was this article helpful?

No CommentsBe the first to comment