We have routers which don't support SNMP OIDs for BGP peer status information, so I wrote a fairly simple script. The API call is relatively 'expensive' so I cache the information and want to implement locking so that only a single process ever updates whilst the others reference the cached data.

Overview: if cache's modification time is less than 60 seconds old, or less th +an 120 seconds old when it's busy being updated { load cached hash else load information via API and save hash to speed up subsequent look + ups
my $cache_ttl = 60; my $cachefile = '/tmp/mtapi.'.$router.'.cache'; my $lockfile = '/tmp/mtapi.'.$router.'.lock'; my %bgp_peer; my $cached = 0; my $modified = (stat($cachefile))[9]; if (defined $modified) { if (($modified >= (time-$cache_ttl)) || ((-e $lockfile) && ($modifie +d >= (time-($cache_ttl*2))))) { if (%bgp_peer = %{lock_retrieve($cachefile)}) { $cached = 1 }; } } if ($cached == 0) { open (LOCK, ">$lockfile"); flock(LOCK, LOCK_EX); my $api = MikroTik::API->new ( { host => $router, username => $api_user, password => $api_passwd, use_ssl => 1, } ); %bgp_peer = $api->get_by_key('/routing/bgp/peer/print', 'name'); $api->logout(); lock_nstore \%bgp_peer, $cachefile; chmod 0660, $cachefile; close LOCK; unlink $lockfile; }

I however still see concurrent API logins happening, a lot more than the 'one in a million' that I had assumed...

PS: I'm really not a programmer, so I'd humbly accept any recommendations or suggestions.


In reply to Faster locking by bbs2web

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.