1# Contributors Listed Below - COPYRIGHT 2016
2# [+] International Business Machines Corp.
3#
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14# implied. See the License for the specific language governing
15# permissions and limitations under the License.
16
17import json
18import os
19# TODO: openbmc/openbmc#2994 remove python 2 support
20import sys
21if sys.version_info[0] < 3:
22    import cPickle as pickle
23else:
24    import pickle
25
26CACHE_PATH = '/var/cache/obmc/'
27
28
29def getCacheFilename(obj_path, iface_name):
30    name = obj_path.replace('/', '.')
31    filename = CACHE_PATH + name[1:] + "@" + iface_name + ".props"
32    return filename
33
34
35def save(obj_path, iface_name, properties):
36    print("Caching: "+ obj_path)
37    filename = getCacheFilename(obj_path, iface_name)
38    parent = os.path.dirname(filename)
39    try:
40        if not os.path.exists(parent):
41            os.makedirs(parent)
42        with open(filename, 'wb') as output:
43            try:
44                # use json module to convert dbus datatypes
45                props = json.dumps(properties[iface_name])
46                prop_obj = json.loads(props)
47                pickle.dump(prop_obj, output)
48            except Exception as e:
49                print("ERROR: " + str(e))
50    except Exception:
51        print("ERROR opening cache file: " + filename)
52
53
54def load(obj_path, iface_name, properties):
55    # overlay with pickled data
56    filename = getCacheFilename(obj_path, iface_name)
57    if (os.path.isfile(filename)):
58        if iface_name in properties:
59            properties[iface_name] = {}
60        print("Loading from cache: " + filename)
61        try:
62            p = open(filename, 'rb')
63            data = pickle.load(p)
64            for prop in list(data.keys()):
65                properties[iface_name][prop] = data[prop]
66
67        except Exception as e:
68            print("ERROR: Loading cache file: " + str(e))
69        finally:
70            p.close()
71