blob: aa55b272ed390bf5309dd625b712cf124db0964b [file] [log] [blame]
Srikanth Vavilapalli1725e492014-12-01 17:50:52 -08001#
2# Copyright (c) 2012,2013 Big Switch Networks, Inc.
3#
4# Licensed under the Eclipse Public License, Version 1.0 (the
5# "License"); you may not use this file except in compliance with the
6# License. You may obtain a copy of the License at
7#
8# http://www.eclipse.org/legal/epl-v10.html
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13# implied. See the License for the specific language governing
14# permissions and limitations under the License.
15#
16
17import datetime
18import json
19import utif
20import re
21
22#
23#
24#
25
26cached_urls = {}
27cached_urls_age = {}
28record_urls = None
29
30
31def clear_cached_urls():
32 """
33 Called when all the url's ought to be discarded.
34
35 This is currently done at every command start to reclaim any
36 memory resources.
37
38 Also issued when any update or delete is issued against the
39 database, since that means one of our results may be different
40
41 """
42 global cached_urls, cached_urls_age
43
44 cached_urls = {}
45 cached_urls_age = {}
46
47
48def reset_url(url):
49 """
50 Remove a url from the cache
51 """
52 if url in cached_urls:
53 del cached_urls[url]
54 del cached_urls_age[url]
55
56
57def get_cached_url(url):
58 """
59 Simple cache to manage multiple url requests issued within one command cycle
60 """
61 if url in cached_urls:
62 # age doesn't get updated when its touched
63 if url in cached_urls_age and \
64 cached_urls_age[url] < datetime.datetime.now():
65 # too old
66 reset_url(url)
67 return None
68
69 return cached_urls[url]
70 return None
71
72
73def record(path):
74 global record_urls
75 if path == None:
76 if record_urls:
77 record_urls.close()
78 record_urls = None
79 return
80 # need to validate path
81 try:
82 record_urls = open(path, 'w')
83 except Exception, e:
84 print 'Error: can\'t open %s' % path
85
86
87def save_url(url, entries, age = None):
88 """
89 Save a url and the response in the cache, associate an age with the
90 entry, currently two seconds.
91 """
92 cached_urls[url] = entries
93 if record_urls:
94 if type(entries) == str:
95 record_urls.write('REST %s %s %s\n' %
96 (url, 'STR', entries))
97 else:
98 # assume its a complex type
99 record_urls.write('REST %s %s %s\n' %
100 (url, 'JSON', json.dumps(entries)))
101
102 # age out the url in two seconds
103 if age == None:
104 age = 2
105
106 cached_urls_age[url] = datetime.datetime.now() + datetime.timedelta(0, age)
107
108
109def command_finished(words):
110 if record_urls:
111 record_urls.write('COMMAND "%s"\n' %
112 ' '.join([utif.quote_string(x) for x in words]))