Merge branch 'master' into lxc_devel
[nodemanager.git] / cgroups.py
1 # Simple wrapper arround cgroups so we don't have to worry the type of
2 # virtualization the sliver runs on (lxc, qemu/kvm, etc.) managed by libvirt
3 #
4 # Xavi Leon <xleon@ac.upc.edu>
5
6 import os
7 import pyinotify
8 import logger
9
10 # Base dir for libvirt
11 BASE_DIR = '/cgroup/libvirt/'
12 VIRT_TECHS = ['lxc']
13
14 # Global cgroup mapping. 
15 CGROUPS = dict()
16
17 class CgroupWatch(pyinotify.ProcessEvent):
18
19     def process_IN_CREATE(self, event):
20         path = os.path.join(event.path, event.name)
21         CGROUPS[event.name] = path
22         logger.verbose("Cgroup Notify: Created cgroup %s on %s" % \
23                         (event.name, event.path))
24         
25     def process_IN_DELETE(self, event):
26         try:
27             del CGROUPS[event.name]
28         except:
29             logger.verbose("Cgroup Notify: Cgroup %s does not exist, continuing..."%event.name)
30         logger.verbose("Cgroup Notify: Deleted cgroup %s on %s" % \
31                         (event.name, event.path))
32
33
34 logger.verbose("Cgroups: Recognizing already existing cgroups...")
35 for virt in VIRT_TECHS:
36     filenames = os.listdir(os.path.join(BASE_DIR, virt))
37     for filename in filenames:
38         path = os.path.join(BASE_DIR, virt, filename)
39         if os.path.isdir(path):
40             CGROUPS[filename] = path
41
42 logger.verbose("Cgroups: Initializing watchers...")
43 wm = pyinotify.WatchManager()
44 notifier = pyinotify.ThreadedNotifier(wm, CgroupWatch())
45 for virt in VIRT_TECHS:
46         wdd = wm.add_watch(os.path.join(BASE_DIR, virt),
47                            pyinotify.IN_DELETE | pyinotify.IN_CREATE,
48                            rec=False)
49 notifier.daemon = True
50 notifier.start()
51
52 def get_cgroup_path(name):
53     """ Returns the base path for the cgroup with a specific name """
54     assert CGROUPS.has_key(name), \
55             "No sliver %s managed by libvirt through cgroup!" % name
56     return CGROUPS[name]
57
58 def get_base_path():
59     return BASE_DIR
60
61 def get_cgroups():
62     """ Returns the list of cgroups active at this moment on the node """
63     return CGROUPS.keys()
64
65 def write(name, key, value):
66     """ Writes a value to the file key with the cgroup with name """
67     base_path = get_cgroup_path(name)
68     with open(os.path.join(base_path, key), 'w') as f:
69         print >>f, value
70
71 def append(name, key, value):
72     """ Appends a value to the file key with the cgroup with name """
73     base_path = get_cgroup_path(name)
74     with open(os.path.join(base_path, key), 'a') as f:
75         print >>f, value