10 glo_coresched_simulate = False
11 joinpath = os.path.join
17 The main entrypoint is adjustCores(self, slivers) which takes a
18 dictionary of sliver records. The cpu_cores field is pulled from the
19 effective rspec (rec["_rspec"]) for each sliver.
21 If cpu_cores > 0 for a sliver, then that sliver will reserve one or
22 more of the cpu_cores on the machine.
24 One core is always left unreserved for system slices.
27 def __init__(self, cgroup_var_name="cpuset.cpus", slice_attr_name="cpu_cores"):
29 self.cgroup_var_name = cgroup_var_name
30 self.slice_attr_name = slice_attr_name
31 self.cgroup_mem_name = "cpuset.mems"
36 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):
71 return a list of available cpu identifiers: [0,1,2,3...]
74 # the cpus never change, so if it's already been computed then don't
79 self.cpus = self.get_cgroup_var(self.cgroup_var_name, 'cpuset')
81 self.cpu_siblings = {}
82 for item in self.cpus:
83 self.cpu_siblings[item] = self.get_core_siblings(item)
87 def find_cpu_mostsiblings(self, cpus):
92 for candidate in self.cpu_siblings[cpu]:
95 if (count > bestCount):
103 def find_compatible_cpu(self, cpus, compatCpu):
105 return self.find_cpu_mostsiblings(cpus)
107 # find a sibling if we can
111 if compatCpu in self.cpu_siblings[cpu]:
114 return self.find_cpu_mostsiblings(cpus)
116 def get_cgroups (self):
118 return a list of cgroups
119 this might change as vservers are instantiated,
120 so always compute it dynamically.
122 return cgroups.get_cgroups()
124 #filenames = os.listdir("/dev/cgroup")
125 #for filename in filenames:
126 # if os.path.isdir(os.path.join("/dev/cgroup", filename)):
127 # cgroups.append(filename)
130 def decodeCoreSpec (self, cores):
132 Decode the value of the core attribute.
133 It's a number, followed by an optional letter "b" to indicate besteffort
134 cores should also be supplied.
138 if cores.endswith("b"):
147 return (cores, bestEffort)
149 def adjustCores (self, slivers):
151 slivers is a dict of {sliver_name: rec}
152 rec is a dict of attributes
153 rec['_rspec'] is the effective rspec
156 cpus = self.get_cpus()[:]
157 mems = self.get_mems()[:]
160 if (len(mems) != len(cpus)):
161 logger.log("CoreSched fewer mems than " + self.cgroup_var_name + "; mem scheduling disabled")
164 logger.log("CoreSched (" + self.cgroup_var_name + "): available units: " + str(cpus))
167 mem_reservations = {}
169 # allocate the cores to the slivers that have them reserved
170 # TODO: Need to sort this from biggest cpu_cores to smallest
171 for name, rec in slivers.iteritems():
172 rspec = rec["_rspec"]
173 cores = rspec.get(self.slice_attr_name, 0)
174 (cores, bestEffort) = self.decodeCoreSpec(cores)
179 # one cpu core reserved for best effort and system slices
181 logger.log("CoreSched: ran out of units while scheduling sliver " + name)
183 cpu = self.find_compatible_cpu(cpus, lastCpu)
187 logger.log("CoreSched: allocating unit " + str(cpu) + " to slice " + name)
188 reservations[name] = reservations.get(name,[]) + [cpu]
190 # now find a memory node to go with the cpu
192 mem = self.find_associated_memnode(mems, cpu)
195 logger.log("CoreSched: allocating memory node " + str(mem) + " to slice " + name)
196 mem_reservations[name] = mem_reservations.get(name,[]) + [mem]
198 logger.log("CoreSched: failed to find memory node for cpu" + str(cpu))
202 # the leftovers go to everyone else
203 logger.log("CoreSched: allocating unit " + str(cpus) + " to _default")
204 reservations["_default"] = cpus[:]
205 mem_reservations["_default"] = mems[:]
209 # now check and see if any of our slices had the besteffort flag
211 for name, rec in slivers.iteritems():
212 rspec = rec["_rspec"]
213 cores = rspec.get(self.slice_attr_name, 0)
214 (cores, bestEffort) = self.decodeCoreSpec(cores)
216 freezable = rspec.get("cpu_freezable", 0)
217 if (cores==0) and (freezable == 1):
218 freezeList[name] = "FROZEN"
220 freezeList[name] = "THAWED"
222 # if the bestEffort flag isn't set then we have nothing to do
226 # note that if a reservation is [], then we don't need to add
227 # bestEffort cores to it, since it is bestEffort by default.
229 if reservations.get(name,[]) != []:
230 reservations[name] = reservations[name] + reservations["_default"]
231 mem_reservations[name] = mem_reservations.get(name,[]) + mem_reservations["_default"]
232 logger.log("CoreSched: adding besteffort units to " + name + ". new units = " + str(reservations[name]))
234 self.reserveUnits(self.cgroup_var_name, reservations)
236 self.reserveUnits(self.cgroup_mem_name, mem_reservations)
238 self.freezeUnits("freezer.state", freezeList)
240 def freezeUnits (self, var_name, freezeList):
241 for (cgroup, freeze) in freezeList.items():
243 logger.verbose("CoreSched: setting freezer for " + cgroup + " to " + freeze)
245 # attempts.append("/dev/cgroup/{}/var_name".format(cgroup, var_name))
246 attempts.append("/sys/fs/cgroup/freezer/libvirt/lxc/{}/{}".format(cgroup, var_name))
247 attempts.append("/sys/fs/cgroup/freezer/machine.slice/machine-lxc\\x2d{}.scope/{}".format(cgroup, var_name))
248 if glo_coresched_simulate:
249 for attempt in attempts: print "F", attempt
252 for attempt in attempts:
253 if os.path.exists(attempt):
254 file(attempt, "w").write(freeze)
258 logger.log("CoreSched: could not freezeUnits with {}".format(cgroup))
259 except Exception as e:
260 # the cgroup probably didn't exit...
261 logger.log("CoreSched: exception while setting freeze for {} ({})".format(cgroup, e))
263 def reserveUnits (self, var_name, reservations):
265 give a set of reservations (dictionary of slicename:cpuid_list),
266 write those reservations to the appropriate cgroup files.
268 reservations["_default"] is assumed to be the default reservation
269 for slices that do not reserve cores. It's essentially the leftover
273 default = reservations["_default"]
275 # set the default vserver cpuset. this will deal with any vservers
276 # that might be created before the nodemanager has had a chance to
277 # update the cpusets.
278 self.reserveDefault(var_name, default)
280 for cgroup in self.get_cgroups():
281 if cgroup in reservations:
282 cpus = reservations[cgroup]
283 logger.log("CoreSched: reserving " + var_name + " on " + cgroup + ": " + str(cpus))
285 # no log message for default; too much verbosity in the common case
288 if glo_coresched_simulate:
289 print "R", "/dev/cgroup/" + cgroup + "/" + var_name, self.listToRange(cpus)
291 cgroups.write(cgroup, var_name, self.listToRange(cpus))
292 #file("/dev/cgroup/" + cgroup + "/" + var_name, "w").write( self.listToRange(cpus) + "\n" )
294 def reserveDefault (self, var_name, cpus):
295 #if not os.path.exists("/etc/vservers/.defaults/cgroup"):
296 # os.makedirs("/etc/vservers/.defaults/cgroup")
298 #if glo_coresched_simulate:
299 # print "RDEF", "/etc/vservers/.defaults/cgroup/" + var_name, self.listToRange(cpus)
301 # file("/etc/vservers/.defaults/cgroup/" + var_name, "w").write( self.listToRange(cpus) + "\n" )
304 def listToRange (self, list):
306 take a list of items [1,2,3,5,...] and return it as a range: "1-3,5"
307 for now, just comma-separate
309 return ",".join( [str(i) for i in list] )
313 return a list of available cpu identifiers: [0,1,2,3...]
316 # the cpus never change, so if it's already been computed then don't
321 self.mems = self.get_cgroup_var(self.cgroup_mem_name, 'cpuset')
323 # build a mapping from memory nodes to the cpus they can be used with
326 for item in self.mems:
327 mems_map[item] = self.get_memnode_cpus(item)
329 if (len(mems_map)>0):
330 # when NUMA_EMU is enabled, only the last memory node will contain
331 # the cpu_map. For example, if there were originally 2 nodes and
332 # we used NUM_EMU to raise it to 12, then
336 # mems_map[5]=[1,3,5,7,9,11]
340 # mems_map[11]=[0,2,4,6,8,10]
341 # so, we go from back to front, copying the entries as necessary.
343 if mems_map[self.mems[0]] == []:
345 for item in reversed(self.mems):
346 if mems_map[item]!=[]:
347 work = mems_map[item]
348 else: # mems_map[item]==[]
349 mems_map[item] = work
351 self.mems_map = mems_map
355 def find_associated_memnode(self, mems, cpu):
357 Given a list of memory nodes and a cpu, see if one of the nodes in
358 the list can be used with that cpu.
361 if cpu in self.mems_map[item]:
365 def get_memnode_cpus(self, index):
367 for a given memory node, return the CPUs that it is associated with.
369 fn = "/sys/devices/system/node/node" + str(index) + "/cpulist"
370 if not os.path.exists(fn):
371 logger.log("CoreSched: failed to locate memory node" + fn)
374 return self.get_cgroup_var(filename=fn)
376 def get_core_siblings(self, index):
377 # use core_siblings rather than core_siblings_list, as it's compatible
379 fn = "/sys/devices/system/cpu/cpu" + str(index) + "/topology/core_siblings"
380 if not os.path.exists(fn):
384 x = open(fn, 'rt').readline().strip().split(',')[-1]
390 siblings.append(cpuid)
398 if __name__=="__main__":
399 glo_coresched_simulate = True
403 print "cgroups:", ",".join(x.get_cgroups())
405 print "cpus:", x.listToRange(x.get_cpus())
407 for item in x.get_cpus():
408 print " ", item, ",".join([str(y) for y in x.cpu_siblings.get(item,[])])
410 print "mems:", x.listToRange(x.get_mems())
411 print "cpu to memory map:"
412 for item in x.get_mems():
413 print " ", item, ",".join([str(y) for y in x.mems_map.get(item,[])])
415 rspec_sl_test1 = {"cpu_cores": "1"}
416 rec_sl_test1 = {"_rspec": rspec_sl_test1}
418 rspec_sl_test2 = {"cpu_cores": "5"}
419 rec_sl_test2 = {"_rspec": rspec_sl_test2}
421 rspec_sl_test3 = {"cpu_cores": "3b"}
422 rec_sl_test3 = {"_rspec": rspec_sl_test3}
424 #slivers = {"sl_test1": rec_sl_test1, "sl_test2": rec_sl_test2}
426 slivers = {"arizona_beta": rec_sl_test1, "arizona_test101": rec_sl_test2, "pl_sirius": rec_sl_test3}
428 #slivers = {"arizona_beta": rec_sl_test1, "arizona_logmon": rec_sl_test2, "arizona_owl": rec_sl_test3}
430 x.adjustCores(slivers)