Debian Codegraph @

huge_page_setup_helper.py

raw symbols SCIP
1 #!/usr/bin/python
2
3 #
4 # Tool to set up Linux large page support with minimal effort
5 #
6 # by Jarod Wilson <[email protected]>
7 # (c) Red Hat, Inc., 2009
8 #
9 # Requires hugeadm from libhugetlbfs 2.7 (or backported support)
10 #
11 import os
12
13 debug = False
14
15 # must be executed under the root to operate
16 if os.geteuid() != 0:
17 print("You must be root to setup hugepages!")
18 os._exit(1)
19
20 # config files we need access to
21 sysctlConf = "/etc/sysctl.conf"
22 if not os.access(sysctlConf, os.W_OK):
23 print("Cannot access %s" % sysctlConf)
24 if debug == False:
25 os._exit(1)
26
27 # This file will be created if it doesn't exist
28 limitsConf = "/etc/security/limits.d/hugepages.conf"
29
30
31 # Figure out what we've got in the way of memory
32 memTotal = 0
33 hugePageSize = 0
34 hugePages = 0
35
36 hugeadmexplain = os.popen("/usr/bin/hugeadm --explain 2>/dev/null").readlines()
37
38 for line in hugeadmexplain:
39 if line.startswith("Total System Memory:"):
40 memTotal = int(line.split()[3])
41 break
42
43 if memTotal == 0:
44 print("Your version of libhugetlbfs' hugeadm utility is too old!")
45 os._exit(1)
46
47
48 # Pick the default huge page size and see how many pages are allocated
49 poolList = os.popen("/usr/bin/hugeadm --pool-list").readlines()
50 for line in poolList:
51 if '*' in line:
52 hugePageSize = int(line.split()[0])
53 hugePages = int(line.split()[2])
54 break
55
56 if hugePageSize == 0:
57 print("Aborting, cannot determine system huge page size!")
58 os._exit(1)
59
60 # Get initial sysctl settings
61 shmmax = 0
62 hugeGID = 0
63
64 for line in hugeadmexplain:
65 if line.startswith("A /proc/sys/kernel/shmmax value of"):
66 shmmax = int(line.split()[4])
67 break
68
69 for line in hugeadmexplain:
70 if line.strip().startswith("vm.hugetlb_shm_group = "):
71 hugeGID = int(line.split()[2])
72 break
73
74
75 # translate group into textual version
76 hugeGIDName = "null"
77 groupNames = os.popen("/usr/bin/getent group").readlines()
78 for line in groupNames:
79 curGID = int(line.split(":")[2])
80 if curGID == hugeGID:
81 hugeGIDName = line.split(":")[0]
82 break
83
84
85 # dump system config as we see it before we start tweaking it
86 print("Current configuration:")
87 print(" * Total System Memory......: %6d MB" % memTotal)
88 print(" * Shared Mem Max Mapping...: %6d MB" % (shmmax / (1024 * 1024)))
89 print(" * System Huge Page Size....: %6d MB" % (hugePageSize / (1024 * 1024)))
90 print(" * Number of Huge Pages.....: %6d" % hugePages)
91 print(" * Total size of Huge Pages.: %6d MB" % (hugePages * hugePageSize / (1024 * 1024)))
92 print(" * Remaining System Memory..: %6d MB" % (memTotal - (hugePages * hugePageSize / (1024 * 1024))))
93 print(" * Huge Page User Group.....: %s (%d)" % (hugeGIDName, hugeGID))
94 print()
95
96
97 # ask how memory they want to allocate for huge pages
98 userIn = None
99 while not userIn:
100 try:
101 userIn = input("How much memory would you like to allocate for huge pages? "
102 "(input in MB, unless postfixed with GB): ")
103 if userIn[-2:] == "GB":
104 userHugePageReqMB = int(userIn[0:-2]) * 1024
105 elif userIn[-1:] == "G":
106 userHugePageReqMB = int(userIn[0:-1]) * 1024
107 elif userIn[-2:] == "MB":
108 userHugePageReqMB = int(userIn[0:-2])
109 elif userIn[-1:] == "M":
110 userHugePageReqMB = int(userIn[0:-1])
111 else:
112 userHugePageReqMB = int(userIn)
113 # As a sanity safeguard, require at least 128M not be allocated to huge pages
114 if userHugePageReqMB > (memTotal - 128):
115 userIn = None
116 print("Refusing to allocate %d, you must leave at least 128MB for the system" % userHugePageReqMB)
117 elif userHugePageReqMB < (hugePageSize / (1024 * 1024)):
118 userIn = None
119 print("Sorry, allocation must be at least a page's worth!")
120 else:
121 break
122 except ValueError:
123 userIn = None
124 print("Input must be an integer, please try again!")
125 userHugePageReqKB = userHugePageReqMB * 1024
126 userHugePagesReq = userHugePageReqKB / (hugePageSize / 1024)
127 print("Okay, we'll try to allocate %d MB for huge pages..." % userHugePageReqMB)
128 print()
129
130
131 # some basic user input validation
132 badchars = list(' \\\'":;~`!$^&*(){}[]?/><,')
133 inputIsValid = False
134 # ask for the name of the group allowed access to huge pages
135 while inputIsValid == False:
136 foundbad = False
137 userGroupReq = input("What group should have access to the huge pages?"
138 "(The group will be created, if need be) [hugepages]: ")
139 if userGroupReq is '':
140 userGroupReq = 'hugepages'
141 if userGroupReq[0].isdigit() or userGroupReq[0] == "-":
142 foundbad = True
143 print("Group names cannot start with a number or dash, please try again!")
144 for char in badchars:
145 if char in userGroupReq:
146 foundbad = True
147 print("Illegal characters in group name, please try again!")
148 break
149 if len(userGroupReq) > 16:
150 foundbad = True
151 print("Group names can't be more than 16 characaters, please try again!")
152 if foundbad == False:
153 inputIsValid = True
154 print("Okay, we'll give group %s access to the huge pages" % userGroupReq)
155
156
157 # see if group already exists, use it if it does, if not, create it
158 userGIDReq = -1
159 for line in groupNames:
160 curGroupName = line.split(":")[0]
161 if curGroupName == userGroupReq:
162 userGIDReq = int(line.split(":")[2])
163 break
164
165 if userGIDReq > -1:
166 print("Group %s (gid %d) already exists, we'll use it" % (userGroupReq, userGIDReq))
167 else:
168 if debug == False:
169 os.popen("/usr/sbin/groupadd %s" % userGroupReq)
170 else:
171 print("/usr/sbin/groupadd %s" % userGroupReq)
172
173 # wait for the groupadd finish
174 os.wait()
175
176 groupNames = os.popen("/usr/bin/getent group %s" % userGroupReq).readlines()
177 for line in groupNames:
178 curGroupName = line.split(":")[0]
179 if curGroupName == userGroupReq:
180 userGIDReq = int(line.split(":")[2])
181 break
182 print("Created group %s (gid %d) for huge page use" % (userGroupReq, userGIDReq))
183 print()
184
185
186 # basic user input validation, take 2
187 # space is valid in this case, wasn't in the prior incarnation
188 badchars = list('\\\'":;~`!$^&*(){}[]?/><,')
189 inputIsValid = False
190 # ask for user(s) that should be in the huge page access group
191 while inputIsValid == False:
192 foundbad = False
193 userUsersReq = input("What user(s) should have access to the huge pages (space-delimited list, users created as needed)? ")
194 for char in badchars:
195 if char in userUsersReq:
196 foundbad = True
197 print("Illegal characters in user name(s) or invalid list format, please try again!")
198 break
199 for n in userUsersReq.split():
200 if len(n) > 32:
201 foundbad = True
202 print("User names can't be more than 32 characaters, please try again!")
203 break
204 if n[0] == "-":
205 foundbad = True
206 print("User names cannot start with a dash, please try again!")
207 break
208 if foundbad == False:
209 inputIsValid = True
210 # see if user(s) already exist(s)
211 curUserList = os.popen("/usr/bin/getent passwd").readlines()
212 hugePageUserList = userUsersReq.split()
213 for hugeUser in hugePageUserList:
214 userExists = False
215 for line in curUserList:
216 curUser = line.split(":")[0]
217 if curUser == hugeUser:
218 print("Adding user %s to huge page group" % hugeUser)
219 userExists = True
220 if debug == False:
221 os.popen("/usr/sbin/usermod -a -G %s %s" % (userGroupReq, hugeUser))
222 else:
223 print("/usr/sbin/usermod -a -G %s %s" % (userGroupReq, hugeUser))
224 if userExists == True:
225 break
226 if userExists == False:
227 print("Creating user %s with membership in huge page group" % hugeUser)
228 if debug == False:
229 if hugeUser == userGroupReq:
230 os.popen("/usr/sbin/useradd %s -g %s" % (hugeUser, userGroupReq))
231 else:
232 os.popen("/usr/sbin/useradd %s -G %s" % (hugeUser, userGroupReq))
233 else:
234 print("/usr/sbin/useradd %s -G %s" % (hugeUser, userGroupReq))
235 print()
236
237
238 # set values for the current running environment
239 if debug == False:
240 os.popen("/usr/bin/hugeadm --pool-pages-min DEFAULT:%sM" % userHugePageReqMB)
241 os.popen("/usr/bin/hugeadm --pool-pages-max DEFAULT:%sM" % userHugePageReqMB)
242 os.popen("/usr/bin/hugeadm --set-shm-group %d" % userGIDReq)
243 os.popen("/usr/bin/hugeadm --set-recommended-shmmax")
244 else:
245 print("/usr/bin/hugeadm --pool-pages-min DEFAULT:%sM" % userHugePageReqMB)
246 print("/usr/bin/hugeadm --pool-pages-max DEFAULT:%sM" % userHugePageReqMB)
247 print("/usr/bin/hugeadm --set-shm-group %d" % userGIDReq)
248 print("/usr/bin/hugeadm --set-recommended-shmmax")
249 print()
250
251 # wait for the hugepage setups finish
252 os.wait()
253
254 # figure out what that shmmax value we just set was
255 hugeadmexplain = os.popen("/usr/bin/hugeadm --explain 2>/dev/null").readlines()
256 for line in hugeadmexplain:
257 if line.strip().startswith("kernel.shmmax = "):
258 shmmax = int(line.split()[2])
259 break
260
261 # write out sysctl config changes to persist across reboot
262 if debug == False:
263 sysctlConfLines = "# sysctl configuration\n"
264 if os.access(sysctlConf, os.W_OK):
265 try:
266 sysctlConfLines = open(sysctlConf).readlines()
267 os.rename(sysctlConf, sysctlConf + ".backup")
268 print(("Saved original %s as %s.backup" % (sysctlConf, sysctlConf)))
269 except:
270 pass
271
272 fd = open(sysctlConf, "w")
273 for line in sysctlConfLines:
274 if line.startswith("kernel.shmmax"):
275 continue
276 elif line.startswith("vm.nr_hugepages"):
277 continue
278 elif line.startswith("vm.hugetlb_shm_group"):
279 continue
280 else:
281 fd.write(line);
282
283 fd.write("kernel.shmmax = %d\n" % shmmax)
284 fd.write("vm.nr_hugepages = %d\n" % userHugePagesReq)
285 fd.write("vm.hugetlb_shm_group = %d\n" % userGIDReq)
286 fd.close()
287
288 else:
289 print("Add to %s:" % sysctlConf)
290 print("kernel.shmmax = %d" % shmmax)
291 print("vm.nr_hugepages = %d" % userHugePagesReq)
292 print("vm.hugetlb_shm_group = %d" % userGIDReq)
293 print()
294
295
296 # write out limits.conf changes to persist across reboot
297 if debug == False:
298 limitsConfLines = "# Huge page access configuration\n"
299 if os.access(limitsConf, os.W_OK):
300 try:
301 limitsConfLines = open(limitsConf).readlines()
302 os.rename(limitsConf, limitsConf + ".backup")
303 print(("Saved original %s as %s.backup" % (limitsConf, limitsConf)))
304 except:
305 pass
306
307 fd = open(limitsConf, "w")
308 for line in limitsConfLines:
309 cfgExist = False
310 for hugeUser in hugePageUserList:
311 try:
312 if line.split()[0] == hugeUser:
313 cfgExist = True
314 except IndexError:
315 # hit either white or comment line, it is safe not to take
316 # any action and continue.
317 pass
318 if cfgExist == True:
319 continue
320 else:
321 fd.write(line)
322
323 for hugeUser in hugePageUserList:
324 fd.write("%s soft memlock %d\n" % (hugeUser, userHugePageReqKB))
325 fd.write("%s hard memlock %d\n" % (hugeUser, userHugePageReqKB))
326 fd.close()
327
328 else:
329 print("Add to %s:" % limitsConf)
330 for hugeUser in hugePageUserList:
331 print("%s soft memlock %d" % (hugeUser, userHugePageReqKB))
332 print("%s hard memlock %d" % (hugeUser, userHugePageReqKB))
333
334
335 # dump the final configuration of things now that we're done tweaking
336 print()
337 print("Final configuration:")
338 print(" * Total System Memory......: %6d MB" % memTotal)
339 if debug == False:
340 print(" * Shared Mem Max Mapping...: %6d MB" % (shmmax / (1024 * 1024)))
341 else:
342 # This should be what we *would* have set it to, had we actually run hugeadm --set-recommended-shmmax
343 print(" * Shared Mem Max Mapping...: %6d MB" % (userHugePagesReq * hugePageSize / (1024 * 1024)))
344 print(" * System Huge Page Size....: %6d MB" % (hugePageSize / (1024 * 1024)))
345 print(" * Available Huge Pages.....: %6d" % userHugePagesReq)
346 print(" * Total size of Huge Pages.: %6d MB" % (userHugePagesReq * hugePageSize / (1024 * 1024)))
347 print(" * Remaining System Memory..: %6d MB" % (memTotal - userHugePageReqMB))
348 print(" * Huge Page User Group.....: %s (%d)" % (userGroupReq, userGIDReq))
349 print()
350