[Kimchi-devel] [PATCH 2/7] add a method to load vms sub collection automatically

Sheldon shaohef at linux.vnet.ibm.com
Mon Jan 20 06:33:18 UTC 2014


On 01/20/2014 01:56 PM, Mark Wu wrote:
> On 01/16/2014 11:56 PM, shaohef at linux.vnet.ibm.com wrote:
>> From: ShaoHe Feng <shaohef at linux.vnet.ibm.com>
>>
>> When define a new vms sub collection, we do not need to touch vms 
>> module any more.
>>
>> such as:
>> add a ifaces, we can define it as follow in vm/ifaces.py:
>>
>> from kimchi.control.vm import SubCollection
>>
>> @SubCollection('ifaces')
>> class VmIfaces(Collection):
>> def __init__(self, model, vm):
>> super(VmIfaces, self).__init__(model)
>>
>> Then access URL: /vms/vm-name/ifaces/mac
>> VM resource can dispatch ifaces automatically
>>
>> Signed-off-by: ShaoHe Feng <shaohef at linux.vnet.ibm.com>
>> ---
>> src/kimchi/control/vm/__init__.py | 44 
>> +++++++++++++++++++++++++++++++++++++++
>> 1 file changed, 44 insertions(+)
>>
>> diff --git a/src/kimchi/control/vm/__init__.py 
>> b/src/kimchi/control/vm/__init__.py
>> index f22e568..f3f6e48 100644
>> --- a/src/kimchi/control/vm/__init__.py
>> +++ b/src/kimchi/control/vm/__init__.py
>> @@ -20,3 +20,47 @@
>> # You should have received a copy of the GNU Lesser General Public
>> # License along with this library; if not, write to the Free Software
>> # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 
>> 02110-1301 USA
>> +
>> +import os
>> +import imp
>> +
>> +
>> +class SubCollection(object):
>> + def __init__(self, name):
>> + self.name = name
>> +
>> + def __call__(self, fun):
>> + fun._sub_collection_name = {"name": self.name}
>> + return fun
>> +
>> +
>> +def _listPathModules(path):
>> + modules = set()
>> + for f in os.listdir(path):
>> + base, ext = os.path.splitext(f)
>> + if ext in ('.py', '.pyc', '.pyo'):
>> + modules.add(base)
>> + return sorted(modules)
>> +
>> +
>> +def _load_sub_collections(path):
>> + for mod_name in _listPathModules(path):
>> + if mod_name.startswith("_"):
>> + continue
>> +
>> + mod_fobj, mod_absp, mod_desc = imp.find_module(mod_name, [path])
>> + module = imp.load_module(mod_name, mod_fobj,
>> + mod_absp, mod_desc)
>> + sub_collections = {}
>> +
>> + for collection in [getattr(module, x) for x in dir(module)]:
>> + if not hasattr(collection, "_sub_collection_name"):
>> + continue
>> +
>> + name = collection._sub_collection_name["name"]
>> + sub_collections.update({name: collection})
>> +
>> + return sub_collections
>> +
>> +
>> +VmDevices = _load_sub_collections(os.path.dirname(__file__))
> I think it should be done as a general facility. You could write a 
> metaclass for resource and load its sub collection in "__new__"
>
>
ACK

-- 
Thanks and best regards!

Sheldon Feng(冯少合)<shaohef at linux.vnet.ibm.com>
IBM Linux Technology Center




More information about the Kimchi-devel mailing list