Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

730 righe
26 KiB

  1. #-*- coding: utf-8 -*-
  2. # Copyright 2008-2010 Calculate Ltd. http://www.calculate-linux.org
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import sys
  17. from cl_utils import (getpathenv, runOsCommand, typeFile,process,
  18. listDirectory, InitrdFile)
  19. import re
  20. from os import path, R_OK
  21. try:
  22. from cl_ldap import ldapUser
  23. except ImportError:
  24. ldapUser = None
  25. from operator import itemgetter
  26. class clLocale:
  27. lang = {
  28. #Belarussian
  29. 'be_BY' : {
  30. 'locale':'be_BY.UTF-8',
  31. 'keymap':'by',
  32. 'dumpkeys_charset': 'koi8-u',
  33. 'consolefont':'Cyr_a8x16',
  34. 'xkblayout':'us,by',
  35. 'language':'be',
  36. },
  37. #Bulgarian
  38. 'bg_BG' : {
  39. 'locale':'bg_BG.UTF-8',
  40. 'keymap':'bg_bds-utf8',
  41. 'dumpkeys_charset': '',
  42. 'consolefont':'ter-m14n',
  43. 'xkblayout':'us,bg',
  44. 'language':'bg',
  45. },
  46. #Belgian
  47. 'fr_BE' : {
  48. 'locale':'fr_BE.UTF-8',
  49. 'keymap':'be-latin1',
  50. 'dumpkeys_charset':'',
  51. 'consolefont':'lat9w-16',
  52. 'xkblayout':'us,be',
  53. 'language':'fr',
  54. },
  55. #Brazilian Portuguese
  56. 'pt_BR' : {
  57. 'locale':'pt_BR.UTF-8',
  58. 'keymap':'br-abnt2',
  59. 'dumpkeys_charset':'',
  60. 'consolefont':'lat9w-16',
  61. 'xkblayout':'pt,us',
  62. 'language':'pt_BR',
  63. },
  64. #Canadian French
  65. 'fr_CA' : {
  66. 'locale':'fr_CA.UTF-8',
  67. 'keymap':'cf',
  68. 'dumpkeys_charset':'',
  69. 'consolefont':'default8x16',
  70. 'xkblayout':'us,ca_enhanced',
  71. 'language':'fr',
  72. },
  73. #Danish
  74. 'da_DK' : {
  75. 'locale':'da_DK.UTF-8',
  76. 'keymap':'dk-latin1',
  77. 'dumpkeys_charset':'',
  78. 'consolefont':'lat0-16',
  79. 'xkblayout':'us,dk',
  80. 'language':'da',
  81. },
  82. #French
  83. 'fr_FR' : {
  84. 'locale':'fr_FR.UTF-8',
  85. 'keymap':'fr-latin9',
  86. 'dumpkeys_charset':'',
  87. 'consolefont':'lat0-16',
  88. 'xkblayout':'fr,us',
  89. 'language':'fr',
  90. },
  91. #German
  92. 'de_DE' : {
  93. 'locale':'de_DE.UTF-8',
  94. 'keymap':'de-latin1',
  95. 'dumpkeys_charset':'',
  96. 'consolefont':'lat9w-16',
  97. 'xkblayout':'de,us',
  98. 'language':'de',
  99. },
  100. #Icelandic
  101. 'is_IS' : {
  102. 'locale':'is_IS.UTF-8',
  103. 'keymap':'is-latin1',
  104. 'dumpkeys_charset':'',
  105. 'consolefont':'cp850-8x16',
  106. 'xkblayout':'us,is',
  107. 'language':'is',
  108. },
  109. #Italian
  110. 'it_IT' : {
  111. 'locale':'it_IT.UTF-8',
  112. 'keymap':'it',
  113. 'dumpkeys_charset':'',
  114. 'consolefont':'default8x16',
  115. 'xkblayout':'us,it',
  116. 'language':'it',
  117. },
  118. #Norwegian
  119. 'nn_NO' : {
  120. 'locale':'nn_NO.UTF-8',
  121. 'keymap':'no-latin1',
  122. 'dumpkeys_charset':'',
  123. 'consolefont':'lat9w-16',
  124. 'xkblayout':'us,no',
  125. 'language':'nn',
  126. },
  127. #Polish
  128. 'pl_PL' : {
  129. 'locale':'pl_PL.UTF-8',
  130. 'keymap':'pl',
  131. 'dumpkeys_charset':'',
  132. 'consolefont':'lat2-16',
  133. 'xkblayout':'us,pl',
  134. 'language':'pl',
  135. },
  136. #Portuguese
  137. 'pt_PT' : {
  138. 'locale':'pl_PL.UTF-8@euro',
  139. 'keymap':'pt-latin9',
  140. 'dumpkeys_charset':'',
  141. 'consolefont':'lat0-16',
  142. 'xkblayout':'pt,us',
  143. 'language':'pt',
  144. },
  145. #Romanian
  146. 'ro_RO' : {
  147. 'locale':'ro_RO.UTF-8',
  148. 'keymap':'ro_win',
  149. 'dumpkeys_charset':'',
  150. 'consolefont':'lat2-16',
  151. 'xkblayout':'ro,us',
  152. 'language':'ro',
  153. },
  154. #Russian
  155. 'ru_RU' : {
  156. 'locale':'ru_RU.UTF-8',
  157. 'keymap':'-u ruwin_cplk-UTF-8',
  158. 'dumpkeys_charset':'',
  159. 'consolefont':'ter-k14n',
  160. 'xkblayout':'us,ru(winkeys)',
  161. 'language':'ru',
  162. },
  163. #Spanish
  164. 'es_ES' : {
  165. 'locale':'es_ES.UTF-8',
  166. 'keymap':'es euro2',
  167. 'dumpkeys_charset':'',
  168. 'consolefont':'lat0-16',
  169. 'xkblayout':'es,us',
  170. 'language':'es',
  171. },
  172. #Swedish
  173. 'sv_SE' : {
  174. 'locale':'sv_SE.UTF-8',
  175. 'keymap':'sv-latin1',
  176. 'dumpkeys_charset':'',
  177. 'consolefont':'lat0-16',
  178. 'xkblayout':'us,se',
  179. 'language':'sv',
  180. },
  181. #Ukrainian
  182. 'uk_UA' : {
  183. 'locale':'uk_UA.UTF-8',
  184. 'keymap':'ua-utf',
  185. 'dumpkeys_charset':'koi8-u',
  186. 'consolefont':'ter-v14n',
  187. 'xkblayout':'us,ua(winkeys)',
  188. 'language':'uk',
  189. },
  190. #United Kingdom/British
  191. 'en_GB' : {
  192. 'locale':'en_GB.UTF-8',
  193. 'keymap':'uk',
  194. 'dumpkeys_charset':'',
  195. 'consolefont':'LatArCyrHeb-16',
  196. 'xkblayout':'us,gb',
  197. 'language':'en',
  198. },
  199. #United State/English
  200. 'en_US' : {
  201. 'locale':'en_US.UTF-8',
  202. 'keymap':'us',
  203. 'dumpkeys_charset':'',
  204. 'consolefont':'LatArCyrHeb-16',
  205. 'xkblayout':'us',
  206. 'language':'en',
  207. }
  208. }
  209. def getLangs(self):
  210. return self.lang.keys()
  211. def getLanguages(self):
  212. return map(lambda x:self.lang[x]['language'],
  213. self.lang.keys())
  214. def isLangExists(self,lang):
  215. return lang in self.lang.keys()
  216. def isValueInFieldExists(self,field,value):
  217. return value in map(lambda x:self.lang[x][field],self.lang.keys())
  218. def getFields(self,field):
  219. return [ l[1][field] for l in self.lang.items() ]
  220. def getFieldByLang(self,field,lang):
  221. return self.lang.get(lang, self.lang['en_US'])[field]
  222. def getFieldByKeymap(self,field,keymap):
  223. return self.lang.get(self.getLangByField('keymap',keymap),
  224. self.lang['en_US'])[field]
  225. def getLangByField(self,field,value):
  226. langs = [lang[0] for lang in self.lang.items()
  227. if lang[1][field] == value ]
  228. if not langs:
  229. return 'en_US'
  230. else:
  231. return langs[0]
  232. class varsShare:
  233. """Share methods and attributs for fill vars methods"""
  234. dictNetworkManagers = {"openrc":"sys-apps/openrc",
  235. "networkmanager":"net-misc/networkmanager"}
  236. dictLinuxName = {"CLD":"Calculate Linux Desktop",
  237. "CLDX":"Calculate Linux Desktop",
  238. "CLDG":"Calculate Linux Desktop",
  239. "CDS":"Calculate Directory Server",
  240. "CLS":"Calculate Linux Scratch",
  241. "CSS":"Calculate Scratch Server",
  242. "CMC":"Calculate Media Center",
  243. "Gentoo":"Gentoo"}
  244. dictLinuxSubName = {"CLD":"KDE", "CLDX":"XFCE", "CLDG":"GNOME"}
  245. dictNameSystem = {'CDS':'server',
  246. 'CLD':'desktop',
  247. 'CLDG':'desktop',
  248. 'CLDX':'desktop',
  249. 'CLS':'desktop',
  250. 'CMC':'desktop',
  251. 'CSS':'server'}
  252. # data object from LDAP
  253. _ldapUserObject = False
  254. # user data from LDAP
  255. _ldapUserData = {}
  256. reFindVer = re.compile(
  257. "(?<=version )(\d+\.?\d*\.?\d*\.?\d*)([^\d* ])*(\d*)")
  258. def getFilesByType(self,pathname,descr):
  259. """Get files from "pathname" has "descr" in descriptions"""
  260. return list(self.get_files_by_type(pathname, descr))
  261. def get_files_by_type(self, pathname, descr):
  262. ftype = typeFile(magic=0x4).getMType
  263. for x in listDirectory(pathname, fullPath=True):
  264. if descr in ftype(x):
  265. yield x
  266. def getInitrd(self,arch,shortname,chroot,kernel,suffix="",notsuffix=""):
  267. """Get initrd for kernel"""
  268. reInitrdVer = re.compile("(initrd|initramfs)-(.+?)(-install)?$",re.S)
  269. def initrd_version_by_name(filename):
  270. resInitrdVer = reInitrdVer.search(filename)
  271. if resInitrdVer:
  272. return resInitrdVer.groups()[1]
  273. return ""
  274. ftype = typeFile(magic=0x4).getMType
  275. kernelfile = path.join(chroot,'boot',kernel)
  276. typeKernelFile = ftype(kernelfile)
  277. if typeKernelFile == None:
  278. return ""
  279. resKernelVer = self.reFindVer.search(ftype(kernelfile))
  280. if resKernelVer:
  281. kernelVersion = "%s-%s-%s"% \
  282. (resKernelVer.group().replace('-calculate',''),
  283. arch, shortname)
  284. origKernelVer = resKernelVer.group()
  285. bootdir = path.join(chroot,'boot')
  286. initramfsFiles = self.getFilesByType(bootdir,"ASCII cpio archive")
  287. initramfsWithVer = \
  288. filter(lambda x: (kernelVersion in x[1] or
  289. origKernelVer in x[1]) and \
  290. x[0].endswith(suffix) and \
  291. (not notsuffix or not x[0].endswith(notsuffix)),
  292. map(lambda x:(x[0],initrd_version_by_name(x[0])),
  293. initramfsFiles))
  294. if initramfsWithVer:
  295. return path.split(min(initramfsWithVer,
  296. key=itemgetter(0))[0])[-1]
  297. return ""
  298. def getDirList(self,pathname):
  299. """Get directory list by pathname"""
  300. dirs = []
  301. if path.exists(pathname):
  302. dirs = filter(lambda x: path.isdir(path.join(pathname,x)),
  303. os.listdir(pathname))
  304. return dirs
  305. def getUserInfo(self):
  306. """Get information about user from LDAP in dict format"""
  307. userName = self.Get('ur_login')
  308. if userName:
  309. if userName in self._ldapUserData:
  310. return self._ldapUserData[userName]
  311. elif not ldapUser is None:
  312. ldapObj = self.getLdapUserObject()
  313. if ldapObj:
  314. userInfo = ldapObj.getUserLdapInfo(userName)
  315. if userInfo:
  316. self._ldapUserData[userName] = userInfo
  317. return userInfo
  318. return {}
  319. def getLdapUserObject(self):
  320. """Get data obejct from LDAP"""
  321. if not self._ldapUserObject:
  322. self._ldapUserObject = ldapUser()
  323. return self._ldapUserObject
  324. def _runos(self, cmd, env={}):
  325. """Return result of os command perform"""
  326. if not env:
  327. env.update(os.environ.items() + [("PATH",getpathenv())] +\
  328. env.items())
  329. retCode, programOut = runOsCommand(cmd, None, env_dict=env)
  330. if not retCode:
  331. return programOut
  332. return False
  333. def get_composite_from_xorgconf(self,chroot="/"):
  334. """Get composite value from xorg.conf"""
  335. xorgConfig = path.join(chroot,
  336. "etc/X11/xorg.conf")
  337. try:
  338. confLines = open(xorgConfig,"r").readlines()
  339. except:
  340. return None
  341. flagStartExtensions = False
  342. lineCompositeTmp = ""
  343. lineComposite = ""
  344. for line in confLines:
  345. line = line.strip()
  346. if flagStartExtensions:
  347. if line.startswith('EndSection'):
  348. lineComposite = lineCompositeTmp
  349. break
  350. elif line.startswith('Section'):
  351. break
  352. if line.startswith('Option') and '"Composite"' in line:
  353. lineCompositeTmp = line
  354. else:
  355. if '"Extensions"' in line and line.startswith('Section'):
  356. flagStartExtensions = True
  357. if lineComposite:
  358. listOpt = filter(lambda x: x.strip(), lineComposite.split('"'))
  359. if len(listOpt) == 3:
  360. ret = listOpt[2].lower()
  361. if ret in ("on","true","yes","1"):
  362. return "on"
  363. elif ret in ("off","false","no","0"):
  364. return "off"
  365. return None
  366. def getValueFromCmdLine(self,option,num):
  367. """Get value of parameter from boot params
  368. Parameters:
  369. option param name
  370. num number part of value parameter (, split)
  371. """
  372. cmdLine = "/proc/cmdline"
  373. calculateParam = "calculate"
  374. names = ("lang","keymap","timezone",
  375. "resolution","video","composite","domain","domain_pw")
  376. # try get timezone from kernel calculate param
  377. try:
  378. if type(num) == str and not num.isdigit():
  379. name = num
  380. num = names.index(name)
  381. else:
  382. name = names[int(num)]
  383. for param in open(cmdLine,"r").read().split(" "):
  384. parname,op,value = param.partition("=")
  385. if parname == calculateParam and op == "=":
  386. # new format
  387. if ":" in value:
  388. params = dict(
  389. map(lambda x:x.partition(':')[0::2],
  390. filter(lambda x:x,
  391. value.split(','))))
  392. return params.get(name,"").strip()
  393. # old format
  394. else:
  395. values = value.split(",")
  396. if len(values) > num and values[num].strip():
  397. return values[num].strip()
  398. except (IOError,ValueError,IndexError),e:
  399. return ""
  400. def getValueFromConfig(self,config,name):
  401. """Get value of parameter from bash type file
  402. Parameters:
  403. config config file name
  404. name param name
  405. """
  406. reMatch = re.compile("^%s\s*=\s*\"?(.*?)(\"\s*)?$"%name, re.I)
  407. try:
  408. if path.exists(config):
  409. for line in open(config,"r").readlines():
  410. match = reMatch.match(line)
  411. if match:
  412. return match.groups()[0].strip()
  413. except:
  414. pass
  415. return False
  416. def getX11Resolution(self):
  417. """Return current screen resolution (width, height), X must be ran"""
  418. lines=self._runos("xdpyinfo")
  419. if not lines:
  420. return ""
  421. reRes = re.compile("dimensions:\s+(\d+)x(\d+)\s+pixels")
  422. searchRes=False
  423. for line in lines:
  424. searchRes = reRes.search(line)
  425. if searchRes:
  426. break
  427. if searchRes:
  428. return (searchRes.group(1), searchRes.group(2))
  429. else:
  430. return ""
  431. def getShortnameByMakeprofile(self,systemroot):
  432. """Get shortname by symlink of make.profile"""
  433. for makeprofile in (path.join(systemroot,'etc/portage/make.profile'),
  434. path.join(systemroot,'etc/make.profile')):
  435. if path.exists(makeprofile):
  436. link = os.readlink(makeprofile)
  437. for pattern in ('/calculate/(?:desktop|server)/(%s)/',
  438. '/distros/profiles/(%s)/'):
  439. reMakeProfileLink = re.compile(pattern%
  440. "|".join(self.dictLinuxName.keys()),re.S)
  441. shortnameSearch = reMakeProfileLink.search(link)
  442. if shortnameSearch:
  443. return shortnameSearch.groups()[0]
  444. return None
  445. def getShortnameByIni(self,systemroot):
  446. """Get shortname by calculate.ini file"""
  447. inifile = path.join(systemroot,'etc/calculate/calculate.ini')
  448. if path.exists(inifile):
  449. FD = open(inifile)
  450. data = FD.readlines()
  451. FD.close()
  452. shortNameList = filter(lambda y:y,
  453. map(lambda x:\
  454. len(x.split("="))==2 and\
  455. x.split("=")[0]=="calculate" and\
  456. x.split("=")[1].strip(), data))
  457. if shortNameList:
  458. return shortNameList[0]
  459. def detectOtherShortname(self,systemroot):
  460. """Detect other system. Now only Gentoo."""
  461. gentooFile = path.join(systemroot,"etc/gentoo-release")
  462. if path.exists(gentooFile):
  463. return "Gentoo"
  464. return None
  465. def getVersionFromMetapackage(self,systemroot,shortname):
  466. """Get version from meta package"""
  467. pkgInfoDir = path.join(systemroot,'var/db/pkg/app-misc/')
  468. if not os.access(pkgInfoDir,os.R_OK):
  469. return None
  470. metaPkgs = sorted(filter(lambda x:"calculate-meta" in x or \
  471. "%s-meta"%shortname.lower() in x,
  472. os.listdir(pkgInfoDir)))
  473. if metaPkgs:
  474. reFindVer = re.compile("(?<=\-)\d+\.?\d*\.?\d*")
  475. findVer = reFindVer.search(metaPkgs[0])
  476. if findVer:
  477. return findVer.group()
  478. return None
  479. def getVersionFromCalculateIni(self,systemroot):
  480. """Get version from calculate ini"""
  481. pathname = path.join(systemroot,
  482. 'etc/calculate/calculate.ini')
  483. if path.exists(pathname):
  484. FD = open(pathname)
  485. data = FD.readlines()
  486. FD.close()
  487. verList = filter(lambda y:y,
  488. map(lambda x:\
  489. len(x.split("="))==2 and\
  490. x.split("=")[0]=="linuxver" and\
  491. x.split("=")[1].strip(), data))
  492. if verList:
  493. reVer=re.compile("^(\d+\.)*\d$",re.S)
  494. reRes = filter(reVer.search,verList)
  495. if reRes:
  496. return reRes[0]
  497. def selectVar(self,selField,where="",eq=""):
  498. """Select value from matrix variables
  499. Example:
  500. selectVar("os_disk_dev",where="os_disk_mount",eq="/")"""
  501. res = filter(lambda x:x[1] == eq,
  502. zip(self.Get(selField),
  503. self.Get(where))) or [("","")]
  504. return res[0][0]
  505. def getVersionFromGentooFiles(self,systemroot):
  506. """Get version from gentoo files"""
  507. gentooFile = path.join(systemroot,"etc/gentoo-release")
  508. systemVersion = ""
  509. flagGentoo = False
  510. reVer=re.compile("^(\d+\.)*\d+$",re.S)
  511. if path.exists(gentooFile):
  512. gentooLink = path.join(systemroot,"etc/make.profile")
  513. if path.islink(gentooLink):
  514. vers = filter(reVer.search,
  515. os.readlink(gentooLink).split('/'))
  516. if vers:
  517. return vers[-1]
  518. def getVersionFromUname(self):
  519. """Get version from uname"""
  520. textLines = self._runos("uname -r")
  521. reVer=re.compile("^(\d+\.)*\d",re.S)
  522. kernelVersion = ""
  523. if textLines:
  524. kernelVersion = textLines[0]
  525. if kernelVersion:
  526. reRes = reVer.search(kernelVersion)
  527. if reRes:
  528. return reRes.group()
  529. def isChroot(self,pid):
  530. """Detect chroot mode by different mountinfo"""
  531. if not os.access('/proc/self/mountinfo',R_OK) or \
  532. not os.access('/proc/1/mountinfo',R_OK):
  533. return False
  534. return open('/proc/1/mountinfo','r').read() != \
  535. open('/proc/self/mountinfo','r').read()
  536. def getProgPath(self,progname):
  537. """Get full path of program or False"""
  538. baseprogname = os.path.basename(progname)
  539. env = {"LANG":"C"}
  540. env.update(os.environ.items() + [("PATH",getpathenv())] +\
  541. env.items())
  542. res = self._runos("which %s"%progname,env=env)
  543. if res:
  544. return res[0].strip()
  545. elif os.path.isabs(progname) and os.path.exists(progname):
  546. return progname
  547. else:
  548. return False
  549. def getVideoByDefault(self,drivers_list):
  550. """Get video by default, or wrong specified"""
  551. workedModules = map(lambda x:x[0],
  552. filter(lambda x:x[1].isdigit() and int(x[1])>0,
  553. map(lambda x:x.split()[:3:2],
  554. open('/proc/modules','r'))))
  555. if "nouveau" in workedModules:
  556. defaultNvidia = "nouveau"
  557. elif "nvidia" in drivers_list:
  558. defaultNvidia = "nvidia"
  559. else:
  560. defaultNvidia = "nv"
  561. if "radeon" in workedModules:
  562. defaultAti = "radeon"
  563. elif "fglrx" in drivers_list:
  564. defaultAti = "fglrx"
  565. else:
  566. defaultAti = "radeon"
  567. defaultDriver = {
  568. 'nvidia':defaultNvidia,
  569. 'ati':defaultAti,
  570. 'intel':'intel',
  571. 'via':'via',
  572. 'vmware':'vmware'}
  573. hr_video = self.Get('hr_video')
  574. if hr_video in defaultDriver and \
  575. defaultDriver[hr_video] in drivers_list:
  576. return defaultDriver[hr_video]
  577. else:
  578. return "other"
  579. def getKernelUid(self,device):
  580. """Get Kernel UID by UUID of device"""
  581. blkidProcess = process('/sbin/blkid','-c','/dev/null','-s','UUID',
  582. '-o','value',device)
  583. res = blkidProcess.read().strip()
  584. if res:
  585. return res[:8]
  586. else:
  587. return "no_uid"
  588. def get_current_kernel_src(self, prefix='/'):
  589. """
  590. Get current kernel source directory
  591. """
  592. src_path = "usr/src"
  593. current_linux_src = path.join(src_path,"linux")
  594. symlink_kernel = path.join(prefix,current_linux_src)
  595. if not path.exists(symlink_kernel) or not path.islink(symlink_kernel):
  596. raise ValueError("Failed to determine current kernel version")
  597. return path.join(src_path,os.readlink(symlink_kernel))
  598. def get_config_version(self, configfile):
  599. re_config = re.compile("Automatically generated file;.*\n"
  600. ".*?Linux/\S+\s+(\S+)\s", re.M)
  601. if path.exists(configfile):
  602. with open(configfile) as f:
  603. match = re_config.search(f.read(200))
  604. if match:
  605. return match.group(1)
  606. def get_src_kernel_version(self, kernel_src):
  607. """
  608. Get version of kernel from .config
  609. """
  610. config_path = path.join(kernel_src, ".config")
  611. makefile_path = path.join(kernel_src, "Makefile")
  612. # get version from config
  613. version = self.get_config_version(config_path)
  614. if version:
  615. return version
  616. # get version from Makefile
  617. re_makefile = re.compile("^VERSION = (\S+)\n"
  618. "PATCHLEVEL = (\S+)\n"
  619. "SUBLEVEL = (\S+)\n"
  620. "EXTRAVERSION = (\S*)\n", re.M)
  621. if path.exists(makefile_path):
  622. with open(makefile_path) as f:
  623. match = re_makefile.search(f.read(200))
  624. if match:
  625. return "{0}.{1}.{2}{3}".format(*match.groups())
  626. return ""
  627. def list_initramfs(self, prefix='/', bootdir='boot'):
  628. boot_dir = path.join(prefix, bootdir)
  629. return self.get_files_by_type(boot_dir,"ASCII cpio archive")
  630. def filter_initramfs(self, iterable, version=None):
  631. for fn in iterable:
  632. if InitrdFile(fn).get_kernel_version() == version:
  633. yield fn
  634. def list_kernel(self, prefix='/', bootdir='boot'):
  635. boot_dir = path.join(prefix, bootdir)
  636. return self.get_files_by_type(boot_dir, "boot executable bzImage")
  637. def filter_kernel(self, iterable, version=None):
  638. ftype = typeFile(magic=0x4).getMType
  639. re_kver = re.compile("bzImage, version (\S+)\s")
  640. for fn in iterable:
  641. m = re_kver.search(ftype(fn))
  642. if m.group(1) == version:
  643. yield fn
  644. def list_config(self, prefix='/', bootdir='boot'):
  645. boot_dir = path.join(prefix, bootdir)
  646. return self.get_files_by_type(boot_dir, "Linux make config build file")
  647. def filter_config(self, iterable, version=None):
  648. for fn in iterable:
  649. if self.get_config_version(fn) == version:
  650. yield fn
  651. def list_system_map(self, prefix='/', bootdir='boot'):
  652. boot_dir = path.join(prefix, bootdir)
  653. for fn in listDirectory(boot_dir):
  654. if fn.startswith("System.map"):
  655. yield path.join(boot_dir, fn)
  656. def filter_system_map(self, iterable, version=None):
  657. re_kver = re.compile("System.map-(\S+)$")
  658. for fn in iterable:
  659. m = re_kver.search(fn)
  660. if m and m.group(1) == version:
  661. yield fn
  662. def max_default(self, iterable, key=lambda x:x, default=None):
  663. try:
  664. return max(iterable, key=key)
  665. except ValueError:
  666. return default