Merge branch 'uu_test' into 'backend_uu'

add timestamp check before each update;move fix at beginning of uu-shutdown

See merge request kylin-desktop/update-manager-group/kylin-system-updater!429
This commit is contained in:
luoxueyi 2022-06-01 01:59:20 +00:00
commit ab48989913
6 changed files with 239 additions and 63 deletions

View File

@ -1,7 +1,7 @@
[autoUpgradePolicy]
preDownload = on
autoUpgradeState = on
downloadMode = timing
downloadTime = 10:00
installMode = bshutdown
installMode = timing
upgradeInverval = 7

View File

@ -0,0 +1 @@
0

View File

@ -14,6 +14,7 @@ backend/SystemUpdater/Core/*.py /usr/share/kylin-system-updater/SystemUpdater/Co
backend/build/mo/* /usr/share/locale/
backend/data/system-updater.conf /var/lib/kylin-system-updater/
backend/data/unattended-upgrades-policy.conf /var/lib/unattended-upgrades/
backend/data/unattended-upgrades-timestamp /var/lib/unattended-upgrades/
backend/data/cn.kylinos.KylinSystemUpdater.policy /usr/share/polkit-1/actions/
backend/data/system-updater-uncoverable.conf /usr/share/kylin-system-updater/

View File

@ -128,10 +128,11 @@ DISTRO_ID = subprocess.check_output(
DEVEL_UNTIL_RELEASE = datetime.timedelta(days=21)
# progress information is written here
PROGRESS_LOG = "/var/run/kylin-unattended-upgrades.progress"
PID_FILE = "/var/run/kylin-unattended-upgrades.pid"
PROGRESS_LOG = "/var/run/unattended-upgrades.progress"
PID_FILE = "/var/run/unattended-upgrades.pid"
LOCK_FILE = "/var/run/kylin-unattended-upgrade.lock"
NOTIFICATION_PIPE = '/tmp/notification.pipe'
TIME_STAMP = "/var/lib/unattended-upgrades/unattended-upgrades-timestamp"
# 禁止关机锁文件路径
FILELOCK_PATH = "/tmp/lock/"
SHUTDOWN_BLOCK_FILELOCK = "kylin-update.lock"
@ -411,6 +412,9 @@ class KylinSystemUpdater:
self.update_interface = dbus.Interface(self.update_proxy,dbus_interface='com.kylin.systemupgrade.interface')
self.success = False
def DataBackendCollect(self,updateinfo,json_file):
self.update_interface.DataBackendCollect(updateinfo,json_file)
def GetConfigValue(self,section,value):
return self.update_interface.GetConfigValue(section,value)
@ -928,6 +932,7 @@ class LogInstallProgress(apt.progress.base.InstallProgress):
self.max_delay = 3600
def status_change(self, pkg, percent, status):
'''
if self.start_time is None:
self.start_time = time.time()
else:
@ -935,13 +940,34 @@ class LogInstallProgress(apt.progress.base.InstallProgress):
logging.warning(_(
"Giving up on lockfile after %s minutes of delay"),
self.max_delay / 60)
sys.exit(1)
sys.exit(1)
'''
# type: (str, float, str) -> None
with open(self.progress_log, "w") as f:
per=str(int(float(percent)))
f.write("%s"%per)
#f.write(_("Progress: %s %% (%s)") % (percent, pkg))
if re.search("Installed",status):
UpdateInfos = {}
UpdateInfos.update({"packageName":str(pkg)})
UpdateInfos.update({"source":"kylin unattended upgrade"})
UpdateInfos.update({"status":1})
json_file = json.dumps(UpdateInfos.copy())
UpdateInfos.clear()
self.update_interface.DataBackendCollect("UpdateInfos",json_file)
def error(self,pkg, errormsg):
UpdateInfos = {}
UpdateInfos.update({"packageName":str(pkg)})
UpdateInfos.update({"source":"kylin unattended upgrade"})
UpdateInfos.update({"status":0})
UpdateInfos.update({"errorCode":str(errormsg)})
json_file = json.dumps(UpdateInfos.copy())
UpdateInfos.clear()
kylin_system_updater.DataBackendCollect("UpdateInfos",json_file)
def _fixup_fds(self):
# () -> None
required_fds = [0, 1, 2, # stdin, stdout, stderr
@ -2098,7 +2124,7 @@ def _get_logdir():
def _setup_logging(options,logfile):
# type: (Options) -> StringIO
# ensure this is run only once
if len(logging.root.handlers) > 0:
@ -2462,6 +2488,12 @@ def do_auto_remove(cache, # type: UnattendedUpgradesCache
def clean_downloaded_packages(fetcher):
# type: (apt_pkg.Acquire) -> None
for item in fetcher.items:
try:
os.unlink(item.destfile)
except OSError:
pass
'''
archivedir = os.path.dirname(
apt_pkg.config.find_dir("Dir::Cache::archives"))
for item in fetcher.items:
@ -2470,6 +2502,7 @@ def clean_downloaded_packages(fetcher):
os.unlink(item.destfile)
except OSError:
pass
'''
def is_update_day():
@ -2561,6 +2594,8 @@ def main(options, rootdir="/"):
'''
if res.success and len(res.pkgs) > 0 and res.result_str == "total_install":
logging.info("total install")
with open(TIME_STAMP,'w') as f:
f.write(time.time())
kylin_system_updater.SetConfigValue("SYSTEM","os_version",release)
kylin_system_updater.SetConfigValue("SYSTEM","update_version",original_version)
else:
@ -2726,6 +2761,7 @@ def run(options, # type: Options
'''
#kylin_system_updater = KylinSystemUpdater()
'''
if kylin_system_updater.GetUnattendedUpgradeValue:
pass
else:
@ -2733,6 +2769,7 @@ def run(options, # type: Options
kylin_system_updater.ConnectToSignals()
kylin_system_updater.GetWhiteList()
kylin_system_updater.RunMainloop()
'''
# check and get lock
try:
apt_pkg.pkgsystem_lock()
@ -2907,7 +2944,8 @@ def run(options, # type: Options
logfile_dpkg)
unLockedEnableShutdown()
subprocess.Popen('dbus-send --system --type=signal / com.kylin.install.notification.InstallFinish',shell=True)
if pkg_install_success:
if pkg_install_success:
clean_downloaded_packages(fetcher)
kylin_system_updater.CheckRebootRequired("unattended-upgrades")
install_result = ''
logging.debug("pkg number:%d,pkg in whitelist number:%d"%(len(pkgs),len(namelist_with_version)))
@ -2951,28 +2989,32 @@ def run(options, # type: Options
break
#fetcher_statistics.ResetFetcher(fetcher)
#fetcher_statistics.GetAquireStatisticsOfPkgs()
if fetcher_statistics.incomplete_pkg_amount == 0:
logging.info("pkg number:%d,shutdown delay time:%d s"%(len(pkgs),30*len(pkgs)))
login_manager.SetExtraInhibitShutdownDelaySec(30*len(pkgs))
docker_image_fetch_result = None
#docker image fetch for mavis and laika
if os.path.exists("/usr/bin/service_runtime_ota.sh"):
docker_image_fetch_result = subprocess.run(["/usr/bin/service_runtime_ota.sh"], shell=True)
if docker_image_fetch_result.returncode == 0:
logging.info("all pkgs downloaded")
insmod = ReadValueFromFile("/var/lib/unattended-upgrades/unattended-upgrades-policy.conf","autoUpgradePolicy","installmode")
if insmod == 'bshutdown':
if len(pkgs_to_upgrade) > 0:
configfilemanager.AddFileName("OTA_PKGS_TO_INSTALL")
subprocess.Popen('dbus-send --system --type=signal / com.kylin.update.notification.DownloadFinish', shell=True)
kylin_system_updater.SetConfigValue('InstallMode','auto_install','True')
elif insmod == 'timing':
pass
insmod = ReadValueFromFile("/var/lib/unattended-upgrades/unattended-upgrades-policy.conf","autoUpgradePolicy","installmode")
if fetcher_statistics.incomplete_pkg_amount == 0 and len(pkgs_to_upgrade) > 0:
if os_release_info['PROJECT_CODENAME'] == 'V10SP1-edu' and os_release_info['SUB_PROJECT_CODENAME']=='mavis':
docker_image_fetch_result = None
#docker image fetch for mavis and laika
if os.path.exists("/usr/bin/service_runtime_ota.sh"):
docker_image_fetch_result = subprocess.run(["/usr/bin/service_runtime_ota.sh"], shell=True)
if docker_image_fetch_result.returncode == 0:
logging.info("all pkgs downloaded")
else:
pass
return UnattendedUpgradesResult(True,_("all pkgs downloaded"))
return UnattendedUpgradesResult(False,_("docker fetch failed"))
logging.info("pkg number:%d,shutdown delay time:%d s"%(len(pkgs),30*len(pkgs)))
login_manager.SetExtraInhibitShutdownDelaySec(30*len(pkgs))
configfilemanager.AddFileName("OTA_PKGS_TO_INSTALL")
subprocess.Popen('dbus-send --system --type=signal / com.kylin.update.notification.DownloadFinish', shell=True)
kylin_system_updater.SetConfigValue('InstallMode','auto_install','True')
elif insmod == 'bshutdown':
logging.info("pkg number:%d,shutdown delay time:%d s"%(len(pkgs),30*len(pkgs)))
login_manager.SetExtraInhibitShutdownDelaySec(30*len(pkgs))
configfilemanager.AddFileName("OTA_PKGS_TO_INSTALL")
kylin_system_updater.SetConfigValue('InstallMode','auto_install','True')
elif insmod == 'timing':
pass
else:
return UnattendedUpgradesResult(False,_("docker fetch failed"))
pass
return UnattendedUpgradesResult(True,_("all pkgs downloaded"))
else:
return UnattendedUpgradesResult(False,_("some pkgs incompletely fetched"))
else:
@ -3286,7 +3328,7 @@ if __name__ == "__main__":
if shutdown_lock < 0:
logging.error("Lock file is already taken, exiting")
#WriteValueToFile(UNATTENDED_UPGRADE_CONFIG_FILE_PATH,"UNATTENDED_UPGRADE","autoupdate_run_status","idle")
sys.exit(0)
sys.exit(1)
localesApp = "unattended-upgrades"
localesDir = "/usr/share/locale"
gettext.bindtextdomain(localesApp, localesDir)
@ -3360,13 +3402,13 @@ if __name__ == "__main__":
signal.signal(signal.SIGUSR1,signal_handler_usr1)
# write pid to let other processes find this one
pidf = PID_FILE
# pidf = os.path.join(apt_pkg.config.find_dir("Dir"),
# "var", "run", "unattended-upgrades.pid")
# clean up pid file on exit
with open(pidf, "w") as fp:
with open(PID_FILE, "w") as fp:
fp.write("%s" % os.getpid())
atexit.register(os.remove, pidf)
atexit.register(os.remove, PID_FILE)
#setup log dir
logdir = os.path.join("var", "log", "kylin-unattended-upgrades")
if not os.path.exists(logdir):
@ -3411,7 +3453,11 @@ if __name__ == "__main__":
logging.warning("control center running ,exiting...")
sys.exit(1)
'''
if options.download_only:
if options.download_only:
kylin_system_updater.ConnectToSignals()
kylin_system_updater.GetWhiteList()
kylin_system_updater.RunMainloop()
WriteValueToFile(UNATTENDED_UPGRADE_CONFIG_FILE_PATH,"UNATTENDED_UPGRADE","autoupdate_run_status","download")
elif options.install_only:
WriteValueToFile(UNATTENDED_UPGRADE_CONFIG_FILE_PATH,"UNATTENDED_UPGRADE","autoupdate_run_status","preinstall")
@ -3419,6 +3465,7 @@ if __name__ == "__main__":
install_start_time = datetime.datetime.now().replace(microsecond=0)
logging.info("unattended-upgrades start time:%s"%install_start_time)
# get log
'''
dpkg_journal_dirty = is_dpkg_journal_dirty()
abnormal_pkg_count = get_abnormally_installed_pkg_count()
logging.info("abnormal pkg count:%s,dpkg dirty:%s"%(abnormal_pkg_count,dpkg_journal_dirty))
@ -3426,4 +3473,5 @@ if __name__ == "__main__":
if dpkg_journal_dirty or abnormal_pkg_count != '0':
ret = subprocess.run("dpkg --configure -a",shell=True,stdout=open(logfile,'a+'),stderr=open(logfile,'a+'))
logging.info("dpkg fix return :%s"%ret.returncode)
'''
sys.exit(main(options))

View File

@ -38,6 +38,7 @@ import subprocess
import os.path
import os
import configparser
import psutil
# for dbus signal handling
try:
from dbus.mainloop.glib import DBusGMainLoop
@ -53,6 +54,7 @@ from enum import IntEnum, Enum
from apscheduler.schedulers.blocking import BlockingScheduler
import random
import threading
import re
try:
import apt_pkg
@ -63,11 +65,11 @@ except Exception:
sys.exit(0)
# progress information is written here
PROGRESS_LOG = "/var/run/kylin-unattended-upgrades.progress"
PID_FILE = "/var/run/kylin-unattended-upgrades.pid"
PROGRESS_LOG = "/var/run/unattended-upgrades.progress"
PID_FILE = "/var/run/unattended-upgrades.pid"
LOCK_FILE = "/var/run/kylin-unattended-upgrades.lock"
PKGS_TO_INSTALL_FLAG_FILE="/var/lib/unattended-upgrades/OTA_PKGS_TO_INSTALL"
TIME_STAMP = "/var/lib/unattended-upgrades/unattended-upgrades-timestamp"
## analytic unattended-upgrades-policy.conf start
POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY = "autoUpgradePolicy"
@ -76,6 +78,7 @@ AUTO_UPGRADE_POLICY_OPTION_AUTOUPGRADE = "autoUpgradeState"
AUTO_UPGRADE_POLICY_OPTION_DOWNLOAD_MODE = "downloadMode"
AUTO_UPGRADE_POLICY_OPTION_DOWNLOAD_TIME = "downloadTime"
AUTO_UPGRADE_POLICY_OPTION_INSTALL_MODE = "installMode"
AUTO_UPGRADE_POLICY_OPTION_UPGRADE_INTERVAL = "upgradeInverval"
INTERVAL_DOWN_INSTALL = 120 # 下载安装的间隔 分钟
INSTALL_RANDOM = 5 # 安装时间随机数范围0-INSTALL_RANDOM 分钟
DOWNLOAD_RANDOM = 3 # 下载时间随机数范围0-DOWNLOAD_RANDOM 分钟
@ -107,7 +110,24 @@ NOTIFICATION_PIPE = '/tmp/notification.pipe'
flag_file_list = ["/var/lib/unattended-upgrades/OTA_PKGS_TO_INSTALL",\
"/var/lib/kylin-auto-upgrade/kylin-autoupgrade.conf","/tmp/notify.pid"]
def is_dpkg_journal_dirty():
# type: () -> bool
"""
Return True if the dpkg journal is dirty
(similar to debSystem::CheckUpdates)
"""
logging.debug("checking whether dpkg journal is dirty")
d = os.path.join("/var/lib/dpkg/",
#os.path.dirname(apt_pkg.config.find_file("Dir::State::status")),
"updates")
for f in os.listdir(d):
if re.match("[0-9]+", f) or re.match("tmp.i",f):
return True
return False
def get_abnormally_installed_pkg_count():
output = subprocess.check_output('dpkg -l|grep ^i[^i]|wc -l',shell=True)
return output.decode().strip()
def GetDateTime():
@ -125,6 +145,18 @@ def ReadOsRelease(file):
pass
return osreleasedict
def FindRuningUnattendedUpgrades():
if os.path.exists(PID_FILE):
pid = open(PID_FILE).readline().strip()
logging.info("runing unattended-upgrades pid:%s"%pid)
try:
ps = psutil.Process(int(pid))
logging.debug("process name:%s,process status:%s"%(ps.name(),ps.status()))
return ps.is_running()
except Exception as e:
logging.error(e)
return False
def ReadValueFromFile(file,section,option):
config=configparser.ConfigParser(allow_no_value=True)
try:
@ -501,7 +533,14 @@ class UnattendedUpgradesShutdown():
self.install_job.resume()
def run(self):
""" delay shutdown and wait for PrepareForShutdown or other signals"""
""" delay shutdown and wait for PrepareForShutdown or other signals"""
if os_release_info['PROJECT_CODENAME'] == 'V10SP1-edu' and os_release_info['SUB_PROJECT_CODENAME']=='mavis':
pass
elif time.time() - float(time_stamp) < float(upgrade_interval):
time_str1 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(time_stamp)))
time_str2 = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
logging.info("upgrade interval not satisfied:%s-%s"%(time_str1,time_str2))
return 0
# set signal handlers
def signal_handler(signum, frame):
@ -532,7 +571,7 @@ class UnattendedUpgradesShutdown():
preDownload = ReadValueFromFile(UNATTENDED_UPGRADE_POLICY_FILE_PATH, POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY, AUTO_UPGRADE_POLICY_OPTION_PREDOWNLOAD)
autoUpgrade = ReadValueFromFile(UNATTENDED_UPGRADE_POLICY_FILE_PATH, POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY, AUTO_UPGRADE_POLICY_OPTION_AUTOUPGRADE)
if autoUpgrade == FeatureSwitch.ON.value or preDownload == FeatureSwitch.ON.value: #open download timing
if autoUpgrade == FeatureSwitch.ON.value and preDownload == FeatureSwitch.ON.value and download_mode ==DownloadMode.TIMING_DOWNLOAD.value: #open download timing
download_time_tmp = ReadValueFromFile(UNATTENDED_UPGRADE_POLICY_FILE_PATH, POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY, AUTO_UPGRADE_POLICY_OPTION_DOWNLOAD_TIME)
timelist = download_time_tmp.split(':')
if len(timelist) != TimeElement.TIME_NUM:
@ -567,6 +606,9 @@ class UnattendedUpgradesShutdown():
if self.install_job is not None:
self.install_job.remove()
self.install_job = self.scheduler.add_job(self.timing_install, 'cron', hour=self.install_time_r['h'], minute=self.install_time_r['m'])
elif install_mode == InstallMode.BEFORE_SHUTDOWN_INSTALL.value:
if self.install_job is not None:
self.install_job.remove()
else: #close install timing
self.install_job.pause()
@ -583,14 +625,20 @@ class UnattendedUpgradesShutdown():
logging.debug("unattended-upgrades-policy.conf not exist")
def upgrade_all_now_handler():
self._wait_for_unattended_upgrade_finish()
self._pause_timer()
env = copy.copy(os.environ)
retdownload = subprocess.run(["kylin-unattended-upgrade","--download-only"], env=env)
retinstall = subprocess.run(["kylin-unattended-upgrade","--install-only"], env=env)
self._resume_timer()
if retdownload == 0 and retinstall == 0:
return True
#self._wait_for_unattended_upgrade_finish()
if FindRuningUnattendedUpgrades():
logging.warning("find runing unattended-upgrades,please wait")
return False
else:
self._pause_timer()
env = copy.copy(os.environ)
retdownload = subprocess.run(["kylin-unattended-upgrade","--download-only"], env=env)
retinstall = subprocess.run(["kylin-unattended-upgrade","--install-only"], env=env)
self._resume_timer()
if retdownload == 0 and retinstall == 0:
return True
else:
return False
def prepare_for_shutdown_handler(active):
@ -600,7 +648,14 @@ class UnattendedUpgradesShutdown():
"this should not happen")
# PrepareForShutdown arrived, starting final iterations
self.install_mode = ReadValueFromFile(UNATTENDED_UPGRADE_POLICY_FILE_PATH,POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY,AUTO_UPGRADE_POLICY_OPTION_INSTALL_MODE)
if self.install_mode == InstallMode.BEFORE_SHUTDOWN_INSTALL.value:
autoUpgrade = ReadValueFromFile(UNATTENDED_UPGRADE_POLICY_FILE_PATH, POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY, AUTO_UPGRADE_POLICY_OPTION_AUTOUPGRADE)
if os_release_info['PROJECT_CODENAME'] == 'V10SP1-edu' and os_release_info['SUB_PROJECT_CODENAME']=='mavis':
if os.path.exists(PKGS_TO_INSTALL_FLAG_FILE):
logging.info("mavis shutdown install")
do_plymouth_splash()
self.start_iterations()
logging.info("finished iteration")
elif autoUpgrade == FeatureSwitch.ON.value and self.install_mode == InstallMode.BEFORE_SHUTDOWN_INSTALL.value:
if self.update_interface.GetConfigValue('InstallMode','shutdown_install'):
#show plymouth splash if bsshutdown is set
if os.path.exists(PKGS_TO_INSTALL_FLAG_FILE):
@ -616,12 +671,6 @@ class UnattendedUpgradesShutdown():
else:
self.mainloop.quit()
'''
elif os_release_info['PROJECT_CODENAME'] == 'V10SP1-edu' and os_release_info['SUB_PROJECT_CODENAME']=='mavis':
if os.path.exists(PKGS_TO_INSTALL_FLAG_FILE):
logging.info("mavis shutdown install")
do_plymouth_splash()
self.start_iterations()
logging.info("finished iteration")
else:
pass
self.mainloop.quit()
@ -653,7 +702,7 @@ class UnattendedUpgradesShutdown():
self.download_job = self.scheduler.add_job(self.timing_download, 'cron', hour=self.download_time_r['h'], minute=self.download_time_r['m'])
if os_release_info['PROJECT_CODENAME'] == 'V10SP1-edu' and os_release_info['SUB_PROJECT_CODENAME']=='mavis':
logging.info("setting startup download timer")
GLib.timeout_add(300, lambda: self.timing_download() and False)
GLib.timeout_add(300*1000, lambda: self.timing_download() and False)
#local_time =time.localtime(time.time()+300)
#self.startup_download_job = self.scheduler.add_job(self.timing_download,'cron',hour=local_time.tm_hour,minute = local_time.tm_min)
else:
@ -693,6 +742,9 @@ class UnattendedUpgradesShutdown():
env = copy.copy(os.environ)
#env["UNATTENDED_UPGRADES_FORCE_INSTALL_ON_SHUTDOWN"] = "1"
logging.info("starting unattended-upgrades in shutdown mode")
if FindRuningUnattendedUpgrades():
logging.warning("another unattended-upgrade is running , quit")
return False
self.on_shutdown_mode_uu_proc = subprocess.Popen(
["kylin-unattended-upgrade","--install-only","--mode=shutdown"], env=env)
#log_msg(_("Running unattended-upgrades in shutdown mode"))
@ -706,13 +758,12 @@ class UnattendedUpgradesShutdown():
#exit_log_result(True)
if os.path.exists(PKGS_TO_INSTALL_FLAG_FILE):
os.remove(PKGS_TO_INSTALL_FLAG_FILE)
subprocess.call(["/bin/plymouth","system-update","--progress=100"])
time.sleep(1)
subprocess.run(["/bin/plymouth","quit","--retain-splash"])
return False
subprocess.call(["/bin/plymouth","system-update","--progress=100"])
time.sleep(1)
subprocess.run(["/bin/plymouth","quit","--retain-splash"])
return False
else:
return True
return False
@ -804,7 +855,8 @@ def main():
level = logging.INFO
if options.debug:
level = logging.DEBUG
if not os.path.exists('/var/lib/unattended-upgrades'):
os.makedirs('/var/lib/unattended-upgrades')
if not os.path.exists(logdir):
os.makedirs(logdir)
logfile = os.path.join(logdir, "unattended-upgrades-shutdown.log")
@ -815,11 +867,84 @@ def main():
signal.signal(signal.SIGTERM, signal_term_handler)
signal.signal(signal.SIGHUP, signal.SIG_IGN)
# init()
logging.info("project id:%s,sub-project id:%s"%(os_release_info['PROJECT_CODENAME'],os_release_info['SUB_PROJECT_CODENAME']))
UnattendedUpgradesShutdown(options).run()
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("", "--debug",
action="store_true", dest="debug",
default=True,#apt_pkg.config.find_b(
#"Unattended-Upgrade::Debug", True),
help="print debug messages")
parser.add_option("", "--delay", default=25, type="int",
help="delay in minutes to wait for unattended-upgrades")
parser.add_option("", "--lock-file",
default="/var/run/kylin-unattended-upgrades.lock",
help="lock file location")
parser.add_option("", "--stop-only",
action="store_true", dest="stop_only", default=False,
help="only stop running unattended-upgrades, don't "
"start it even when "
"Unattended-Upgrade::InstallOnShutdown is true")
parser.add_option("", "--wait-for-signal",
action="store_true", dest="wait_for_signal",
default=False,
help="wait for TERM signal before starting operation")
(options, args) = parser.parse_args()
logdir = "/var/log/kylin-unattended-upgrades/"
# setup logging
level = logging.INFO
if options.debug:
level = logging.DEBUG
if not os.path.exists('/var/lib/unattended-upgrades'):
os.makedirs('/var/lib/unattended-upgrades')
if not os.path.exists(logdir):
os.makedirs(logdir)
logfile = os.path.join(logdir, "unattended-upgrades-shutdown.log")
logging.basicConfig(filename=logfile,
level=level,
format="%(asctime)s %(levelname)s - %(message)s")
os_release_info = ReadOsRelease('/etc/os-release')
logging.info("project id:%s,sub-project id:%s"%(os_release_info['PROJECT_CODENAME'],os_release_info['SUB_PROJECT_CODENAME']))
upgrade_interval = ReadValueFromFile(UNATTENDED_UPGRADE_POLICY_FILE_PATH, POLICY_CONF_SECTION_AUTO_UPGRADE_POLICY, AUTO_UPGRADE_POLICY_OPTION_UPGRADE_INTERVAL)
time_stamp = "0"
if os.path.exists(TIME_STAMP):
with open(TIME_STAMP,'r') as f:
time_stamp = f.readline()
logging.info("time stamp:%s"%time_stamp)
# setup gettext
localesApp = "unattended-upgrades"
localesDir = "/usr/share/locale"
gettext.bindtextdomain(localesApp, localesDir)
gettext.textdomain(localesApp)
# use a normal logfile instead of syslog too as on shutdown its too
# easy to get syslog killed
main()
try:
apt_pkg.init_config()
# logdir = apt_pkg.config.find_dir(
# "Unattended-Upgrade::LogDir", logdir)
except apt_pkg.Error as error:
logging.error(_("Apt returned an error when loading configuration, "
"using default values"))
logging.error(_("error message: '%s'"), error)
clean_flag_files(flag_file_list)
signal.signal(signal.SIGTERM, signal_term_handler)
signal.signal(signal.SIGHUP, signal.SIG_IGN)
dpkg_fix=None
if os_release_info['PROJECT_CODENAME'] == 'V10SP1-edu' and os_release_info['SUB_PROJECT_CODENAME']=='mavis':
dpkg_journal_dirty = is_dpkg_journal_dirty()
abnormal_pkg_count = get_abnormally_installed_pkg_count()
logging.info("abnormal pkg count:%s,dpkg dirty:%s"%(abnormal_pkg_count,dpkg_journal_dirty))
if dpkg_journal_dirty:
dpkg_fix = subprocess.run("dpkg --configure -a",shell=True,stdout=open(logfile,'a+'),stderr=open(logfile,'a+'))
if abnormal_pkg_count != '0':
apt_fix = subprocess.Popen("echo y|apt install -f",shell=True,stdout=open(logfile,'a+'),stderr=open(logfile,'a+'))
UnattendedUpgradesShutdown(options).run()
#main()

View File

@ -6,8 +6,9 @@ Documentation=man:unattended-upgrade(8)
[Service]
ExecStart=/usr/bin/kylin-unattended-upgrade-shutdown --wait-for-signal
KillMode=process
TimeoutStopSec=1800
Type=idle
#KillMode=process
#TimeoutStopSec=1800
[Install]
WantedBy=multi-user.target