1#
2# Copyright 2015 ClusterHQ
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
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 implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""
18The package that contains a module per each C library that
19`libzfs_core` uses.  The modules expose CFFI objects required
20to make calls to functions in the libraries.
21"""
22from __future__ import absolute_import, division, print_function
23
24import threading
25import importlib
26
27from cffi import FFI
28
29
30def _setup_cffi():
31    class LazyLibrary(object):
32
33        def __init__(self, ffi, libname):
34            self._ffi = ffi
35            self._libname = libname
36            self._lib = None
37            self._lock = threading.Lock()
38
39        def __getattr__(self, name):
40            if self._lib is None:
41                with self._lock:
42                    if self._lib is None:
43                        self._lib = self._ffi.dlopen(self._libname)
44
45            return getattr(self._lib, name)
46
47    MODULES = ["libnvpair", "libzfs_core"]
48    ffi = FFI()
49
50    for module_name in MODULES:
51        module = importlib.import_module("." + module_name, __name__)
52        ffi.cdef(module.CDEF)
53        lib = LazyLibrary(ffi, module.LIBRARY)
54        setattr(module, "ffi", ffi)
55        setattr(module, "lib", lib)
56
57
58_setup_cffi()
59
60# vim: softtabstop=4 tabstop=4 expandtab shiftwidth=4
61