4 """Whole core scheduling
12 glo_coresched_simulate = False
13 joinpath = os.path.join
16 """ Whole-core scheduler
18 The main entrypoint is adjustCores(self, slivers) which takes a
19 dictionary of sliver records. The cpu_cores field is pulled from the
20 effective rspec (rec["_rspec"]) for each sliver.
22 If cpu_cores > 0 for a sliver, then that sliver will reserve one or
23 more of the cpu_cores on the machine.
25 One core is always left unreserved for system slices.
28 def __init__(self, cgroup_var_name="cpuset.cpus", slice_attr_name="cpu_cores"):
30 self.cgroup_var_name = cgroup_var_name
31 self.slice_attr_name = slice_attr_name
32 self.cgroup_mem_name = "cpuset.mems"
37 def get_cgroup_var(self, name=None, subsys=None, filename=None):
38 """ decode cpuset.cpus or cpuset.mems into a list of units that can
42 assert(filename!=None or name!=None)
45 # filename="/dev/cgroup/" + name
46 filename = reduce(lambda a, b: joinpath(a, b) if b else a, [subsys, name],
47 cgroups.get_base_path())
49 data = open(filename).readline().strip()
56 # cpuset.cpus could be something as arbitrary as:
58 # deal with commas and ranges
59 for part in data.split(","):
60 unitRange = part.split("-")
61 if len(unitRange) == 1:
62 unitRange = (unitRange[0], unitRange[0])
63 for i in range(int(unitRange[0]), int(unitRange[1])+1):
70 """ return a list of available cpu identifiers: [0,1,2,3...]
73 # the cpus never change, so if it's already been computed then don't
78 self.cpus = self.get_cgroup_var(self.cgroup_var_name, 'cpuset')
80 self.cpu_siblings = {}
81 for item in self.cpus:
82 self.cpu_siblings[item] = self.get_core_siblings(item)
86 def find_cpu_mostsiblings(self, cpus):
91 for candidate in self.cpu_siblings[cpu]:
94 if (count > bestCount):
102 def find_compatible_cpu(self, cpus, compatCpu):
104 return self.find_cpu_mostsiblings(cpus)
106 # find a sibling if we can
110 if compatCpu in self.cpu_siblings[cpu]:
113 return self.find_cpu_mostsiblings(cpus)
115 def get_cgroups (self):
116 """ return a list of cgroups
117 this might change as vservers are instantiated, so always compute
120 return cgroups.get_cgroups()
122 #filenames = os.listdir("/dev/cgroup")
123 #for filename in filenames:
124 # if os.path.isdir(os.path.join("/dev/cgroup", filename)):
125 # cgroups.append(filename)
128 def decodeCoreSpec (self, cores):
129 """ Decode the value of the core attribute. It's a number, followed by
130 an optional letter "b" to indicate besteffort cores should also
135 if cores.endswith("b"):
144 return (cores, bestEffort)
146 def adjustCores (self, slivers):
147 """ slivers is a dict of {sliver_name: rec}
148 rec is a dict of attributes
149 rec['_rspec'] is the effective rspec
152 cpus = self.get_cpus()[:]
153 mems = self.get_mems()[:]
156 if (len(mems) != len(cpus)):
157 logger.log("CoreSched fewer mems than " + self.cgroup_var_name + "; mem scheduling disabled")
160 logger.log("CoreSched (" + self.cgroup_var_name + "): available units: " + str(cpus))
163 mem_reservations = {}
165 # allocate the cores to the slivers that have them reserved
166 # TODO: Need to sort this from biggest cpu_cores to smallest
167 for name, rec in slivers.iteritems():
168 rspec = rec["_rspec"]
169 cores = rspec.get(self.slice_attr_name, 0)
170 (cores, bestEffort) = self.decodeCoreSpec(cores)
175 # one cpu core reserved for best effort and system slices
177 logger.log("CoreSched: ran out of units while scheduling sliver " + name)
179 cpu = self.find_compatible_cpu(cpus, lastCpu)
183 logger.log("CoreSched: allocating unit " + str(cpu) + " to slice " + name)
184 reservations[name] = reservations.get(name,[]) + [cpu]
186 # now find a memory node to go with the cpu
188 mem = self.find_associated_memnode(mems, cpu)
191 logger.log("CoreSched: allocating memory node " + str(mem) + " to slice " + name)
192 mem_reservations[name] = mem_reservations.get(name,[]) + [mem]
194 logger.log("CoreSched: failed to find memory node for cpu" + str(cpu))
198 # the leftovers go to everyone else
199 logger.log("CoreSched: allocating unit " + str(cpus) + " to _default")
200 reservations["_default"] = cpus[:]
201 mem_reservations["_default"] = mems[:]
203 # now check and see if any of our slices had the besteffort flag
205 for name, rec in slivers.iteritems():
206 rspec = rec["_rspec"]
207 cores = rspec.get(self.slice_attr_name, 0)
208 (cores, bestEffort) = self.decodeCoreSpec(cores)
210 # if the bestEffort flag isn't set then we have nothing to do
214 # note that if a reservation is [], then we don't need to add
215 # bestEffort cores to it, since it is bestEffort by default.
217 if reservations.get(name,[]) != []:
218 reservations[name] = reservations[name] + reservations["_default"]
219 mem_reservations[name] = mem_reservations.get(name,[]) + mem_reservations["_default"]
220 logger.log("CoreSched: adding besteffort units to " + name + ". new units = " + str(reservations[name]))
222 self.reserveUnits(self.cgroup_var_name, reservations)
224 self.reserveUnits(self.cgroup_mem_name, mem_reservations)
226 def reserveUnits (self, var_name, reservations):
227 """ give a set of reservations (dictionary of slicename:cpuid_list),
228 write those reservations to the appropriate cgroup files.
230 reservations["_default"] is assumed to be the default reservation
231 for slices that do not reserve cores. It's essentially the leftover
235 default = reservations["_default"]
237 # set the default vserver cpuset. this will deal with any vservers
238 # that might be created before the nodemanager has had a chance to
239 # update the cpusets.
240 self.reserveDefault(var_name, default)
242 for cgroup in self.get_cgroups():
243 if cgroup in reservations:
244 cpus = reservations[cgroup]
245 logger.log("CoreSched: reserving " + var_name + " on " + cgroup + ": " + str(cpus))
247 # no log message for default; too much verbosity in the common case
250 if glo_coresched_simulate:
251 print "R", "/dev/cgroup/" + cgroup + "/" + var_name, self.listToRange(cpus)
253 cgroups.write(cgroup, var_name, self.listToRange(cpus))
254 #file("/dev/cgroup/" + cgroup + "/" + var_name, "w").write( self.listToRange(cpus) + "\n" )
256 def reserveDefault (self, var_name, cpus):
257 #if not os.path.exists("/etc/vservers/.defaults/cgroup"):
258 # os.makedirs("/etc/vservers/.defaults/cgroup")
260 #if glo_coresched_simulate:
261 # print "RDEF", "/etc/vservers/.defaults/cgroup/" + var_name, self.listToRange(cpus)
263 # file("/etc/vservers/.defaults/cgroup/" + var_name, "w").write( self.listToRange(cpus) + "\n" )
266 def listToRange (self, list):
267 """ take a list of items [1,2,3,5,...] and return it as a range: "1-3,5"
268 for now, just comma-separate
270 return ",".join( [str(i) for i in list] )
273 """ return a list of available cpu identifiers: [0,1,2,3...]
276 # the cpus never change, so if it's already been computed then don't
281 self.mems = self.get_cgroup_var(self.cgroup_mem_name, 'cpuset')
283 # build a mapping from memory nodes to the cpus they can be used with
286 for item in self.mems:
287 mems_map[item] = self.get_memnode_cpus(item)
289 if (len(mems_map)>0):
290 # when NUMA_EMU is enabled, only the last memory node will contain
291 # the cpu_map. For example, if there were originally 2 nodes and
292 # we used NUM_EMU to raise it to 12, then
296 # mems_map[5]=[1,3,5,7,9,11]
300 # mems_map[11]=[0,2,4,6,8,10]
301 # so, we go from back to front, copying the entries as necessary.
303 if mems_map[self.mems[0]] == []:
305 for item in reversed(self.mems):
306 if mems_map[item]!=[]:
307 work = mems_map[item]
308 else: # mems_map[item]==[]
309 mems_map[item] = work
311 self.mems_map = mems_map
315 def find_associated_memnode(self, mems, cpu):
316 """ Given a list of memory nodes and a cpu, see if one of the nodes in
317 the list can be used with that cpu.
320 if cpu in self.mems_map[item]:
324 def get_memnode_cpus(self, index):
325 """ for a given memory node, return the CPUs that it is associated
328 fn = "/sys/devices/system/node/node" + str(index) + "/cpulist"
329 if not os.path.exists(fn):
330 logger.log("CoreSched: failed to locate memory node" + fn)
333 return self.get_cgroup_var(filename=fn)
335 def get_core_siblings(self, index):
336 # use core_siblings rather than core_siblings_list, as it's compatible
338 fn = "/sys/devices/system/cpu/cpu" + str(index) + "/topology/core_siblings"
339 if not os.path.exists(fn):
343 x = open(fn, 'rt').readline().strip().split(',')[-1]
349 siblings.append(cpuid)
357 if __name__=="__main__":
358 glo_coresched_simulate = True
362 print "cgroups:", ",".join(x.get_cgroups())
364 print "cpus:", x.listToRange(x.get_cpus())
366 for item in x.get_cpus():
367 print " ", item, ",".join([str(y) for y in x.cpu_siblings.get(item,[])])
369 print "mems:", x.listToRange(x.get_mems())
370 print "cpu to memory map:"
371 for item in x.get_mems():
372 print " ", item, ",".join([str(y) for y in x.mems_map.get(item,[])])
374 rspec_sl_test1 = {"cpu_cores": "1"}
375 rec_sl_test1 = {"_rspec": rspec_sl_test1}
377 rspec_sl_test2 = {"cpu_cores": "5"}
378 rec_sl_test2 = {"_rspec": rspec_sl_test2}
380 rspec_sl_test3 = {"cpu_cores": "3b"}
381 rec_sl_test3 = {"_rspec": rspec_sl_test3}
383 #slivers = {"sl_test1": rec_sl_test1, "sl_test2": rec_sl_test2}
385 slivers = {"arizona_beta": rec_sl_test1, "arizona_test101": rec_sl_test2, "pl_sirius": rec_sl_test3}
387 #slivers = {"arizona_beta": rec_sl_test1, "arizona_logmon": rec_sl_test2, "arizona_owl": rec_sl_test3}
389 x.adjustCores(slivers)