You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1620 lines
66 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 Mir Calculate. 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. from functools import wraps
  16. import random
  17. import sys
  18. from os import path
  19. import os
  20. import time
  21. from calculate.core.server.gen_pid import search_worked_process
  22. from calculate.core.setup_cache import Cache as SetupCache
  23. from calculate.core.server.func import MethodsInterface
  24. from calculate.lib.cl_template import SystemIni, LayeredIni
  25. from calculate.lib.datavars import DataVarsError, VariableError, Variable
  26. from calculate.lib.utils.tools import AddonError
  27. from calculate.lib.utils.colortext.palette import TextState
  28. from calculate.lib.utils.colortext import get_color_print
  29. from calculate.update.emerge_parser import RevdepPercentBlock
  30. from calculate.update.datavars import DataVarsUpdate
  31. from calculate.update.update_info import UpdateInfo
  32. from calculate.lib.utils.binhosts import (Binhosts, BinhostSignError,
  33. BinhostError, PackagesIndex, DAYS)
  34. from calculate.lib.utils.gpg import GPG, GPGError
  35. from calculate.lib.cl_log import log
  36. import hashlib
  37. import re
  38. import shutil
  39. from collections import MutableSet
  40. from contextlib import contextmanager
  41. import tempfile
  42. from calculate.lib.utils.git import Git, GitError, MTimeKeeper, NotGitError
  43. from calculate.lib.utils.portage import (Layman, EmergeLog,
  44. EmergeLogNamedTask,
  45. PackageInformation,
  46. get_packages_files_directory,
  47. get_manifest_files_directory,
  48. get_remove_list)
  49. from calculate.lib.utils.text import _u8
  50. Colors = TextState.Colors
  51. from calculate.lib.utils.files import (getProgPath, STDOUT, removeDir,
  52. PercentProgress, process, getRunCommands,
  53. readFile, listDirectory, pathJoin,
  54. find, FindFileType,quite_unlink,
  55. writeFile, makeDirectory)
  56. import emerge_parser
  57. import logging
  58. from emerge_parser import (EmergeParser, EmergeCommand, EmergeError,
  59. EmergeCache, Chroot)
  60. from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate,
  61. RegexpLocalization, _)
  62. setLocalTranslate('cl_update3', sys.modules[__name__])
  63. __ = getLazyLocalTranslate(_)
  64. class UpdateError(AddonError):
  65. """Update Error"""
  66. class OverlayOwnCache(MutableSet):
  67. """
  68. Сет оверлеев с интегрированным кэшем
  69. """
  70. def __init__(self, dv=None):
  71. self.dv = dv
  72. def __get_overlays(self):
  73. own_cache_value = SystemIni(self.dv).getVar('system', 'own_cache') or ""
  74. return [x.strip() for x in own_cache_value.split(',') if x.strip()]
  75. def __write_overlays(self, overlays):
  76. if not overlays:
  77. SystemIni(self.dv).delVar('system', 'own_cache')
  78. else:
  79. SystemIni(self.dv).setVar('system',
  80. {'own_cache': ",".join(overlays)})
  81. def __contains__(self, item):
  82. return item in self.__get_overlays()
  83. def __iter__(self):
  84. return iter(self.__get_overlays())
  85. def __len__(self):
  86. return len(self.__get_overlays())
  87. def __append_value(self, overlays, value):
  88. if value not in overlays:
  89. overlays.append(value)
  90. self.__write_overlays(overlays)
  91. def add(self, value):
  92. overlays = self.__get_overlays()
  93. self.__append_value(overlays, value)
  94. def discard(self, value):
  95. overlays = self.__get_overlays()
  96. if value in overlays:
  97. overlays.remove(value)
  98. self.__write_overlays(overlays)
  99. def variable_module(var_env):
  100. def variable_module_decor(f):
  101. @wraps(f)
  102. def wrapper(self, *args, **kw):
  103. old_env = self.clVars.defaultModule
  104. try:
  105. self.clVars.defaultModule = var_env
  106. return f(self, *args, **kw)
  107. finally:
  108. self.clVars.defaultModule = old_env
  109. return wrapper
  110. return variable_module_decor
  111. class Update(MethodsInterface):
  112. """Основной объект для выполнения действий связанных с обновлением системы
  113. """
  114. def init(self):
  115. commandLog = path.join(self.clVars.Get('core.cl_log_path'),
  116. 'lastcommand.log')
  117. emerge_parser.CommandExecutor.logfile = commandLog
  118. self.color_print = get_color_print()
  119. self.emerge_cache = EmergeCache()
  120. if self.clVars.Get('cl_env_debug_set') == 'off':
  121. EmergeCache.logger.logger.setLevel(logging.WARNING)
  122. self.emerge_cache.check_list = (
  123. self.emerge_cache.check_list +
  124. map(lambda x:emerge_parser.GitCheckvalue(x, self.getGit()),
  125. self.clVars.Get('update.cl_update_rep_path')))
  126. self.update_map = {}
  127. self.refresh_binhost = False
  128. self.pkgnum = None
  129. self.pkgnummax = None
  130. self.gpgdata_md5 = []
  131. self.gpg_changed = False
  132. def get_prog_path(self, program_name):
  133. return getProgPath(program_name)
  134. def getGit(self):
  135. return self.clVars.Get('cl_update_git')
  136. @contextmanager
  137. def private_repo(self, rpath, url):
  138. if Git.is_private_url(url):
  139. try:
  140. if not path.exists(rpath):
  141. makeDirectory(rpath)
  142. os.chmod(rpath, 0700)
  143. yield
  144. finally:
  145. try:
  146. for dn in (Git._gitDir(rpath), path.join(rpath, "profiles/templates")):
  147. if path.exists(dn):
  148. os.chmod(dn, 0700)
  149. for fn in find(path.join(rpath, "profiles"), True, FindFileType.RegularFile,
  150. True, None, downfilter=lambda x: not x.endswith("/templates")):
  151. if fn.endswith("calculate.env") or fn.endswith("ini.env"):
  152. os.chmod(fn, 0600)
  153. if path.exists(rpath):
  154. os.chmod(rpath, 0755)
  155. except OSError:
  156. pass
  157. else:
  158. yield
  159. def _syncRepository(self, name, url, rpath, revision,
  160. cb_progress=None, clean=False, notask=False):
  161. """
  162. Синхронизировать репозитори
  163. """
  164. dv = self.clVars
  165. git = self.getGit()
  166. info_outdated = False
  167. old_dir = "%s.old" % git._gitDir(rpath)
  168. if path.exists(old_dir):
  169. clean = True
  170. try:
  171. self.stash_cache(rpath, name)
  172. if not git.checkExistsRep(rpath):
  173. if not notask:
  174. self.startTask(_("Syncing the {rep} repository").format(
  175. rep=name.capitalize()))
  176. self.addProgress()
  177. with self.private_repo(rpath, url):
  178. git.cloneTagRepository(url, rpath, revision,
  179. cb_progress=cb_progress)
  180. info_outdated = True
  181. else:
  182. cr = ""
  183. try:
  184. need_update = False
  185. tag_cr = git.getCommit(rpath, revision)
  186. cr = git.getCurrentCommit(rpath)
  187. ref_type = git.reference_type(rpath, revision)
  188. if tag_cr != cr or ref_type == Git.Reference.Branch:
  189. need_update = True
  190. elif clean:
  191. status = git.getStatusInfo(rpath)
  192. if not status or status['files']:
  193. need_update = True
  194. except GitError as e:
  195. need_update = True
  196. if need_update:
  197. if not notask:
  198. self.startTask(_("Syncing the {rep} repository").format(
  199. rep=name.capitalize()))
  200. self.addProgress()
  201. with self.private_repo(rpath, url):
  202. git.updateTagRepository(url, rpath, revision,
  203. cb_progress=cb_progress,
  204. clean=clean)
  205. new_cr = git.getCurrentCommit(rpath)
  206. if new_cr != cr:
  207. info_outdated = True
  208. if info_outdated:
  209. self.raiseOutdate()
  210. dv.Set('cl_update_outdate_set', 'on', force=True)
  211. finally:
  212. self.unstash_cache(rpath, name)
  213. # TODO: debug1
  214. #dv.Set('cl_update_outdate_set', 'on', force=True)
  215. return True
  216. def raiseOutdate(self):
  217. self.clVars.Set('cl_update_outdate_set', 'on', force=True)
  218. def setAutocheckParams(self, status, interval, update_other, cleanpkg):
  219. """
  220. Настроить параметры автопроверки обновлений
  221. """
  222. onoff = lambda x: "on" if x else "off"
  223. self.clVars.Write('cl_update_autocheck_set', onoff(status), True)
  224. self.clVars.Write('cl_update_autocheck_interval', interval, True)
  225. self.clVars.Write('cl_update_other_set', onoff(update_other), True)
  226. self.clVars.Write('cl_update_cleanpkg_set', onoff(cleanpkg), True)
  227. if not status:
  228. UpdateInfo.set_update_ready(False)
  229. return True
  230. def checkSchedule(self, interval, status):
  231. """
  232. Проверить по расписанию необходимость запуска команды
  233. """
  234. if not status:
  235. self.printWARNING(_("Updates autocheck is not enabled"))
  236. return False
  237. last_check = SystemIni(self.clVars).getVar('system', 'last_check') or ""
  238. re_interval = re.compile("^(\d+)\s*(hours?|days?|weeks?)?", re.I)
  239. interval_match = re_interval.search(interval)
  240. MINUTE = 60
  241. HOUR = MINUTE * 60
  242. DAY = HOUR * 24
  243. WEEK = DAY * 7
  244. if interval_match:
  245. if interval_match.group(2):
  246. suffix_map = {'h': HOUR, 'd': DAY, 'w': WEEK}
  247. k = suffix_map.get(interval_match.group(2).lower()[0], HOUR)
  248. else:
  249. k = HOUR
  250. est = int(interval_match.group(1)) * k
  251. else:
  252. est = 3 * HOUR
  253. if last_check:
  254. if last_check.isdigit():
  255. if (time.time() - int(last_check)) < (est - 10 * MINUTE):
  256. self.printWARNING(_("Please wait for the update time"))
  257. return False
  258. self.mark_schedule()
  259. return True
  260. def checkRun(self, wait_update):
  261. """
  262. Проверить повторный запуск
  263. """
  264. update_running = lambda: any(os.getpid() != x
  265. for x in
  266. search_worked_process('update', dv))
  267. dv = self.clVars
  268. if update_running():
  269. if not wait_update:
  270. raise UpdateError(_("Update is already running. "
  271. "Try to run later."))
  272. else:
  273. self.startTask(_("Waiting for another update to be complete"))
  274. while update_running():
  275. self.pauseProcess()
  276. while update_running():
  277. time.sleep(0.3)
  278. self.resumeProcess()
  279. time.sleep(random.random() * 3)
  280. self.endTask()
  281. if self.clVars.Get('cl_chroot_status') == 'off':
  282. emerge_running = lambda: any("/usr/bin/emerge" in x
  283. for x in getRunCommands(True))
  284. if emerge_running():
  285. if not wait_update:
  286. raise UpdateError(_("Emerge is running. "
  287. "Try to run later."))
  288. else:
  289. self.startTask(_("Waiting for emerge to be complete"))
  290. while emerge_running():
  291. time.sleep(1)
  292. self.endTask()
  293. return True
  294. @variable_module("update")
  295. def trimRepositories(self, repname):
  296. """
  297. Синхронизировать репозитории
  298. """
  299. dv = self.clVars
  300. rpath = \
  301. dv.select('cl_update_rep_path', cl_update_rep_name=repname, limit=1)
  302. git = self.getGit()
  303. self.addProgress()
  304. git.trimRepository(rpath, cb_progress=self.setProgress)
  305. return True
  306. @variable_module("update")
  307. def syncRepositories(self, repname, fallback_sync=False,
  308. clean_on_error=True):
  309. """
  310. Синхронизировать репозитории
  311. """
  312. dv = self.clVars
  313. check_status = dv.GetBool('update.cl_update_check_rep_set')
  314. url, rpath, revision = (
  315. dv.Select(["cl_update_rep_url", "cl_update_rep_path",
  316. "cl_update_rep_rev"],
  317. where="cl_update_rep_name", eq=repname, limit=1))
  318. if not url or not rpath:
  319. raise UpdateError(_("Configuration variables for repositories "
  320. "are not setup"))
  321. git = self.getGit()
  322. if not git.checkUrl(url):
  323. raise UpdateError(_("Git %s is unavailable") % url)
  324. chroot_path = path.normpath(self.clVars.Get('cl_chroot_path'))
  325. if chroot_path == '/':
  326. rpath_orig = rpath
  327. else:
  328. rpath_orig = rpath[len(chroot_path):]
  329. mtime = MTimeKeeper(path.join(rpath, "profiles/updates"))
  330. mtime.save()
  331. try:
  332. if clean_on_error:
  333. try:
  334. layman = Layman(dv.Get('cl_update_layman_installed'),
  335. dv.Get('cl_update_layman_make'),
  336. dv.Get('cl_update_layman_conf'),
  337. prefix=chroot_path)
  338. if repname not in ("portage", "gentoo"):
  339. layman.add(repname, url, rpath_orig)
  340. if not self._syncRepository(repname, url, rpath, revision,
  341. cb_progress=self.setProgress,
  342. clean=check_status,
  343. notask=fallback_sync):
  344. return "skip"
  345. return True
  346. except GitError as e:
  347. if not isinstance(e, NotGitError):
  348. if e.addon:
  349. self.printWARNING(str(e.addon))
  350. self.printWARNING(str(e))
  351. self.endTask(False)
  352. self.startTask(
  353. _("Re-fetching the {name} repository").format(
  354. name=repname))
  355. self.addProgress()
  356. rpath_new = "%s_new" % rpath
  357. try:
  358. self._syncRepository(repname, url, rpath_new, revision,
  359. cb_progress=self.setProgress,
  360. clean=check_status,
  361. notask=fallback_sync)
  362. removeDir(rpath)
  363. shutil.move(rpath_new, rpath)
  364. except OSError as e:
  365. raise UpdateError(_("Failed to modify the "
  366. "{repname} repository").format(
  367. repname=repname) + _(": ") + str(e))
  368. finally:
  369. if path.exists(rpath_new):
  370. removeDir(rpath_new)
  371. else:
  372. if not self._syncRepository(repname, url, rpath, revision,
  373. clean=check_status):
  374. return "skip"
  375. layman = Layman(dv.Get('cl_update_layman_installed'),
  376. dv.Get('cl_update_layman_make'),
  377. dv.Get('cl_update_layman_conf'),
  378. prefix=chroot_path)
  379. if repname not in ("portage", "gentoo"):
  380. layman.add(repname, url, rpath_orig)
  381. finally:
  382. mtime.restore()
  383. return True
  384. metadata_cache_names = ("metadata/md5-cache", "metadata/cache")
  385. def stash_cache(self, rpath, name):
  386. """
  387. Спрятать кэш
  388. """
  389. if name in ("portage", "gentoo"):
  390. return
  391. if not name in OverlayOwnCache(self.clVars):
  392. for cachename in self.metadata_cache_names:
  393. cachedir = path.join(rpath, cachename)
  394. if path.exists(cachedir):
  395. try:
  396. cachedir_s = path.join(path.dirname(rpath),
  397. path.basename(
  398. cachename) + ".stash")
  399. if path.exists(cachedir_s):
  400. removeDir(cachedir_s)
  401. shutil.move(cachedir, cachedir_s)
  402. except BaseException as e:
  403. pass
  404. def unstash_cache(self, rpath, name):
  405. """
  406. Извлеч кэш
  407. """
  408. if name in ("portage", "gentoo"):
  409. return
  410. cachenames = self.metadata_cache_names
  411. if not name in OverlayOwnCache(self.clVars):
  412. if any(path.exists(path.join(rpath, x)) for x in cachenames):
  413. for cachename in cachenames:
  414. cachedir_s = path.join(path.dirname(rpath),
  415. path.basename(cachename) + ".stash")
  416. if path.exists(cachedir_s):
  417. try:
  418. removeDir(cachedir_s)
  419. except BaseException as e:
  420. pass
  421. OverlayOwnCache(self.clVars).add(name)
  422. else:
  423. for cachename in cachenames:
  424. cachedir = path.join(rpath, cachename)
  425. cachedir_s = path.join(path.dirname(rpath),
  426. path.basename(cachename) + ".stash")
  427. if path.exists(cachedir_s):
  428. try:
  429. shutil.move(cachedir_s, cachedir)
  430. except BaseException as e:
  431. pass
  432. else:
  433. if all(not path.exists(path.join(rpath, x)) for x in cachenames):
  434. OverlayOwnCache(self.clVars).discard(name)
  435. def syncLaymanRepository(self, repname):
  436. """
  437. Обновить репозиторий через layman
  438. """
  439. layman = self.get_prog_path('/usr/bin/layman')
  440. if not layman:
  441. raise UpdateError(_("The Layman tool is not found"))
  442. rpath = self.clVars.Select('cl_update_other_rep_path',
  443. where='cl_update_other_rep_name', eq=repname,
  444. limit=1)
  445. laymanname = path.basename(rpath)
  446. self.stash_cache(rpath, laymanname)
  447. try:
  448. if Git.is_git(rpath):
  449. self.addProgress()
  450. p = PercentProgress(layman, "-s", laymanname, part=1, atty=True)
  451. for perc in p.progress():
  452. self.setProgress(perc)
  453. else:
  454. p = process(layman, "-s", repname, stderr=STDOUT)
  455. if p.failed():
  456. raise UpdateError(
  457. _("Failed to update the {rname} repository").format(
  458. rname=repname),
  459. addon=p.read())
  460. finally:
  461. self.unstash_cache(rpath, laymanname)
  462. return True
  463. def _regenCache_process(self, progname, repname, cpu_num):
  464. return process(progname, "--repo=%s" % repname, "--update",
  465. "--jobs=%s" % cpu_num, stderr=STDOUT)
  466. def regenCache(self, repname):
  467. """
  468. Обновить кэш метаданных репозитория
  469. """
  470. egenCache = self.get_prog_path('/usr/bin/egencache')
  471. if not egenCache:
  472. raise UpdateError(_("The Portage tool is not found"))
  473. if repname in self.clVars.Get('cl_update_rep_name'):
  474. path_rep = self.clVars.Select('cl_update_rep_path',
  475. where='cl_update_rep_name',
  476. eq=repname, limit=1)
  477. repo_name = readFile(
  478. path.join(path_rep, "profiles/repo_name")).strip()
  479. if repo_name != repname:
  480. self.printWARNING(
  481. _("Repository '{repo_name}' called '{repname}'"
  482. " in cl_update_rep_name").format(
  483. repo_name=repo_name, repname=repname))
  484. raise UpdateError(_("Failed to update the cache of the {rname} "
  485. "repository").format(rname=repname))
  486. cpu_num = self.clVars.Get('hr_cpu_num')
  487. if repname in OverlayOwnCache(self.clVars):
  488. self.printWARNING(
  489. _("Repository %s has its own cache") % repname.capitalize())
  490. else:
  491. self.startTask(_("Updating the %s repository cache") %
  492. repname.capitalize())
  493. p = self._regenCache_process(egenCache, repname, cpu_num)
  494. if p.failed():
  495. raise UpdateError(_("Failed to update the cache of the {rname} "
  496. "repository").format(rname=repname),
  497. addon=p.read())
  498. return True
  499. def emergeMetadata(self):
  500. """
  501. Выполнить egencache и emerge --metadata
  502. """
  503. emerge = self.get_prog_path("/usr/bin/emerge")
  504. if not emerge:
  505. raise UpdateError(_("The Emerge tool is not found"))
  506. self.addProgress()
  507. p = PercentProgress(emerge, "--ask=n", "--metadata", part=1, atty=True)
  508. for perc in p.progress():
  509. self.setProgress(perc)
  510. if p.failed():
  511. data = p.read()
  512. with open('/var/log/calculate/failed-metadata-%d.log' % time.time(),
  513. 'w') as f:
  514. f.write(data + p.alldata)
  515. raise UpdateError(_("Failed to update metadata"), addon=data)
  516. return True
  517. def _eixUpdateCommand(self, eix_cmd, countRep):
  518. return PercentProgress(eix_cmd, "-F", part=countRep or 1, atty=True)
  519. def eixUpdate(self, repositroies):
  520. """
  521. Выполенине eix-update для репозиторием
  522. eix-update выполнятется только для тех репозиториев, которые
  523. обновлялись, если cl_update_eixsync_force==auto, либо
  524. все, если cl_update_eixupdate_force==force
  525. """
  526. eixupdate = self.get_prog_path("/usr/bin/eix-update")
  527. if not eixupdate:
  528. raise UpdateError(_("The Eix tool is not found"))
  529. self.addProgress()
  530. countRep = len(repositroies)
  531. p = self._eixUpdateCommand(eixupdate, countRep)
  532. for perc in p.progress():
  533. self.setProgress(perc)
  534. if p.failed():
  535. raise UpdateError(_("Failed to update eix cache"), addon=p.read())
  536. return True
  537. def is_binary_pkg(self, pkg, binary=None):
  538. """
  539. Является ли пакет бинарным
  540. """
  541. if binary:
  542. return True
  543. if 'PN' in pkg and pkg['PN'].endswith('-bin'):
  544. return True
  545. if binary is not None:
  546. return binary
  547. if "binary" in pkg and pkg['binary']:
  548. return True
  549. return False
  550. def _printEmergePackage(self, pkg, binary=False, num=1, max_num=1):
  551. """
  552. Вывод сообщения сборки пакета
  553. """
  554. self.endTask()
  555. _print = self.color_print
  556. if self.pkgnum is not None:
  557. num = self.pkgnum
  558. if self.pkgnummax is not None:
  559. max_num = self.pkgnummax
  560. one = _print("{0}", num)
  561. two = _print("{0}", max_num)
  562. part = _("({current} of {maximum})").format(current=one, maximum=two)
  563. _print = _print.foreground(Colors.DEFAULT)
  564. if self.is_binary_pkg(pkg, binary):
  565. _colorprint = _print.foreground(Colors.PURPLE)
  566. else:
  567. _colorprint = _print.foreground(Colors.GREEN)
  568. PackageInformation.add_info(pkg)
  569. name = ""
  570. if pkg.info['DESCRIPTION']:
  571. name = _(pkg.info['DESCRIPTION'])
  572. name = name[:1].upper() + name[1:]
  573. if not name.strip():
  574. name = str(pkg)
  575. self.printSUCCESS(
  576. _("{part} {package}").format(part=part, package=name))
  577. self.startTask(
  578. _("Emerging {package}").format(package=_colorprint(str(pkg))))
  579. def _printInstallPackage(self, pkg, binary=False):
  580. """
  581. Вывод сообщения установки пакета
  582. """
  583. self.endTask()
  584. _print = self.color_print
  585. if self.is_binary_pkg(pkg, binary):
  586. _print = _print.foreground(Colors.PURPLE)
  587. else:
  588. _print = _print.foreground(Colors.GREEN)
  589. pkg_key = "{CATEGORY}/{PF}".format(**pkg)
  590. if pkg_key in self.update_map:
  591. self.startTask(_("Installing {pkg} [{oldver}]").format(
  592. pkg=_print(str(pkg)), oldver=self.update_map[pkg_key]))
  593. self.update_map.pop(pkg_key)
  594. else:
  595. self.startTask(_("Installing %s") % (_print(str(pkg))))
  596. def _printFetching(self, fn):
  597. """
  598. Вывод сообщения о скачивании
  599. """
  600. self.endTask()
  601. self.startTask(_("Fetching binary packages"))
  602. def _printUninstallPackage(self, pkg, num=1, max_num=1):
  603. """
  604. Вывод сообщения удаления пакета
  605. """
  606. self.endTask()
  607. _print = self.color_print
  608. if num and max_num:
  609. one = _print("{0}", num)
  610. two = _print("{0}", max_num)
  611. part = _(" ({current} of {maximum})").format(current=one,
  612. maximum=two)
  613. else:
  614. part = ""
  615. _print = _print.foreground(Colors.LIGHT_RED)
  616. self.startTask(
  617. _("Unmerging{part} {package}").format(part=part,
  618. package=_print(str(pkg))))
  619. def emergelike(self, cmd, *params):
  620. """
  621. Запуск команды, которая подразумевает выполнение emerge
  622. """
  623. cmd_path = self.get_prog_path(cmd)
  624. if not cmd_path:
  625. raise UpdateError(_("Failed to find the %s command") % cmd)
  626. with EmergeParser(
  627. emerge_parser.CommandExecutor(cmd_path, params)) as emerge:
  628. self._startEmerging(emerge)
  629. return True
  630. def revdep_rebuild(self, cmd, *params):
  631. """
  632. Запуск revdep-rebulid
  633. """
  634. cmd_path = self.get_prog_path(cmd)
  635. if not cmd_path:
  636. raise UpdateError(_("Failed to find the %s command") % cmd)
  637. with EmergeParser(
  638. emerge_parser.CommandExecutor(cmd_path, params)) as emerge:
  639. revdep = RevdepPercentBlock(emerge)
  640. self.addProgress()
  641. revdep.add_observer(self.setProgress)
  642. revdep.action = lambda x: (
  643. self.endTask(), self.startTask(_("Assigning files to packages"))
  644. if "Assign" in revdep else None)
  645. self._startEmerging(emerge)
  646. return True
  647. def _display_pretty_package_list(self, pkglist, remove_list=False):
  648. """
  649. Отобразить список пакетов в "удобочитаемом" виде
  650. """
  651. _print = self.color_print
  652. ebuild_color = TextState.Colors.GREEN
  653. binary_color = TextState.Colors.PURPLE
  654. remove_color = TextState.Colors.LIGHT_RED
  655. flag_map = {"updating":
  656. _print.foreground(TextState.Colors.LIGHT_CYAN)("U"),
  657. "reinstall":
  658. _print.foreground(TextState.Colors.YELLOW)("rR"),
  659. "new":
  660. _print.foreground(TextState.Colors.LIGHT_GREEN)("N"),
  661. "newslot":
  662. _print.foreground(TextState.Colors.LIGHT_GREEN)("NS"),
  663. "downgrading": (
  664. _print.foreground(TextState.Colors.LIGHT_CYAN)("U") +
  665. _print.foreground(TextState.Colors.LIGHT_BLUE)("D"))}
  666. for pkg in sorted([PackageInformation.add_info(x) for x in
  667. pkglist],
  668. key=lambda y: y['CATEGORY/PN']):
  669. install_flag = ""
  670. if remove_list:
  671. pkgcolor = _print.foreground(remove_color)
  672. else:
  673. for flag in flag_map:
  674. if pkg[flag]:
  675. install_flag = "(%s) " % flag_map[flag]
  676. break
  677. if self.is_binary_pkg(pkg):
  678. pkgcolor = _print.foreground(binary_color)
  679. else:
  680. pkgcolor = _print.foreground(ebuild_color)
  681. if pkg.info['DESCRIPTION']:
  682. fullname = "%s " % _(pkg.info['DESCRIPTION'])
  683. fullname = fullname[:1].upper() + fullname[1:]
  684. else:
  685. fullname = ""
  686. shortname = pkgcolor("%s-%s" % (pkg["CATEGORY/PN"], pkg["PVR"]))
  687. if "SIZE" in pkg and pkg['SIZE'] and pkg["SIZE"] != "0 kB":
  688. size = " (%s)" % pkg["SIZE"]
  689. else:
  690. size = ""
  691. mult = _print.bold("*")
  692. self.printDefault(
  693. _u8("&nbsp;{mult} {fullname}{flag}{shortname}{size}").format(
  694. mult=_u8(mult), fullname=_u8(fullname), shortname=_u8(shortname),
  695. size=_u8(size),
  696. flag=_u8(install_flag)))
  697. def _display_install_package(self, emerge, emergelike=False):
  698. """
  699. Отобразить список устанавливаемых пакетов
  700. """
  701. # подробный список пакетов
  702. _print = self.color_print
  703. if emergelike:
  704. self.printPre(str(emerge.install_packages))
  705. else:
  706. pkglist = emerge.install_packages.list
  707. self.printSUCCESS(_print(
  708. _("Listing packages for installation")))
  709. self._display_pretty_package_list(pkglist)
  710. if emerge.install_packages.remove_list:
  711. self.printSUCCESS(_print(
  712. _("Listing packages for removal")))
  713. self._display_pretty_package_list(
  714. emerge.install_packages.remove_list, remove_list=True)
  715. if len(emerge.install_packages.list) > 0:
  716. install_mess = (_("{count} packages will be installed").format(
  717. count=len(emerge.install_packages.list)) + ", ")
  718. else:
  719. install_mess = ""
  720. if str(emerge.download_size) != "0 kB":
  721. self.printSUCCESS(_("{install}{size} will be downloaded").format(
  722. install=install_mess,
  723. size=str(emerge.download_size)))
  724. def _display_remove_list(self, emerge):
  725. """
  726. Отобразить список удаляемых пакетов
  727. """
  728. # подробный список пакетов
  729. if self.clVars.Get('update.cl_update_emergelist_set') == 'on':
  730. self.printPre(self._emerge_translate(
  731. emerge.uninstall_packages.verbose_result))
  732. else:
  733. _print = self.color_print
  734. pkglist = emerge.uninstall_packages.list
  735. self.printSUCCESS(_print.bold(
  736. _("Listing packages for removal")))
  737. self._display_pretty_package_list(pkglist, remove_list=True)
  738. def mark_schedule(self):
  739. """
  740. Установить отметку о запуске запланированной проверки
  741. """
  742. SystemIni(self.clVars).setVar('system', {'last_check': str(int(time.time()))})
  743. def get_default_emerge_opts(self):
  744. if self.clVars.GetBool('cl_update_with_bdeps_set'):
  745. bdeps = " --with-bdeps=y"
  746. else:
  747. bdeps = " --with-bdeps=n"
  748. return self.clVars.Get('cl_emerge_default_opts') + bdeps
  749. def premerge(self, param, *packages):
  750. """
  751. Вывести информацию об обновлении
  752. """
  753. deo = self.get_default_emerge_opts()
  754. param = [param, "-pv"]
  755. with EmergeParser(EmergeCommand(list(packages), emerge_default_opts=deo,
  756. extra_params=param)) as emerge:
  757. try:
  758. emerge.run()
  759. if not emerge.install_packages.list:
  760. self.printSUCCESS(_("The system is up to date"))
  761. self.set_need_update(False)
  762. return True
  763. emergelike = self.clVars.Get('cl_update_emergelist_set') == 'on'
  764. self._display_install_package(emerge, emergelike)
  765. if str(emerge.skipped_packages):
  766. self._display_error(emerge.skipped_packages)
  767. except EmergeError:
  768. self.set_need_update(False)
  769. self._display_install_package(emerge, emergelike=True)
  770. self._display_error(emerge.prepare_error)
  771. raise
  772. if self.clVars.Get('cl_update_pretend_set') == 'on':
  773. # установить кэш: есть обновления
  774. self.set_need_update()
  775. return True
  776. self.set_need_update(False)
  777. answer = self.askConfirm(
  778. _("Would you like to merge these packages?"), "yes")
  779. if answer == "no":
  780. raise KeyboardInterrupt
  781. return "yes"
  782. return True
  783. def set_need_update(self, val=True):
  784. """
  785. Установить флаг: есть обновления
  786. """
  787. if self.clVars.Get('update.cl_update_autocheck_set') == 'off':
  788. val = False
  789. UpdateInfo.set_update_ready(val)
  790. return True
  791. def _emerge_translate(self, s):
  792. """
  793. Перевести текст из emerge
  794. """
  795. return RegexpLocalization('cl_emerge').translate(str(s))
  796. def setUpToDateCache(self):
  797. """
  798. Установить кэш - "нет пакетов для обновления"
  799. """
  800. #self.updateCache(PackageList([]))
  801. self.set_need_update(False)
  802. return True
  803. def _startEmerging(self, emerge):
  804. """
  805. Настроить и выполнить emerge
  806. """
  807. if emerge.install_packages and emerge.install_packages.list:
  808. for pkg in emerge.install_packages.list:
  809. rv = pkg.get('REPLACING_VERSIONS', '')
  810. if rv:
  811. self.update_map["{CATEGORY}/{PF}".format(**pkg)] = \
  812. rv.partition(":")[0]
  813. emerge.command.send("yes\n")
  814. emerge.emerging.add_observer(self._printEmergePackage)
  815. emerge.installing.add_observer(self._printInstallPackage)
  816. emerge.uninstalling.add_observer(self._printUninstallPackage)
  817. emerge.fetching.add_observer(self._printFetching)
  818. def cancel_observing_fetch(fn):
  819. emerge.fetching.clear_observers()
  820. emerge.fetching.add_observer(cancel_observing_fetch)
  821. try:
  822. emerge.run()
  823. except EmergeError:
  824. if emerge.emerging_error:
  825. self._display_error(emerge.emerging_error.log)
  826. else:
  827. self._display_error(emerge.prepare_error)
  828. raise
  829. def _display_error(self, error):
  830. lines_num = int(self.clVars.Get('update.cl_update_lines_limit'))
  831. error = "<br/>".join(str(error).split('<br/>')[-lines_num:])
  832. self.printPre(self._emerge_translate(error))
  833. def emerge(self, use, param, *packages):
  834. """
  835. Выполнить сборку пакета
  836. """
  837. deo = self.get_default_emerge_opts()
  838. if not packages:
  839. packages = [param]
  840. extra_params = None
  841. else:
  842. extra_params = [param]
  843. command = EmergeCommand(list(packages), emerge_default_opts=deo,
  844. extra_params=extra_params,
  845. use=use)
  846. if self.clVars.Get('cl_chroot_path') != '/':
  847. command = Chroot(self.clVars.Get('cl_chroot_path'), command)
  848. with EmergeParser(command) as emerge:
  849. try:
  850. emerge.question.action = lambda x: False
  851. emerge.run()
  852. if not emerge.install_packages.list:
  853. return True
  854. except EmergeError:
  855. self._display_error(emerge.prepare_error)
  856. raise
  857. self._startEmerging(emerge)
  858. return True
  859. def emerge_ask(self, pretend, *params):
  860. """
  861. Вывести информацию об обновлении
  862. """
  863. deo = self.get_default_emerge_opts()
  864. param = [x for x in params if x.startswith("-")]
  865. packages = [x for x in params if not x.startswith("-")]
  866. command = EmergeCommand(list(packages), emerge_default_opts=deo,
  867. extra_params=param)
  868. with EmergeParser(command) as emerge:
  869. try:
  870. emerge.question.action = lambda x: False
  871. emerge.run()
  872. if emerge.install_packages.list:
  873. emergelike = self.clVars.Get(
  874. 'update.cl_update_emergelist_set') == 'on'
  875. self._display_install_package(emerge, emergelike)
  876. if emerge.skipped_packages:
  877. self._display_error(emerge.skipped_packages)
  878. if not pretend:
  879. answer = self.askConfirm(
  880. _("Would you like to merge these packages?"), "yes")
  881. if answer == "no":
  882. emerge.command.send("no\n")
  883. raise KeyboardInterrupt
  884. else:
  885. return True
  886. else:
  887. self.set_need_update(False)
  888. self.printSUCCESS(_("The system is up to date"))
  889. except EmergeError:
  890. self.set_need_update(False)
  891. self._display_install_package(emerge, emergelike=True)
  892. self._display_error(emerge.prepare_error)
  893. raise
  894. self._startEmerging(emerge)
  895. return True
  896. def depclean(self):
  897. """
  898. Выполнить очистку системы от лишних пакетов
  899. """
  900. deo = self.get_default_emerge_opts()
  901. emerge = None
  902. try:
  903. emerge = EmergeParser(EmergeCommand(["--depclean"],
  904. emerge_default_opts=deo))
  905. outdated_kernel = False
  906. try:
  907. emerge.question.action = lambda x: False
  908. emerge.run()
  909. if not emerge.uninstall_packages.list:
  910. UpdateInfo(self.clVars).outdated_kernel = False
  911. return True
  912. kernel_pkg = self.clVars.Get('cl_update_kernel_pkg')
  913. if any(("%s-%s" % (x['CATEGORY/PN'], x['PVR'])) == kernel_pkg
  914. for x in emerge.uninstall_packages.list):
  915. pkglist = [
  916. "=%s-%s" % (x['CATEGORY/PN'], x['PVR']) for x in
  917. emerge.uninstall_packages.list
  918. if ("%s-%s" % (x['CATEGORY/PN'],
  919. x['PVR'])) != kernel_pkg]
  920. emerge.command.send('n\n')
  921. emerge.close()
  922. emerge = None
  923. if not pkglist:
  924. UpdateInfo(self.clVars).outdated_kernel = True
  925. return True
  926. emerge = EmergeParser(
  927. EmergeCommand(pkglist,
  928. extra_params=["--unmerge", '--ask=y'],
  929. emerge_default_opts=deo))
  930. emerge.question.action = lambda x: False
  931. emerge.run()
  932. outdated_kernel = True
  933. else:
  934. outdated_kernel = False
  935. self._display_remove_list(emerge)
  936. except EmergeError:
  937. self._display_error(emerge.prepare_error)
  938. raise
  939. if (self.askConfirm(
  940. _("Would you like to unmerge these unused packages "
  941. "(recommended)?")) != 'yes'):
  942. return True
  943. UpdateInfo(self.clVars).outdated_kernel = outdated_kernel
  944. self._startEmerging(emerge)
  945. finally:
  946. if emerge:
  947. emerge.close()
  948. return True
  949. def update_task(self, task_name):
  950. """
  951. Декоратор для добавления меток запуска и останова задачи
  952. """
  953. def decor(f):
  954. def wrapper(*args, **kwargs):
  955. logger = EmergeLog(EmergeLogNamedTask(task_name))
  956. logger.mark_begin_task()
  957. ret = f(*args, **kwargs)
  958. if ret:
  959. logger.mark_end_task()
  960. return ret
  961. return wrapper
  962. return decor
  963. def migrateCacheRepository(self, url, branch, storage):
  964. """
  965. Перенести репозиторий из кэша в локальный
  966. """
  967. rep = storage.get_repository(url, branch)
  968. if rep:
  969. rep.storage = storage.storages[0]
  970. self.clVars.Invalidate('cl_update_profile_storage')
  971. return True
  972. def reconfigureProfileVars(self, profile_dv, chroot):
  973. """
  974. Синхронизировать репозитории
  975. Настройка переменных для выполнения синхронизации репозиториев
  976. """
  977. dv = self.clVars
  978. try:
  979. if not profile_dv:
  980. raise UpdateError(
  981. _("Failed to use the new profile. Try again."))
  982. for var_name in ('cl_update_rep_path',
  983. 'cl_update_rep_url',
  984. 'cl_update_rep_name',
  985. 'cl_update_branch',
  986. 'cl_update_binhost_list',
  987. 'cl_update_binhost_unstable_list',
  988. 'cl_update_binhost_stable_set',
  989. 'cl_update_binhost_stable_opt_set',
  990. 'cl_update_branch_name',
  991. 'cl_profile_system',
  992. 'cl_update_rep'):
  993. dv.Set(var_name, profile_dv.Get(var_name), force=True)
  994. dv.Set('cl_chroot_path', chroot, force=True)
  995. except DataVarsError as e:
  996. error = UpdateError(_("Wrong profile"))
  997. error.addon = e
  998. raise error
  999. return True
  1000. def setProfile(self, profile_shortname):
  1001. profile = self.clVars.Select('cl_update_profile_path',
  1002. where='cl_update_profile_shortname',
  1003. eq=profile_shortname, limit=1)
  1004. if not profile:
  1005. raise UpdateError(_("Failed to determine profile %s") %
  1006. self.clVars.Get('cl_update_profile_system'))
  1007. profile_path = path.relpath(profile, '/etc/portage')
  1008. try:
  1009. profile_file = '/etc/portage/make.profile'
  1010. if not path.exists(
  1011. path.join(path.dirname(profile_file), profile_path)):
  1012. raise UpdateError(
  1013. _("Failed to set the profile: %s") % _("Profile not found"))
  1014. for rm_fn in filter(path.lexists,
  1015. ('/etc/make.profile',
  1016. '/etc/portage/make.profile')):
  1017. os.unlink(rm_fn)
  1018. os.symlink(profile_path, profile_file)
  1019. except (OSError, IOError) as e:
  1020. raise UpdateError(_("Failed to set the profile: %s") % str(e))
  1021. return True
  1022. def applyProfileTemplates(self, useClt=None, cltFilter=False,
  1023. useDispatch=True, action="merge"):
  1024. """
  1025. Наложить шаблоны из профиля
  1026. """
  1027. from calculate.lib.cl_template import TemplatesError, ProgressTemplate
  1028. dv = DataVarsUpdate()
  1029. try:
  1030. dv.importUpdate()
  1031. dv.flIniFile()
  1032. dv.Set('cl_action', action, force=True)
  1033. try:
  1034. dv.Set('cl_templates_locate',
  1035. self.clVars.Get('cl_update_templates_locate'))
  1036. except VariableError:
  1037. self.printERROR(_("Failed to apply profiles templates"))
  1038. return True
  1039. dv.Set("cl_chroot_path", '/', True)
  1040. dv.Set("cl_root_path", '/', True)
  1041. for copyvar in ("cl_dispatch_conf", "cl_verbose_set",
  1042. "update.cl_update_world"):
  1043. dv.Set(copyvar, self.clVars.Get(copyvar), True)
  1044. # определение каталогов содержащих шаблоны
  1045. useClt = useClt in ("on", True)
  1046. self.addProgress()
  1047. nullProgress = lambda *args, **kw: None
  1048. dispatch = self.dispatchConf if useDispatch else None
  1049. clTempl = ProgressTemplate(nullProgress, dv, cltObj=useClt,
  1050. cltFilter=cltFilter,
  1051. printSUCCESS=self.printSUCCESS,
  1052. printWARNING=self.printWARNING,
  1053. askConfirm=self.askConfirm,
  1054. dispatchConf=dispatch,
  1055. printERROR=self.printERROR)
  1056. try:
  1057. clTempl.applyTemplates()
  1058. if clTempl.hasError():
  1059. if clTempl.getError():
  1060. raise TemplatesError(clTempl.getError())
  1061. finally:
  1062. if clTempl:
  1063. if clTempl.cltObj:
  1064. clTempl.cltObj.closeFiles()
  1065. clTempl.closeFiles()
  1066. finally:
  1067. dv.close()
  1068. return True
  1069. def cleanpkg(self):
  1070. """
  1071. Очистить PKGDIR и DISTFILES в текущей системе
  1072. """
  1073. portdirs = ([self.clVars.Get('cl_portdir')] +
  1074. self.clVars.Get('cl_portdir_overlay'))
  1075. pkgfiles = get_packages_files_directory(*portdirs)
  1076. distdirfiles = get_manifest_files_directory(*portdirs)
  1077. distdir = self.clVars.Get('install.cl_distfiles_path')
  1078. pkgdir = self.clVars.Get('cl_pkgdir')
  1079. logger = log("update_cleanpkg.log",
  1080. filename="/var/log/calculate/update_cleanpkg.log",
  1081. formatter="%(asctime)s - %(clean)s - %(message)s")
  1082. return self._cleanpkg(
  1083. distdir, pkgdir, distdirfiles, pkgfiles, logger)
  1084. def _update_binhost_packages(self):
  1085. os.system('/usr/sbin/emaint binhost -f &>/dev/null')
  1086. def _cleanpkg(self, distdir, pkgdir, distdirfiles, pkgfiles, logger):
  1087. """
  1088. Общий алгоритм очистки distfiles и pkgdir от устаревших пакетов
  1089. """
  1090. skip_files = ["/metadata.dtd", "/Packages"]
  1091. try:
  1092. if self.clVars.Get('client.os_remote_auth'):
  1093. skip_files += ['portage_lockfile']
  1094. except DataVarsError:
  1095. pass
  1096. for cleantype, filelist in (
  1097. ("packages",
  1098. get_remove_list(pkgdir, list(pkgfiles), depth=4)),
  1099. ("distfiles",
  1100. get_remove_list(distdir, list(distdirfiles), depth=1))):
  1101. removelist = []
  1102. for fn in filelist:
  1103. try:
  1104. if not any(fn.endswith(x) for x in skip_files):
  1105. os.unlink(fn)
  1106. removelist.append(path.basename(fn))
  1107. except OSError:
  1108. pass
  1109. removelist_str = ",".join(removelist)
  1110. if removelist_str:
  1111. logger.info(removelist_str, extra={'clean': cleantype})
  1112. if cleantype == "packages":
  1113. try:
  1114. self._update_binhost_packages()
  1115. for dn in listDirectory(pkgdir, fullPath=True):
  1116. if path.isdir(dn) and not listDirectory(dn):
  1117. os.rmdir(dn)
  1118. except OSError:
  1119. pass
  1120. return True
  1121. def updateSetupCache(self):
  1122. cache = SetupCache(self.clVars)
  1123. cache.update(force=True)
  1124. return True
  1125. def get_bin_cache_filename(self):
  1126. return pathJoin(self.clVars.Get('cl_chroot_path'),
  1127. LayeredIni.IniPath.Grp)
  1128. def update_local_info_binhost(self, write_binhost=True):
  1129. """
  1130. Проверить, что доступен хотя бы один из binhost'ов
  1131. :return:
  1132. """
  1133. hosts = self.clVars.Get("update.cl_update_binhost_host")
  1134. datas = self.clVars.Get("update.cl_update_binhost_revisions")
  1135. if not hosts:
  1136. self.delete_binhost()
  1137. raise UpdateError(_("Failed to find the server with "
  1138. "appropriate updates"))
  1139. else:
  1140. with writeFile(self.get_bin_cache_filename()) as f:
  1141. f.write(datas[0].strip()+"\n")
  1142. if write_binhost:
  1143. if hosts[0] != self.clVars.Get('update.cl_update_binhost'):
  1144. self.refresh_binhost = True
  1145. self.clVars.Set('cl_update_package_cache_set', 'on')
  1146. self.clVars.Write('cl_update_binhost', hosts[0], location="system")
  1147. new_ts = self.clVars.Get("update.cl_update_binhost_timestamp")
  1148. if new_ts:
  1149. new_ts = new_ts[0]
  1150. if new_ts.isdigit():
  1151. ini = SystemIni(self.clVars)
  1152. ini.setVar('system', {'last_update': new_ts})
  1153. if self.is_update_action(self.clVars.Get("cl_action")):
  1154. value = self.clVars.GetBool('update.cl_update_binhost_stable_set')
  1155. new_value = self.clVars.GetBool('update.cl_update_binhost_stable_opt_set')
  1156. if value != new_value:
  1157. self.clVars.Write(
  1158. 'cl_update_binhost_stable_set',
  1159. self.clVars.Get('update.cl_update_binhost_stable_opt_set'),
  1160. location="system")
  1161. return True
  1162. def is_update_action(self, action):
  1163. return action == 'sync'
  1164. def save_with_bdeps(self):
  1165. oldval = self.clVars.Get('cl_update_with_bdeps_set')
  1166. newval = self.clVars.Get('cl_update_with_bdeps_opt_set')
  1167. if oldval != newval:
  1168. self.clVars.Write('cl_update_with_bdeps_set', newval,
  1169. location="system")
  1170. self.clVars.Set('cl_update_force_depclean_set', 'on')
  1171. return True
  1172. def message_binhost_changed(self):
  1173. if self.refresh_binhost:
  1174. self.printWARNING(_("Update server was changed to %s") %
  1175. self.clVars.Get('cl_update_binhost'))
  1176. else:
  1177. self.printSUCCESS(_("Update server %s") %
  1178. self.clVars.Get('cl_update_binhost'))
  1179. return True
  1180. def delete_binhost(self):
  1181. self.clVars.Delete('cl_update_binhost', location="system")
  1182. try:
  1183. bin_cache_fn = self.get_bin_cache_filename()
  1184. if path.exists(bin_cache_fn):
  1185. os.unlink(bin_cache_fn)
  1186. except OSError:
  1187. raise UpdateError(
  1188. _("Failed to remove cached ini.env of binary repository"))
  1189. try:
  1190. for varname in ('update.cl_update_package_cache',
  1191. 'update.cl_update_package_cache_sign'):
  1192. fn = self.clVars.Get(varname)
  1193. if path.exists(fn):
  1194. os.unlink(fn)
  1195. except OSError:
  1196. raise UpdateError(
  1197. _("Failed to remove cached Package index"))
  1198. # удалить binhost
  1199. binhost_fn = self.inchroot(
  1200. self.clVars.Get("update.cl_update_portage_binhost_path"))
  1201. if path.exists(binhost_fn):
  1202. os.unlink(binhost_fn)
  1203. return True
  1204. def update_binhost_list(self, dv=None):
  1205. """
  1206. Обновить список binhost'ов после обновления до master веток
  1207. :return:
  1208. """
  1209. changes = False
  1210. try:
  1211. if dv is None:
  1212. dv = DataVarsUpdate()
  1213. dv.importUpdate()
  1214. dv.flIniFile()
  1215. for varname in ('update.cl_update_binhost_list',
  1216. 'update.cl_update_binhost_unstable_list',
  1217. 'update.cl_update_binhost_timestamp_path',
  1218. 'update.cl_update_binhost_revision_path'):
  1219. new_value = dv.Get(varname)
  1220. old_value = self.clVars.Get(varname)
  1221. if new_value != old_value:
  1222. changes = True
  1223. self.clVars.Set(varname, new_value, force=True)
  1224. except DataVarsError as e:
  1225. raise UpdateError(_("Failed to get values for binhost search"))
  1226. if not changes:
  1227. return False
  1228. self.create_binhost_data()
  1229. return True
  1230. def drop_binhosts(self, dv):
  1231. """
  1232. Обновление до master веток
  1233. """
  1234. branch = dv.Get('update.cl_update_branch')
  1235. revs = [
  1236. branch for x in dv.Get('update.cl_update_rep_name')
  1237. ]
  1238. dv.Set('update.cl_update_branch_name', revs)
  1239. dv.Invalidate('update.cl_update_rep_rev')
  1240. return True
  1241. def inchroot(self, fn):
  1242. return pathJoin(self.clVars.Get("cl_chroot_path"), fn)
  1243. def prepare_gpg(self):
  1244. """
  1245. Получить объект для проверки подписи, либо получить заглушку
  1246. """
  1247. gpg_force = self.clVars.Get('cl_update_gpg_force')
  1248. gpg_keys = [self.inchroot(x)
  1249. for x in self.clVars.Get('cl_update_gpg_keys')]
  1250. if gpg_force == "skip":
  1251. return True
  1252. gpgtmpdir = "/var/calculate/tmp/update"
  1253. if not path.exists(gpgtmpdir):
  1254. makeDirectory(gpgtmpdir)
  1255. gpg = GPG(tempfile.mkdtemp(dir=gpgtmpdir,
  1256. prefix="gpg-"))
  1257. for keyfn in gpg_keys:
  1258. if path.exists(keyfn):
  1259. try:
  1260. key = readFile(keyfn)
  1261. gpg.import_key(key)
  1262. except GPGError as e:
  1263. self.printWARNING(_("Failed to load public keys from '%s' "
  1264. "for signature checking") % keyfn)
  1265. if not gpg.count_public():
  1266. if gpg_force == "force":
  1267. raise UpdateError(_("Public keys for Packages signature checking not found"))
  1268. else:
  1269. return True
  1270. self.clVars.Set('update.cl_update_gpg', gpg, force=True)
  1271. return True
  1272. def download_packages(self, url_binhost, packages_fn, packages_sign_fn, gpg):
  1273. quite_unlink(packages_fn)
  1274. orig_packages = Binhosts.fetch_packages(url_binhost)
  1275. try:
  1276. with writeFile(packages_fn) as f:
  1277. pi = PackagesIndex(orig_packages)
  1278. pi["TTL"] = str(30 * DAYS)
  1279. pi["DOWNLOAD_TIMESTAMP"] = str(int(time.time()))
  1280. pi.write(f)
  1281. except (OSError, IOError):
  1282. raise UpdateError(_("Failed to save Packages"))
  1283. self.endTask(True)
  1284. self.startTask(_("Check packages index signature"))
  1285. if not gpg:
  1286. self.endTask("skip")
  1287. self.clVars.Set('cl_update_package_cache_set', Variable.Off, force=True)
  1288. return True
  1289. try:
  1290. Binhosts.check_packages_signature(
  1291. url_binhost, orig_packages, gpg)
  1292. with writeFile(packages_sign_fn) as f:
  1293. f.write(Binhosts.fetch_packages_sign(url_binhost))
  1294. except BinhostSignError:
  1295. for fn in (packages_fn, packages_sign_fn):
  1296. if path.exists(fn):
  1297. try:
  1298. os.unlink(fn)
  1299. except OSError:
  1300. pass
  1301. self.clVars.Set("update.cl_update_bad_sign_set", Variable.On)
  1302. self.clVars.Set('update.cl_update_binhost_recheck_set', Variable.On)
  1303. self.clVars.Set('cl_update_package_cache_set', Variable.Off, force=True)
  1304. raise
  1305. return True
  1306. class Reason(object):
  1307. Success = 0
  1308. BadSign = 1
  1309. Outdated = 2
  1310. Skip = 3
  1311. Updating = 4
  1312. WrongBinhost = 5
  1313. BadEnv = 6
  1314. EnvNotFound = 7
  1315. SkipSlower = 8
  1316. UnknownError = 9
  1317. @staticmethod
  1318. def humanReadable(reason):
  1319. return {
  1320. Update.Reason.WrongBinhost: "FAILED (Wrong binhost)",
  1321. Update.Reason.Outdated: "OUTDATED",
  1322. Update.Reason.Updating: "UPDATING",
  1323. Update.Reason.BadEnv: "FAILED (Bad env)",
  1324. Update.Reason.EnvNotFound: "FAILED (Env not found)",
  1325. Update.Reason.UnknownError: "FAILED (Unknown error)",
  1326. Update.Reason.BadSign: "FAILED (Bad sign)",
  1327. Update.Reason.Skip: "SKIP",
  1328. Update.Reason.SkipSlower: "",
  1329. Update.Reason.Success: ""
  1330. }.get(reason,reason)
  1331. def _get_binhost_logger(self):
  1332. return log("binhost-scan.log",
  1333. filename=pathJoin(
  1334. self.clVars.Get('cl_chroot_path'),
  1335. "/var/log/calculate/binhost-scan.log"),
  1336. formatter="%(message)s")
  1337. def get_arch_machine(self):
  1338. return self.clVars.Get('os_arch_machine')
  1339. @variable_module("update")
  1340. def create_binhost_data(self):
  1341. dv = self.clVars
  1342. last_ts = dv.Get('cl_update_last_timestamp')
  1343. if dv.GetBool('cl_update_binhost_stable_opt_set'):
  1344. binhost_list = dv.Get('cl_update_binhost_list')
  1345. else:
  1346. binhost_list = dv.Get('cl_update_binhost_unstable_list')
  1347. self.binhosts_data = Binhosts(
  1348. # значение малозначимо, поэтому берётся из собирающей системы
  1349. dv.GetInteger('cl_update_binhost_timeout'),
  1350. dv.Get('cl_update_binhost_revision_path'),
  1351. dv.Get('cl_update_binhost_timestamp_path'),
  1352. last_ts, binhost_list,
  1353. self.get_arch_machine(),
  1354. gpg=dv.Get('update.cl_update_gpg'))
  1355. return True
  1356. @variable_module("update")
  1357. def _search_best_binhost(self, binhosts_data, stabilization):
  1358. if not self.clVars.Get('cl_ebuild_phase'):
  1359. logger = self._get_binhost_logger()
  1360. if logger:
  1361. logger.info(
  1362. "Started scan on: {date}, current timestamp: {ts}".format(
  1363. date=time.ctime(), ts=binhosts_data.last_ts))
  1364. retval = []
  1365. skip_check_status = False
  1366. actual_reason = self.Reason.UnknownError
  1367. for binhost in sorted(binhosts_data.get_binhosts(), reverse=True):
  1368. host = binhost.host
  1369. if not binhost.valid:
  1370. reason = self.Reason.WrongBinhost
  1371. elif binhost.outdated:
  1372. reason = self.Reason.Outdated
  1373. elif not skip_check_status:
  1374. status = binhost.status
  1375. if status is not binhosts_data.BinhostStatus.Success:
  1376. errors = {
  1377. binhosts_data.BinhostStatus.Updating: self.Reason.Updating,
  1378. binhosts_data.BinhostStatus.BadEnv: self.Reason.BadEnv,
  1379. binhosts_data.BinhostStatus.EnvNotFound: self.Reason.EnvNotFound
  1380. }
  1381. reason = errors.get(status, self.Reason.UnknownError)
  1382. elif binhost.bad_sign:
  1383. reason = self.Reason.BadSign
  1384. else:
  1385. # SUCCESS
  1386. if not binhost.downgraded or stabilization:
  1387. host = "-> %s" % host
  1388. reason = self.Reason.Success
  1389. else:
  1390. reason = self.Reason.Skip
  1391. elif binhost.downgraded:
  1392. reason = self.Reason.Skip
  1393. else:
  1394. reason = self.Reason.SkipSlower
  1395. if reason == self.Reason.Success:
  1396. retval.append([binhost.host, binhost.data,
  1397. str(binhost.timestamp),
  1398. str(binhost.duration)])
  1399. skip_check_status = True
  1400. if reason < actual_reason:
  1401. actual_reason = reason
  1402. logger.info("{host:<60} {speed:<7} {timestamp:<10} {reason}".format(
  1403. host=host, speed=float(binhost.duration) / 1000.0,
  1404. timestamp=binhost.timestamp,
  1405. reason=Update.Reason.humanReadable(reason)))
  1406. if not retval:
  1407. if actual_reason is self.Reason.BadSign:
  1408. raise UpdateError(_("Failed to find the reliable server with appropriate updates"))
  1409. elif actual_reason in (self.Reason.Outdated,
  1410. self.Reason.Skip,
  1411. self.Reason.Updating):
  1412. raise UpdateError(_("Failed to find the server with appropriate updates"))
  1413. else:
  1414. raise UpdateError(_("Failed to find the working server with updates"))
  1415. return retval
  1416. def check_current_binhost(self, binhost_url):
  1417. """
  1418. Проверка текущего сервера обновлений на валидность
  1419. """
  1420. if not binhost_url in self.binhosts_data.binhost_list:
  1421. raise UpdateError(_("Current binhost is absent in list of update servers"))
  1422. binhost = self.binhosts_data.get_binhost(binhost_url)
  1423. if binhost.valid and not binhost.outdated and not binhost.downgraded:
  1424. if binhost.status == self.binhosts_data.BinhostStatus.Success:
  1425. self.clVars.Set('update.cl_update_binhost_data',
  1426. [[binhost.host, binhost.data,
  1427. str(binhost.timestamp),
  1428. str(binhost.duration)]],
  1429. force=True)
  1430. self.endTask()
  1431. else:
  1432. if not binhost.valid:
  1433. raise UpdateError(
  1434. _("Current binhost {} is not valid").format(binhost_url))
  1435. elif binhost.outdated:
  1436. raise UpdateError(
  1437. _("Current binhost {} is outdated").format(binhost_url))
  1438. elif binhost.downgraded:
  1439. raise UpdateError(
  1440. _("Current binhost {} was downgraded").format(binhost_url))
  1441. if self.binhosts_data.gpg:
  1442. packages_fn = self.clVars.Get('update.cl_update_package_cache')
  1443. packages_sign_fn = self.clVars.Get('update.cl_update_package_cache_sign')
  1444. if path.exists(packages_fn) and path.exists(packages_sign_fn):
  1445. packages_sign = readFile(packages_sign_fn)
  1446. pi = PackagesIndex(readFile(packages_fn))
  1447. pi.clean()
  1448. try:
  1449. Binhosts.check_packages_signature(
  1450. None, pi.get_value(), self.binhosts_data.gpg,
  1451. sign=packages_sign)
  1452. return True
  1453. except BinhostSignError:
  1454. for fn in (packages_fn, packages_sign_fn):
  1455. if path.exists(fn):
  1456. try:
  1457. os.unlink(fn)
  1458. except OSError:
  1459. pass
  1460. if binhost.bad_sign:
  1461. raise UpdateError(
  1462. _("Current binhost {} has wrong signature").format(
  1463. binhost_url))
  1464. return True
  1465. @variable_module("update")
  1466. def detect_best_binhost(self):
  1467. # выполняется переход с серверов unstable обновлней на stable
  1468. # в этом случае не важно, что бинари могут старее текущих
  1469. if (self.clVars.GetBool('cl_update_binhost_stable_opt_set') and
  1470. not self.clVars.GetBool('cl_update_binhost_stable_set')):
  1471. stabilization = True
  1472. else:
  1473. stabilization = False
  1474. self.startTask("Searching new binhost")
  1475. retval = self._search_best_binhost(self.binhosts_data, stabilization)
  1476. self.clVars.Set('update.cl_update_binhost_data',
  1477. retval or Variable.EmptyTable, force=True)
  1478. self.endTask()
  1479. return True
  1480. def update_layman(self):
  1481. """
  1482. Обновить базу layman
  1483. :param builder_path:
  1484. :return:
  1485. """
  1486. cmd = "/usr/bin/layman"
  1487. cmd_path = self.get_prog_path(cmd)
  1488. if not cmd_path:
  1489. raise UpdateError(_("Failed to find the %s command") % cmd)
  1490. layman = emerge_parser.CommandExecutor(cmd_path, ["-f"])
  1491. layman.execute()
  1492. return layman.success()