Merge branch 'backend_uu' into uu_test

This commit is contained in:
shenyafeng 2022-10-21 14:46:30 +08:00
commit 2b4d0e8628
36 changed files with 2093 additions and 518 deletions

View File

@ -160,7 +160,6 @@ class UpdateMsgCollector():
dict_message = self.convertor.JsonConvertDict(json_message)
if messageType == "":
messageType = "SystemUpdate"
logging.debug("messageType: %s, json_message: %s ", messageType, json_message)
if type(dict_message) != type(dict) and "appname" not in dict_message.keys():
raise AttributeError("'%s' object has no attribute '%s'" % ("dict message", "appname"))
@ -350,13 +349,6 @@ class MessageSend():
def GetLocalTid(self, key):
# 试图获取本地tid
try:
# if os.path.exists(LOCALTIDDIR+LOCALTIDFILE):
# with open(LOCALTIDDIR+LOCALTIDFILE, "r") as f:
# self.localtid = f.readline()
# # print(self.localtid)
# else:
# self.localtid = ""
# 存放至数据库
tid = self.collector.updateManager.sqlite3_server.select_from_tid("tid",key)
if tid == "None" or tid == None:
@ -470,12 +462,14 @@ class PHPServer(threading.Thread):
PINGBACK_INTERNET_FILE_URL = "http://archive1.kylinos.cn:32294/kylin-update-manager-server/get_file.php?"
PINGBACK_INTRANET_URL = "http://archive.kylinos-intranet.cn/kylin-update-manager-server/main.php?"
PINGBACK_INTRANET_FILE_URL = "http://archive.kylinos-intranet.cn/kylin-update-manager-server/get_file.php?"
SYSTEM_VERSION_PATH = "/etc/kylin-version/kylin-system-version.conf"
def get_values(self, _appname="", _appversion="", _state='', _errorcode=''):
def get_values(self, _appname="", _appversion="", _state='', _errorcode='', _errorstring=""):
self.appname = _appname
self.appversion = _appversion
self.status = _state
self.errorcode = _errorcode
self.errorstring = _errorstring
def run(self):
# 获取本机ip
@ -514,22 +508,31 @@ class PHPServer(threading.Thread):
key = "0"
try:
# 用于收集源管理器的更新日志
if self.status == "success":
if self.status != "success":
# nowtime = datetime.utcnow( ).strftime ( '%Y-%m-%d %H:%M:%S.%f' )[:-3]
nowtime = get_east_8_time()
log_dir = os.path.join(self.LOG_PATH, host_mac + "_" + nowtime)
log_file_gzip = log_dir + ".tar.gz"
os.makedirs(log_dir, exist_ok=True)
for name in os.listdir("/var/log/kylin-system-updater/"):
if "kylin-system-updater.log." in name:
shutil.copy(os.path.join("/var/log/kylin-system-updater/",name), log_dir)
for name in os.listdir("/var/log/kylin-update-manager"):
if "kylin-update-manager.log." in name:
shutil.copy(os.path.join("/var/log/kylin-update-manager",name), log_dir)
if os.path.exists(self.KYLIN_SOFTWARE_PROPERTIES_LOG):
shutil.copy(self.KYLIN_SOFTWARE_PROPERTIES_LOG, log_dir)
if os.path.exists("/var/log/dpkg.log"):
shutil.copy("/var/log/dpkg.log", log_dir)
#get updater log
updater_path = os.path.join(log_dir,"kylin-system-updater")
os.makedirs(updater_path, exist_ok=True)
#get updater log
if os.path.exists("/var/log/kylin-system-updater/kylin-system-updater.log.1"):
shutil.copy("/var/log/kylin-system-updater/kylin-system-updater.log.1", log_dir)
if os.path.exists("/var/log/kylin-system-updater/kylin-system-updater.log.1.1.gz"):
shutil.copy("/var/log/kylin-system-updater/kylin-system-updater.log.1.1.gz", log_dir)
#get apt log
if os.path.exists("/var/log/apt/history.log"):
shutil.copy("/var/log/apt/history.log", log_dir)
if os.path.exists("/var/log/apt/term.log"):
shutil.copy("/var/log/apt/term.log", log_dir)
#get version file
if os.path.exists(self.SYSTEM_VERSION_PATH):
shutil.copy(self.SYSTEM_VERSION_PATH, log_dir)
gZipFile(log_dir, log_file_gzip)
header = {'Content-Type': "multipart/form-data", "Accept-Encoding": "gzip"}
try:
@ -546,7 +549,7 @@ class PHPServer(threading.Thread):
log_file_gzip = ""
kmg_tmp = {'ip': host_ip, 'version': version, 'soft_version': soft_version, 'datetime': nowtime,
'host_mac': host_mac, 'appname': self.appname, 'appversion': self.appversion, 'serial_number': key,
'state': self.status, 'filename': log_file_gzip, 'errorcode': self.errorcode}
'state': self.status, 'filename': log_file_gzip, 'errorcode': self.errorcode, 'errorstring': self.errorstring}
kmg = parse.urlencode(kmg_tmp)
logging.debug("PHPServer UpdateInfos: %s .", kmg_tmp)
# 优先使用内网服务器,再使用外网
@ -563,10 +566,9 @@ class PHPServer(threading.Thread):
if os.path.isfile(log_file_gzip):
os.remove(log_file_gzip)
def PHPSeverSend(_send_log = False, _appname="", _appversion="", _statue="", _errorcode=""):
if _send_log == True:
def PHPSeverSend(_appname="", _appversion="", _statue="", _errorcode="", _errorstring=""):
send_thread = PHPServer()
send_thread.get_values(_appname=_appname, _appversion=_appversion, _state=_statue, _errorcode=_errorcode)
send_thread.get_values(_appname=_appname, _appversion=_appversion, _state=_statue, _errorcode=_errorcode, _errorstring=_errorstring)
send_thread.start()
def gZipFile(src, dst):

View File

@ -13,46 +13,57 @@ from gettext import gettext as _
from sys import exec_prefix
from SystemUpdater.Core.DataAcquisition import PHPSeverSend
from SystemUpdater.Core.UpdaterConfigParser import UpgradeConfig
from SystemUpdater.Core.utils import get_config_patch
import apt_pkg
from ..backend import InstallBackend
DB_FILE = os.path.join("/var/cache/kylin-system-updater/kylin-system-updater.db")
UMDB_FILE = os.path.join("/var/cache/kylin-system-updater/kylin-system-updater.db")
# UMDB_FILE = os.path.join("/var/cache/kylin-system-updater/kylin-system-updater.db")
INSTALLED_LIST = [{"item": "errorcode", "type": "int", "default": "0"}]
DISPALY_LIST = []
class Sqlite3Server(object):
def __init__(self, window_main):
def __init__(self, updateManager):
self.connect = None
self.window_main = window_main
logging.info(_("Init Sqlite3Server..."))
self.window_main = updateManager
self.config_path = get_config_patch()
self.init_sqlit()
# uncoverable配置文件
self.ucconfigs = UpgradeConfig(datadir = "/etc/kylin-version", name = "kylin-system-version.conf")
self._system_version_config()
# 初始化连接数据库
# 初始化连接数据库,修改为使用时连接
def init_sqlit(self):
logging.info(_("Initialize the connection to the database ..."))
try:
if os.path.isfile(DB_FILE):
self.connect = sqlite3.connect(DB_FILE, check_same_thread=False)
self.cursor = self.connect.cursor()
self.insert_new_field()
else:
logging.info(_("Initialize database files ..."))
if not os.path.isfile(DB_FILE):
if not os.path.isdir(os.path.dirname(DB_FILE)):
os.makedirs(os.path.dirname(DB_FILE))
shutil.copy("/usr/share/kylin-system-updater/kylin-system-updater.db", os.path.dirname(DB_FILE))
except Exception as e:
logging.error("Failed to initialize database files: %s", str(e))
#connect连接数据库
def connect_database(self):
try:
logging.debug("Connect database ...")
self.connect = sqlite3.connect(DB_FILE, check_same_thread=False)
self.cursor = self.connect.cursor()
self.insert_new_field()
except Exception as e:
logging.error(_("Failed to initialize the database: %s"), str(e))
return False
logging.info(_("Connecting to the database successfully."))
return True
logging.error("Failed to connect database: %s", str(e))
#disconnect连接数据库
def disconnect_database(self):
try:
logging.debug("Disconnect database ...")
if self.connect != None:
self.connect.close()
if self.connect != None:
del self.cursor
except Exception as e:
logging.error("Failed to disconnect database: %s", str(e))
# 数据库表格中动态增加新的字段用于扩展
def insert_new_field(self):
@ -100,63 +111,85 @@ class Sqlite3Server(object):
# 写入数据到installed表中
def insert_into_installed(self, *args, **kwargs):
self.connect_database()
self.cursor.execute(
"insert into installed (appname, version, time, description, icon, statue, keyword, errorcode) values(?,"
"?,?,?,?,?,?,?)",
(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]))
self.connect.commit()
self.disconnect_database()
# 写入数据到display表中
def insert_into_display(self, *args, **kwargs):
self.connect_database()
try:
sql = "update display set " + args[0] + "='" + args[1] + "' where id = 1"
self.cursor.execute(sql)
self.connect.commit()
except Exception as e:
logging.error("Insert error: %s.", str(e))
self.disconnect_database()
return False
logging.info("Database: Insert (%s=%s) To display Complete ...", args[0], args[1])
self.disconnect_database()
return True
# 写入数据到tid_search表中
def insert_into_tid(self, *args, **kwargs):
self.connect_database()
self.cursor.execute(
"insert into tid_search (key, tid) values(?,?)",
(args[0], args[1]))
self.connect.commit()
self.disconnect_database()
# 搜索tid_search表获取tid值
def select_from_tid(self, *args, **kwargs):
retval = ''
self.connect_database()
try:
sql = "select "+args[0]+" from tid_search where key='"+args[1]+"'"
self.cursor.execute(sql)
rets = self.cursor.fetchall()
if len(rets)!= 0:
return str(rets[0])
if len(rets[0])!=0:
ret_first = rets[0]
retval = str(ret_first[0])
except Exception as e:
logging.error("Insert error: %s.", str(e))
self.disconnect_database()
logging.info(_("Database: Select data Complete..."))
return ""
self.disconnect_database()
return retval
# 读出display表中数据
def select_from_display(self, *args, **kwargs):
try:
self.connect_database()
sql = "select "+args[0]+" from display"
self.cursor.execute(sql)
self.connect.commit()
return str(self.cursor.fetchone()[0])
retval = str(self.cursor.fetchone()[0])
self.disconnect_database()
return retval
except Exception as e:
logging.error("Insert error: %s.", str(e))
logging.info(_("Database: Insert To Complete..."))
logging.error("select error: %s.", str(e))
self.disconnect_database()
return "Error"
# 写入updateinfos表中
def insert_into_updateinfo(self, *args, **kwargs):
try:
self.connect_database()
self.cursor.execute(
"insert into updateinfos (appname, version, description, date, status, keyword, errorcode, appname_cn, status_cn, changelog) values(?,"
"?,?,?,?,?,?,?,?,?)",
(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]))
self.connect.commit()
self.disconnect_database()
except Exception as e:
logging.error("Insert error: %s.", str(e))
self.disconnect_database()
logging.info(_("Database: Insert To Complete..."))
# 接收更新列表与信息,生成数据并插入数据库中
@ -216,15 +249,11 @@ class Sqlite3Server(object):
pkgversion = str(pkgversion).split('=')[-1]
logging.info("Complete system upgrade, refresh system version ...")
self._refresh_system_version(pkgversion)
#移除step-two标记
self._removal_of_marker()
#FIXME: 临时方案 PHP
PHPSeverSend(_send_log = self.window_main.configs_uncover.getWithDefault("SystemStatus", "upload_upgrade_log", False), _appname=pkgname, _appversion=pkgversion, _statue=status, _errorcode="10000100")
with open(self.window_main.config_path + str(pkgname) + ".yaml", "r") as stream:
try:
data_yaml = yaml.safe_load(stream)
changeLog = data_yaml['changelog']
except yaml.YAMLError as exc:
logging.error(exc)
PHPSeverSend(_appname=pkgname, _appversion=pkgversion, _statue=status, _errorcode="10000100", _errorstring=errstr)
elif pkg_list:
changeLog = " "
# 单包更新 # 获取单包数据插入数据库
@ -275,7 +304,7 @@ class Sqlite3Server(object):
# 软件商店获取中文名
appname_cn = self.get_cn_appname(str(pkgname))
#FIXME: 临时方案 PHP
PHPSeverSend(_send_log = self.window_main.configs_uncover.getWithDefault("SystemStatus", "upload_upgrade_log", False), _appname=pkgname, _appversion=pkgversion, _statue=status, _errorcode="10000100")
PHPSeverSend(_appname=pkgname, _appversion=pkgversion, _statue=status, _errorcode="10000100", _errorstring=errstr)
try:
self.insert_into_updateinfo(pkgname, pkgversion, pkgdescription, timestr, status, "1", errstr, appname_cn, status_cn, changeLog)
# FIXME: 发送插入数据库成功的信号local_upgrade_list
@ -329,7 +358,7 @@ class Sqlite3Server(object):
self.insert_into_updateinfo(str(i), pkgversion, pkgdescription, timestr, status, "1", errstr, appname_cn, status_cn, changeLog)
self.window_main.dbusController.UpdateSqlitSingle(str(i), timestr)
#FIXME: 临时方案 PHP
PHPSeverSend(_send_log = self.window_main.configs_uncover.getWithDefault("SystemStatus", "upload_upgrade_log", False), _appname=pkg.name, _appversion=pkgversion, _statue=status, _errorcode="10000100")
PHPSeverSend(_appname=pkg.name, _appversion=pkgversion, _statue=status, _errorcode="10000100", _errorstring=errstr)
# insert group deb next
for i in pkg_group:
# FIXME: 获取组信息
@ -349,16 +378,15 @@ class Sqlite3Server(object):
InstallInfos.update({"new_version":str(pkgversion)})
InstallInfos.update({"status":status})
InstallInfos.update({"errorCode":str(error_string+" "+error_desc)})
self.window_main.collector.Upgrade_Process_Msg("finish-install", InstallInfos.copy())
#FIXME: 临时方案 PHP
PHPSeverSend(_send_log = self.window_main.configs_uncover.getWithDefault("SystemStatus", "upload_upgrade_log", False), _appname=i, _appversion=pkgversion, _statue=status, _errorcode="10000100")
with open(self.window_main.config_path + str(i) + ".yaml", "r") as stream:
json_file = json.dumps(InstallInfos.copy())
try:
data_yaml = yaml.safe_load(stream)
changeLog = data_yaml['changelog']
except yaml.YAMLError as exc:
logging.error(exc)
self.window_main.collector.UpdateMsg("InstallInfos", json_file)
except:
pass
#FIXME: 临时方案 PHP
PHPSeverSend(_appname=i, _appversion=pkgversion, _statue=status, _errorcode="10000100", _errorstring=errstr)
try:
self.insert_into_updateinfo(str(i), pkgversion, pkgdescription, timestr, status, "1", errstr, appname_cn, status_cn, changeLog)
self.window_main.dbusController.UpdateSqlitSingle(str(i), timestr)
@ -375,6 +403,8 @@ class Sqlite3Server(object):
pkgversion = str(pkgversion).split('=')[-1]
logging.info("Complete system upgrade, refresh system version ...")
self._refresh_system_version(str(pkgversion))
#移除step-two标记
self._removal_of_marker()
elif mode == InstallBackend.MODE_INSTALL_SYSTEM: # 全盘升级
self.insert_into_updateinfo(_("Upgrade System"), "", "This is a complete system upgrade, equivalent to the implementation of apt dist-upgrade", timestr, status, "1", errstr, str("全盘升级"), status_cn, " ")
@ -383,16 +413,18 @@ class Sqlite3Server(object):
if status == "success":
# 更新版本号
self._refresh_system_version(pseudo_version=True)
#移除step-two标记
self._removal_of_marker()
else:
logging.warning("Cache is None.")
# 获取group信息
def GetGroupmsg(self, appname):
jsonfile = appname+".json"
files = os.listdir(self.window_main.config_path) #获取文件夹中所有文件
files = os.listdir(self.config_path) #获取文件夹中所有文件
if jsonfile in files: # 存在
# 读取组JSON文件
with open(self.window_main.config_path+jsonfile, "r") as f:
with open(self.config_path+jsonfile, "r") as f:
try :
data = json.load(f)
except json.JSONDecodeError as e:
@ -429,23 +461,46 @@ class Sqlite3Server(object):
pass
return pkgs_install,pkgs_upgrade,pkgs_remove
#查找数据库
def find_msg_from_datebase(self, table, field, action = 'check', cid = 0):
# 查询数据
def _removal_of_marker(self):
try:
sql = "select "+field+" from "+table
self.cursor.execute(sql)
update_count = self.cursor.fetchone()[0]
logging.info("%d history updates detected.", update_count)
marker_path = "/var/cache/kylin-update-manager/ignoreOrDelay"
if os.path.exists(marker_path):
with open(marker_path, 'r+') as f:
line= f.readline()
if "2107" in line or "2203" in line:
f.seek(0)
f.truncate()
except Exception as e:
logging.error("Check update error: %s", str(e))
logging.error("Removing the upgrade success mark error: %s.",str(e))
# #查找数据库
# def find_msg_from_datebase(self, table, field, action = 'check', cid = 0):
# # 查询数据
# try:
# sql = "select "+field+" from "+table
# self.cursor.execute(sql)
# update_count = self.cursor.fetchone()[0]
# logging.info("%d history updates detected.", update_count)
# except Exception as e:
# logging.error("Check update error: %s", str(e))
def _system_version_config(self):
try:
os_version = ''
update_version = ''
self.connect_database()
sql = "select init_version from display where id=1"
self.cursor.execute(sql)
_is_init_verison = self.cursor.fetchone()[0]
if _is_init_verison == "yes":
update_version, os_version = self.get_default_version()
logging.info("Need to refresh version ...")
self._refresh_system_version(update_version, os_version)
sql = "update display set init_version = 'no'"
self.cursor.execute(sql)
self.connect.commit()
self.disconnect_database()
except Exception as e:
logging.error(str(e))
self.disconnect_database()
def _refresh_system_version(self, update_version='', os_version = '', pseudo_version = False):
try:
@ -485,7 +540,7 @@ class Sqlite3Server(object):
def get_default_version(self):
update_version = ""
os_version = ""
INPUT_CONFIG_PATH = self.window_main.config_path + 'kylin-update-desktop-system.json'
INPUT_CONFIG_PATH = self.config_path + 'kylin-update-desktop-system.json'
if os.path.isfile(INPUT_CONFIG_PATH): # 存在
# 读取JSON文件
with open(INPUT_CONFIG_PATH, "r") as f:
@ -541,6 +596,7 @@ class Sqlite3Server(object):
cursor.execute(sql)
connect.commit()
retval = cursor.fetchone()
connect.close()
if retval != None and len(retval) != 0:
return str(retval[0])
else:
@ -578,15 +634,14 @@ class Sqlite3Server(object):
and "status_cn" in upgrade_info.keys() \
and "changelog" in upgrade_info.keys():
appname = upgrade_info["appname"]
if "(" in appname and ")" in appname:
appname_orig = appname.split("(")[0]
appname_suffix = "("+appname.split("(")[1]
if appname_orig in self.window_main.cache:
pkg = self.window_main.cache[appname_orig]
if "kylin-unattended-upgrade" == appname:
upgrade_info["appname"] = self.get_cn_appname(appname)
if upgrade_info["appname"] == "":
upgrade_info["appname"] = _("kylin-unattended-upgrade")
if appname in self.window_main.cache and upgrade_info["description"] == "":
pkg = self.window_main.cache[appname]
if pkg.is_installed:
upgrade_info["description"] = pkg.installed.description
upgrade_info["appname"] = self.get_cn_appname(appname_orig)+appname_suffix
upgrade_info["status_cn"] = self.get_cn_appname(appname_orig)
self.insert_into_updateinfo( upgrade_info["appname"], upgrade_info["version"], \
upgrade_info["description"], \
upgrade_info["date"], \

View File

@ -17,6 +17,7 @@ class LogInstallProgress(apt.progress.base.InstallProgress):
self.filename=file
self.error_pkg=""
self.errormsg=""
# raise Exception("for test!!!")
def error(self,pkg, errormsg):
logging.error(("Install mode - dpkg, Install error: %s"), errormsg)

View File

@ -21,7 +21,7 @@ def get_logfile():
for i in os.listdir(path):
if "kylin-system-updater.log." in os.path.basename(path + i):
numlist.append((path + i).split(".")[2])
if get_FileSize(path + i) < 10:
if get_FileSize(path + i) < 100:
return path + i
#获取1-5未使用的最小数字的标号作为日志文件
for i in range(1, 6):
@ -40,3 +40,30 @@ def get_logfile():
return os.path.join(path, "kylin-system-updater.log.1")
except:
return os.path.join(path, "kylin-system-updater.log.1")
def upgrade_strategies_logfile():
if not os.path.exists(path):
os.makedirs(path)
#优先获取当前未写满100M的日志编号文件
for i in os.listdir(path):
if "upgrade-strategies-daemon.log." in os.path.basename(path + i):
numlist.append((path + i).split(".")[2])
if get_FileSize(path + i) < 10:
return path + i
#获取1-5未使用的最小数字的标号作为日志文件
for i in range(1, 6):
if str(i) not in numlist:
return(os.path.join(path, ("upgrade-strategies-daemon.log.%s") % i))
try:
#编号1-5日志文件均写满时删除第一个往前移动日志编号获取最后一个编号作为日志文件
if len(numlist) != 0:
os.remove(os.path.join(path, "upgrade-strategies-daemon.log.1"))
for i in range(2, 6):
os.rename(os.path.join(path, ("upgrade-strategies-daemon.log.%s") % i),
os.path.join(path, ("upgrade-strategies-daemon.log.%s") % (i - 1)))
return os.path.join(path, "upgrade-strategies-daemon.log.5")
#默认情况下未生成任何日志时使用编号1的日志文件
else:
return os.path.join(path, "upgrade-strategies-daemon.log.1")
except:
return os.path.join(path, "upgrade-strategies-daemon.log.1")

View File

@ -67,7 +67,8 @@ class MyCache(SystemUpdater.Core.DistUpgradeCache.MyCache):
# check if the dpkg journal is ok (we need to do that here
# too because libapt will only do it when it tries to lock
# the packaging system)
assert(not self._dpkgJournalDirty())
if self._dpkgJournalDirty() == True:
logging.info("dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.")
# init the regular cache
self._initDepCache()
self.all_changes = {}

View File

@ -1,6 +1,4 @@
#!/usr/bin/python3
from types import coroutine
import apt
import apt_pkg
import fnmatch
@ -8,26 +6,21 @@ import logging
import logging.handlers
import re
import os
import sys
import string
import subprocess
import json
try:
from typing import AbstractSet, DefaultDict, Dict, Iterable, List
# AbstractSet # pyflakes
# DefaultDict # pyflakes
# Dict # pyflakes
# Iterable # pyflakes
# List # pyflakes
from typing import Set, Tuple, Union
# Set # pyflakes
# Tuple # pyflakes
from typing import List
from typing import Union
except ImportError:
pass
from gettext import gettext as _
import apt
import apt_pkg
SYSTEM_UPDATER_CORE_LIB_PATH="/usr/share/kylin-system-updater/"
sys.path.append(SYSTEM_UPDATER_CORE_LIB_PATH)
from SystemUpdater.Core.utils import get_config_patch
ImportantListPath="/var/lib/kylin-software-properties/template/important.list"
SOURCESLIST = "/etc/apt/sources.list"
@ -56,6 +49,8 @@ class UpdateListFilterCache(apt.Cache):
# 必须升级的包
self.installList = []
self.config_path = get_config_patch()
# 获取源属性
self.origin_property = OriginProperty()
self.origin_property.get_allowed_sources()
@ -106,7 +101,7 @@ class UpdateListFilterCache(apt.Cache):
exit(-1)
# 获取/usr/share/kylin-update-desktop-config/data/下所有json文件
for root,dirs,files in os.walk(self.window_main.config_path):
for root,dirs,files in os.walk(self.config_path):
pass
for i in files:
if ".json" in i:
@ -123,7 +118,7 @@ class UpdateListFilterCache(apt.Cache):
# 在分组中
# 获取每个对应json文件中的upgrade_list
if i in jsonfiles:
filepath = os.path.join(self.window_main.config_path, i)
filepath = os.path.join(self.config_path, i)
filepath = filepath+".json"
with open(filepath, 'r') as f:
pkgdict = f.read()

View File

@ -10,6 +10,7 @@ from gi.repository import Gio
from .OriginFilter import UpdateListFilterCache
from .errors import *
from .enums import *
from SystemUpdater.Core.utils import get_config_patch
class LocalUpgradeDataList:
"""
@ -56,8 +57,9 @@ class UpdateList():
self.application_dirs = [os.path.join(base, 'applications')
for base in data_dirs.split(':')]
if self.parent.options.close_filter == False and self.parent.source_info.is_disc == False and \
self.parent.configs_cover.getWithDefault("SystemStatusCover", "close_source_filter", False) == False :
self.config_path = get_config_patch()
if self.parent.install_mode.check_filter() == True:
#开启原过滤
self.fu = UpdateListFilterCache(self.parent)
else:
@ -77,14 +79,11 @@ class UpdateList():
logging.info('Emptying the ConfigPath(%s) is complete...',self.OUTPUT_CONFIG_PATH)
#读取推送列表,判断分组和单包推送,再进行源过滤
def _read_important_list(self,cache,pkgs_upgrade):
def _make_important_list(self,cache,pkgs_upgrade,important_list = []):
upgradeable_pkgs = []
tmp = []
upgradeable_groups = []
with open(self.IMPORTANT_LIST_PATH, 'r') as f:
data = f.read()
important_list = data.split()
logging.info("The Server Push List: %a",important_list)
for pkg_name in important_list:
@ -93,8 +92,8 @@ class UpdateList():
pkg_obj = cache[pkg_name]
#在可升级的列表当中 此步骤为了排除已安装不需要升级的
if pkg_obj.is_installed:
if pkg_obj in pkgs_upgrade:
pkgs_upgrade.remove(pkg_obj)
if pkg_name in pkgs_upgrade:
pkgs_upgrade.remove(pkg_name)
tmp.append(pkg_obj)
else:
tmp.append(pkg_obj)
@ -255,7 +254,7 @@ class UpdateList():
group_json = {}
for ug in self.upgrade_meta.groups_pkgs:
pkgs_json = {}
with open(self.parent.config_path + str(ug) + ".yaml", "r") as stream:
with open(self.config_path + str(ug) + ".yaml", "r") as stream:
try:
data_yaml = yaml.safe_load(stream)
pkgs_json.update({"cur_version":""})
@ -354,36 +353,8 @@ class UpdateList():
return downgrade_raw,downgrade_pkgs
def _make_groups_upgrade(self,cache,group_list, pkgs_upgrade = []):
if os.path.isdir(self.parent.config_path) == False:
logging.warning("configPath(%s) is not exists...",self.parent.config_path)
return
def _make_groups_pkgs(self,cache,data,pkgs_upgrade = []):
files = os.listdir(self.parent.config_path) #获得文件夹中所有文件的名称列表
for ifile in files:
#判是否是目录以及是否以JSON结尾
if ifile.endswith('.json'):
#读取组JSON文件
with open(self.parent.config_path+ifile,'r') as f:
try:
data = json.load(f)
except Exception as exc:
logging.error(exc)
raise UpdateBaseError(ERROR_LOAD_CONFIG_FAILED)
group_name = data['package']
#读取组的yaml 文件的changelog的信息
with open(self.parent.config_path + group_name + ".yaml", "r") as stream:
try:
data_yaml = yaml.safe_load(stream)
except Exception as exc:
logging.error(exc)
raise UpdateBaseError(ERROR_LOAD_CONFIG_FAILED)
#过滤没有推送的配置文件
if not group_name in group_list:
continue
upgrade_pkgs_list = data['upgrade_list']
#检查包是否在cache中 以及是否已经安装 没有安装的话才添加到列表
new_install_list = self._check_pkg_in_cache(cache,data['install_list'])
@ -418,14 +389,56 @@ class UpdateList():
if pkg in new_install_list:
new_install_list.remove(pkg)
return new_install_list,new_upgrade_list
def _make_groups_upgrade(self,cache,group_list,is_openkylin,pkgs_install,pkgs_upgrade):
upgrade_list = []
install_list = []
if os.path.isdir(self.config_path) == False:
logging.warning("configPath(%s) is not exists...",self.config_path)
return
files = os.listdir(self.config_path) #获得文件夹中所有文件的名称列表
for ifile in files:
#判是否是目录以及是否以JSON结尾
if ifile.endswith('.json'):
#读取组JSON文件
with open(self.config_path+ifile,'r') as f:
try:
data = json.load(f)
except Exception as exc:
logging.error(exc)
raise UpdateBaseError(ERROR_LOAD_CONFIG_FAILED)
group_name = data['package']
#读取组的yaml 文件的changelog的信息
with open(self.config_path + group_name + ".yaml", "r") as stream:
try:
data_yaml = yaml.safe_load(stream)
except Exception as exc:
logging.error(exc)
raise UpdateBaseError(ERROR_LOAD_CONFIG_FAILED)
#过滤没有推送的配置文件
if not group_name in group_list:
continue
if is_openkylin == True:
install_list,upgrade_list = pkgs_install,pkgs_upgrade
else:
install_list,upgrade_list = self._make_groups_pkgs(cache,data,pkgs_upgrade)
#判断当前是否可升级或者新装的包
if len(new_install_list) == 0 and len(new_upgrade_list) == 0:
if len(install_list) == 0 and len(upgrade_list) == 0:
continue
#3、生成升级的包列表JSON
upgrade_pkgs_json = self._make_pkg_info_json(cache,new_upgrade_list)
upgrade_pkgs_json = self._make_pkg_info_json(cache,upgrade_list)
#2、生成安装的软件列表
install_pkgs_json = self._make_pkg_info_json(cache,new_install_list)
install_pkgs_json = self._make_pkg_info_json(cache,install_list)
#输出JSON配置文件
self._make_group_output_json(data,data_yaml,upgrade_pkgs_json,install_pkgs_json)
@ -434,11 +447,38 @@ class UpdateList():
#添加到字典维护的升级列表
self.upgrade_meta.upgrade_groups.append(group_name)
self.upgrade_meta.groups_pkgs.update({group_name:{"pkgs_upgrade":new_upgrade_list,"pkgs_install":new_install_list}})
logging.info("Group(%s) upgrade:%d install:%d",group_name,len(new_upgrade_list),len(new_install_list))
self.upgrade_meta.groups_pkgs.update({group_name:{"pkgs_upgrade":upgrade_list,"pkgs_install":install_list}})
logging.info("Group(%s) upgrade:%d install:%d",group_name,len(upgrade_list),len(install_list))
else:
pass
def _make_openkylin_output_json(self,upgrade_pkgs_json,install_pkgs_json):
groups_base_info = {}
output_json = {}
#FIXME: 确定输出文件的文件名 以及放置位置
output_config_name = self.OUTPUT_CONFIG_PATH + "kylin-update-desktop-system.json"
#4、添加一些基础信息
groups_base_info.update({"package":"kylin-update-desktop-system"})
groups_base_info.update({"new_version":"33797.0001"})
groups_base_info.update({"name":{"zh_CN": "系统更新","en_US": "Kylin OS"}})
groups_base_info.update({"description":{"zh_CN": "Openkylin-系统更新包","en_US": "Openkylin-System Update Package"}})
groups_base_info.update({"icon":" "})
#添加读yaml文件
groups_base_info.update({"changelog":"Openkylin-系统更新包\n"})
#5、添加升级的内容
output_json.update(groups_base_info)
output_json.update({"upgrade_list":upgrade_pkgs_json})
output_json.update({"install_list":install_pkgs_json})
#6 产生JSON文件
with open(output_config_name, 'w', encoding='utf-8') as f:
json.dump(output_json, f, ensure_ascii=False, indent=4)
logging.info("Generate Jsonfile(%s) to complete... ",output_config_name)
def _rate_application_for_package(self, application, pkg):
score = 0
desktop_file = os.path.basename(application.get_filename())
@ -538,16 +578,39 @@ class UpdateList():
#6、保存单包版本号
self.upgrade_meta.versoin_pkgs['single_upgrade'].update({pkg_cache.name:getattr(pkg_cache.installed, "version", '')})
def update(self,cache):
def _make_distupgrade(self,cache):
pkgs_upgrade = []
pkgs_install = []
if cache.get_changes():
cache.clear()
cache._depcache.upgrade(True)
#查找所有可升级的包
for pkg in cache:
try:
if pkg.marked_install:
pkgs_install.append(pkg.name)
elif pkg.marked_upgrade:
pkgs_upgrade.append(pkg.name)
except KeyError:
pass
return pkgs_install,pkgs_upgrade
def update_kylin(self,cache,important_data,is_openkylin = False):
pkgs_install = []
pkgs_upgrade = []
#查找所有可升级的包
if is_openkylin == True:
pkgs_install,pkgs_upgrade = self._make_distupgrade(cache)
else:
for pkg in cache:
if pkg.is_upgradable and pkg.is_installed:
pkgs_upgrade.append(pkg)
pkgs_upgrade.append(pkg.name)
logging.info("System all upgradeable packages:upgrade:%d ",len(pkgs_upgrade))
logging.info("System all upgradeable packages:upgrade:%d install:%d ",len(pkgs_upgrade),len(pkgs_install))
group_important_list,self.upgrade_meta.single_pkgs = self._read_important_list(cache,pkgs_upgrade)
group_important_list,self.upgrade_meta.single_pkgs = self._make_important_list(cache,pkgs_upgrade,important_data)
#清空输出的目录
self._empty_output_dir()
@ -561,11 +624,10 @@ class UpdateList():
self._make_single_upgrade(cache,self.upgrade_meta.single_pkgs)
#分组的包的JSON
self._make_groups_upgrade(cache,group_important_list,[pkg.name for pkg in pkgs_upgrade])
self._make_groups_upgrade(cache,group_important_list,is_openkylin,pkgs_install,pkgs_upgrade)
self._make_autoupgrade_config(cache,self.upgrade_meta,self.upgrade_meta.adjust_pkgs)
self.parent.dbusController.UpdateDetectFinished(True,self.upgrade_meta.upgrade_groups + self.upgrade_meta.single_pkgs,'','')
return

View File

@ -7,8 +7,9 @@ __all__ = (
"ERROR_UPDATE_SOURCE_FAILED","ERROR_NETWORK_FAILED","ERROR_NOT_GROUPS_CONFIG","ERROR_SOFTWARE_INDEX_RROKEN",
"ERROR_NOT_INIT_PACKAGESINFIO","ERROR_READ_IMPORTANTLIST_FAILED","ERROR_RESOLVER_FAILED","ERROR_NOT_UPGRADE_PACKAGES",
"ERROR_REMOVE_ESSENTIAL_PACKAGES","ERROR_NOT_DISK_SPACE","ERROR_NOT_CONFIGPKG_DEPENDENCIES","ERROR_NOT_SELFPKG_DEPENDENCIES",
"ERROR_NOT_FIX_SYSTEM","ERROR_READ_LOCAL_DEB","ERROR_INSTALL_DEB_BASE","ERROR_LOAD_CONFIG_FAILED",
"ERROR_NOT_FIX_SYSTEM","ERROR_READ_LOCAL_DEB","ERROR_LOCAL_DEB_FORMAT","ERROR_INSTALL_DEB_BASE","ERROR_LOAD_CONFIG_FAILED",
"ERROR_UPDATE_KEY_SIGNATURES","ERROR_UPDATE_NET_AUTHENTICATION","ERROR_UPDATE_NOTREAD_SOURCES","PRIORITY_UPGRADE_SUCCCESSED",
"ERROR_UPDATE_INVALID_TIME",
"get_error_description_from_enum", "get_error_string_from_enum", "get_source_name_from_enum", "get_caller_from_enum")
@ -19,11 +20,12 @@ _ = gettext.gettext
PRIORITY_UPGRADE_SUCCCESSED = "priority-upgrade-successed"
#更新阶段
#apt update阶段出现的错误解析
ERROR_UPDATE_DEFAULT_FAILED = "error-update-default-failed"
ERROR_UPDATE_KEY_SIGNATURES = "The following signatures"
ERROR_UPDATE_NET_AUTHENTICATION ="does the network require authentication?"
ERROR_UPDATE_NOTREAD_SOURCES = "The list of sources could not be read"
ERROR_UPDATE_INVALID_TIME = "(invalid for another"
ERROR_UPDATE_SOURCE_FAILED = "error-update-source-failed"
ERROR_NETWORK_FAILED = "error-network-failed"
@ -44,10 +46,11 @@ ERROR_NOT_UPGRADE_PACKAGES = "error-not-upgrade-packages"
ERROR_REMOVE_ESSENTIAL_PACKAGES = "error-remove-essential-packages"
ERROR_NOT_DISK_SPACE = "error-not-disk-space"
ERROR_READ_LOCAL_DEB = "error-read-local-deb"
ERROR_LOCAL_DEB_FORMAT = "error-local-deb-format"
ERROR_INSTALL_DEB_BASE = "error-install-deb-base"
_STRINGS_ERROR = {
PRIORITY_UPGRADE_SUCCCESSED: _("Update Manager upgrade is complete, please restart the control panel before performing the system update"),
PRIORITY_UPGRADE_SUCCCESSED: _("Update Manager upgrade is complete, please restart the setting panel before performing the system update."),
#update
ERROR_UPDATE_DEFAULT_FAILED: _("Check for update exceptions!"),
@ -71,6 +74,7 @@ _STRINGS_ERROR = {
ERROR_REMOVE_ESSENTIAL_PACKAGES: _("There is an exception in the update package."),
ERROR_NOT_DISK_SPACE: _("Disk space is insufficient, please clean the disk and then upgrade"),
ERROR_READ_LOCAL_DEB:_(" "),
ERROR_LOCAL_DEB_FORMAT:_(" "),
ERROR_INSTALL_DEB_BASE:_(" ")}
_DESCS_ERROR = {
@ -79,6 +83,7 @@ _DESCS_ERROR = {
ERROR_NETWORK_FAILED: _("Please check your network connection and retry."),
ERROR_UPDATE_KEY_SIGNATURES: _("Check your source public key signature"),
ERROR_UPDATE_NOTREAD_SOURCES: _("Please check your source list and retry."),
ERROR_UPDATE_INVALID_TIME: _("Please check the system time and synchronize the system time before updating."),
ERROR_UPDATE_NET_AUTHENTICATION: _("Check if your network requires authentication?"),
ERROR_NOT_GROUPS_CONFIG: _("Unable to get group configuration package, Please check if the configuration package exists in the software source repository."),
ERROR_NOT_INIT_PACKAGESINFIO: _("An unresolvable problem occurred while initializing the package."),
@ -99,6 +104,7 @@ _DESCS_ERROR = {
ERROR_REMOVE_ESSENTIAL_PACKAGES: _("You request the removal of a system-essential package."),
ERROR_NOT_DISK_SPACE: _("test"),
ERROR_READ_LOCAL_DEB:_("Deb format exception, read local deb file error."),
ERROR_LOCAL_DEB_FORMAT:_("Deb format exception, failed to parse package file."),
ERROR_INSTALL_DEB_BASE:_("Install deb error.")
}

View File

@ -59,9 +59,6 @@ from ctypes import *
import struct
# 禁止关机锁文件路径
FILELOCK_PATH = "/tmp/lock/"
SHUTDOWN_BLOCK_FILELOCK = "kylin-update.lock"
inhibit_lock = None
VERIFY_SO = "libkylin_signtool.so"
class ExecutionTime(object):
@ -202,15 +199,9 @@ def country_mirror():
def get_dist():
" return the codename of the current runing distro "
# support debug overwrite
dist = os.environ.get("META_RELEASE_FAKE_CODENAME")
if dist:
logging.warning("using fake release name '%s' (because of "
"META_RELEASE_FAKE_CODENAME environment) " % dist)
return dist
# then check the real one
from subprocess import Popen, PIPE
p = Popen(["lsb_release", "-c", "-s"], stdout=PIPE,
p = Popen(["lsb_release", "-i", "-s"], stdout=PIPE,
universal_newlines=True)
res = p.wait()
if res != 0:
@ -223,12 +214,6 @@ def get_dist():
def get_dist_version():
" return the version of the current running distro "
# support debug overwrite
desc = os.environ.get("META_RELEASE_FAKE_VERSION")
if desc:
logging.warning("using fake release version '%s' (because of "
"META_RELEASE_FAKE_VERSION environment) " % desc)
return desc
# then check the real one
from subprocess import Popen, PIPE
p = Popen(["lsb_release", "-r", "-s"], stdout=PIPE,
@ -473,6 +458,17 @@ def _split_package_id(package):
return name, arch
def get_config_patch():
#检查组配置文件当前的目录
NOW_UPDATE_CONFIG = '/usr/share/kylin-update-desktop-config/config/'
OLD_UPDATE_CONFIG = '/usr/share/kylin-update-desktop-config/data/'
if os.path.exists(NOW_UPDATE_CONFIG):
return NOW_UPDATE_CONFIG
elif os.path.exists(OLD_UPDATE_CONFIG):
return NOW_UPDATE_CONFIG
else:
return NOW_UPDATE_CONFIG
def get_broken_details(cache,now=True):
"""Return a message which provides debugging information about
broken packages.

View File

@ -30,7 +30,7 @@ from .Core.DataAcquisition import UpdateMsgCollector
from SystemUpdater.Core.UpdaterConfigParser import UpgradeConfig
from SystemUpdater.Core.utils import kill_process
from SystemUpdater.Core.DpkgInstallProgress import LogInstallProgress
from SystemUpdater.Core.utils import deb_verify,PolicyKit_Authority,get_proc_from_dbus_name,whether_to_quit_uu
from SystemUpdater.Core.utils import deb_verify,PolicyKit_Authority,get_proc_from_dbus_name,whether_to_quit_uu,get_dist
class UpdateManager():
BACKEND_PKG_NAME = 'kylin-system-updater'
@ -49,7 +49,6 @@ class UpdateManager():
self.init_config_aptdeamon = False
self.aptd_lang_switch = False
self.retry_limit = self.RETRY_LIMIT_NUM
self.config_path = self.refresh_config_patch()
self.now_working = InstallBackend.ACTION_DEFUALT_STATUS
#dbus
self.dbusController = self._setup_dbus()
@ -63,25 +62,31 @@ class UpdateManager():
#连接数据库
self.sqlite3_server = Sqlite3Server(self)
self.simulate_mode = SimulateTerminal()
self.source_info = MakeSourceInit()
self.install_mode = UpdateInstallMode(self)
self.apt_p2p_config = AptP2pConfigManager()
self._reload_options_config()
self._refresh_cache_only()
except Exception as e:
logging.error(e)
traceback.print_exc()
def refresh_config_patch(self):
#检查组配置文件当前的目录
NOW_UPDATE_CONFIG = '/usr/share/kylin-update-desktop-config/config/'
OLD_UPDATE_CONFIG = '/usr/share/kylin-update-desktop-config/data/'
if os.path.exists(NOW_UPDATE_CONFIG):
return NOW_UPDATE_CONFIG
elif os.path.exists(OLD_UPDATE_CONFIG):
return OLD_UPDATE_CONFIG
else:
return NOW_UPDATE_CONFIG
def _reload_options_config(self):
#添加默认保留旧配置
apt_pkg.config["DPkg::Options::"] = "--force-confold"
options_new = list(set(apt_pkg.config.value_list("DPkg::Options")))
for option in ("--force-confnew","--force-confdef"):
if option in options_new:
options_new.remove(option)
#清除所有配置重新加载
apt_pkg.config.clear("DPkg::Options")
for option in options_new:
apt_pkg.config["DPkg::Options::"] = option
#去除安装推荐和建议的软件包
if apt_pkg.config.find_b("APT::Install-Recommends",False) == True:
apt_pkg.config.clear("APT::Install-Recommends")
if apt_pkg.config.find_b("APT::Install-Suggests",False) == True:
apt_pkg.config.clear("APT::Install-Suggests")
def check_frontend_pkg(self):
#控制面板前端包的检查升级
@ -163,12 +168,12 @@ class UpdateManager():
self.install_mode.reset_shutdown_mode()
#检查 光盘源
self.source_info.check_source()
self.install_mode.check_source()
if self.options.no_check_network is False and self.source_info.is_disc == False:
if self.install_mode.check_network() == True:
self.dbusController.check_connectivity()
if self.options.no_update_source is False:
if self.install_mode.update_important() == True:
self.dbusController.on_update_important_list()
return
@ -194,7 +199,6 @@ class UpdateManager():
def start_available(self):
try:
self.config_path = self.refresh_config_patch()
self.refresh_cache()
self.update_list = UpdateList(self)
@ -212,7 +216,7 @@ class UpdateManager():
#检查优先自我升级
self._check_self_upgrade(self.cache)
self.update_list.update(self.cache)
self.update_list.update_kylin(self.cache,self.install_mode.get_important_data(),self.install_mode.is_openkylin_desktop())
if self.cache != None and self.cache.get_changes():
self.cache.clear()
@ -251,14 +255,13 @@ class UpdateManager():
def _check_self_upgrade(self,cache):
need_upgrade = False
self_upgrade = []
with open(UpdateList.IMPORTANT_LIST_PATH, 'r') as f:
data = f.read()
important_list = data.split()
important_list = self.install_mode.get_important_data()
for pkg_name in [self.BACKEND_PKG_NAME,self.APTD_PKG_NAME,self.FRONTEND_PKG_NAME]:
if pkg_name in cache:
self_pkg = cache[pkg_name]
if self_pkg.is_installed and self_pkg.is_upgradable:
if self_pkg.is_installed:
if self_pkg.is_upgradable:
logging.info("Check: (%s) will upgrading From %s to %s...",pkg_name,\
self_pkg.installed.source_version,self_pkg.candidate.source_version)
if pkg_name in important_list:
@ -274,6 +277,8 @@ class UpdateManager():
raise UpdateBaseError(ERROR_NOT_SELFPKG_DEPENDENCIES)
else:
logging.info("Check: (%s:%s) No need to upgrade and duo to not pust...",pkg_name,self_pkg.installed.source_version)
else:
logging.info("Check: (%s:%s) No need to upgrade...",pkg_name,self_pkg.installed.source_version)
else:
logging.info("Check: (%s) Not to be installed...",pkg_name)
else:
@ -285,11 +290,10 @@ class UpdateManager():
self_pkg = cache[pkg_name]
if self_pkg.is_installed:
if self_pkg.is_upgradable:
self.dbusController.UpdateDetectStatusChanged(95,_("Group configuration being updated"))
logging.info("Check: groups JSON ConfigPkgs(%s) start upgrading From %s to %s...",pkg_name,\
self_pkg.installed.source_version,self_pkg.candidate.source_version)
try:
self_pkg.mark_install()
self_pkg.mark_install(True, False, True)
self_upgrade.append(pkg_name)
need_upgrade = True
except SystemError:
@ -299,16 +303,9 @@ class UpdateManager():
else:
logging.info("Check: ConfigPkgs(%s:%s) No need to upgrade...",pkg_name,self_pkg.installed.source_version)
else:
self.dbusController.UpdateDetectStatusChanged(95,_("Group configuration being updated"))
if self.update_list.fu != None:
after_pkgs_list,adjust_pkgs = self.update_list.fu.check_in_allowed_origin([self_pkg],True)
if after_pkgs_list == [] and adjust_pkgs == []:
logging.info("Check: (%s) will not upgrading From %s to %s,duo to not locate at Allowed origins...",pkg_name,\
self_pkg.installed.source_version,self_pkg.candidate.source_version)
continue
logging.info("Check: groups JSON ConfigPkgs(%s) start new installing...",pkg_name)
try:
self_pkg.mark_install(True,False,True)
self_pkg.mark_install(True, False, True)
self_upgrade.append(pkg_name)
need_upgrade = True
except SystemError:
@ -320,6 +317,7 @@ class UpdateManager():
raise UpdateBaseError(ERROR_NOT_GROUPS_CONFIG)
if need_upgrade == True:
self.dbusController.UpdateDetectStatusChanged(95,_("Priority Upgrade Package being updated"))
self.start_install(InstallBackend.MODE_INSTALL_SINGLE,True,upgrade_content=self_upgrade)
raise UpdateProgressExit()
@ -327,7 +325,8 @@ class UpdateManager():
if cache.get_changes():
cache.clear()
#获取出现破损状态包的数量
if cache._depcache.broken_count > 0:
if cache._depcache.broken_count or cache._depcache.del_count > 0 or \
cache._depcache.inst_count > 0:
#线程获取详细的卸载软件包情况
self.simulate_mode.start_caculate(["apt-get", "install","-f","--simulate"],thread=True)
else:
@ -640,7 +639,7 @@ class UpdateManager():
if depends.split('_')[0] == debfile.split('_')[0] and depends.split('_')[1] == debfile.split('_')[1] and debfile not in satisfy_list:
depends_count += 1
satisfy_list.append(debfile)
if depends_count < len(noSatisfyList):
if depends_count < len(noSatisfyList) or depends_count < len(depends_pkg):
#本地依赖不满足
error_string = str(debname.split("_")[0])+_("dependency is not satisfied")+", ".join(noSatisfyList)
logging.error(error_string)
@ -688,12 +687,12 @@ class UpdateManager():
# 检查本地破损
try:
deb_cache = Cache()
logging.info("Install deb package, check broken")
logging.info("Install deb_package, check broken")
broken_count = deb_cache._depcache.broken_count
deb = DebPackage(deb_path, deb_cache)
deb.check(allow_downgrade=True)
logging.info("Install deb package, required changes")
(install, remove, unauth) = deb.required_changes # need in cach
debPackage = DebPackage(deb_path, deb_cache)
debPackage.check(allow_downgrade=True)
logging.info("Install deb_package, required changes")
(install, remove, unauth) = debPackage.required_changes # need in cach
if broken_count > 0:
self._is_broken = True
else :
@ -706,12 +705,14 @@ class UpdateManager():
logging.error(str(e))
if "E:read" in str(e):
raise UpdateBaseError(ERROR_READ_LOCAL_DEB)
else:
raise UpdateBaseError(ERROR_LOCAL_DEB_FORMAT)
except Exception as e:
logging.error(str(e))
raise UpdateBaseError(ERROR_INSTALL_DEB_BASE)
self._need_downgrade = False
# 不满足的依赖列表
depends = deb.depends
depends = debPackage.depends
self.noSatisfyList = self._gen_noSatisfyList(depends, deb_cache)
_list = []
# cache是否满足
@ -735,8 +736,8 @@ class UpdateManager():
_group_satify = False
providers = []
for or_group in depends:
for deb in or_group:
debname,ver,oper = deb
for deb_info in or_group:
debname,ver,oper = deb_info
if ":" in debname:
debname=debname.split(":")[0]
try:
@ -965,8 +966,18 @@ class UpdateSafeManager():
return False
class UpdateInstallMode():
OPENKYLIN_DISTTRIBUTOR = "Openkylin"
KYLIN_DISTTRIBUTOR = "Kylin"
SYSTEM_UPDATE_GROUPS = "kylin-update-desktop-system"
DIR_MRDIA = "/media/"
MOUNT_SQUASHFS_PATH = "/media/kylin/kylin-test-upgrade/upgrade-pool/"
IMPORTANT_LIST_PATH = '/var/lib/kylin-software-properties/template/important.list'
def __init__(self,parent):
self.parent = parent
self.is_disc = False
self.is_mounted = False
self.dist = get_dist()
if self.shutdown_mode() == True:
logging.info("Initialize Shutdown Install Model...")
@ -976,6 +987,38 @@ class UpdateInstallMode():
self.tmp_content = []
self.inhibit_lock = None
def is_openkylin_desktop(self):
return self.dist == self.OPENKYLIN_DISTTRIBUTOR
# return True
def check_network(self):
if self.parent.options.no_check_network is False and self.is_disc == False:
return True
else:
return False
def update_important(self):
if self.parent.options.no_update_source is False and self.is_openkylin_desktop() == False:
return True
else:
return False
def get_important_data(self):
important_list = []
if self.is_openkylin_desktop() == False:
with open(self.IMPORTANT_LIST_PATH, 'r') as f:
data = f.read()
important_list = data.split()
else:
important_list = [self.SYSTEM_UPDATE_GROUPS,self.parent.BACKEND_PKG_NAME,self.parent.APTD_PKG_NAME,self.parent.FRONTEND_PKG_NAME]
return important_list
def check_filter(self):
if self.parent.options.close_filter == False and self.is_disc == False and self.is_openkylin_desktop() == False:
return True
else:
return False
def _plymouth_splash(self):
if os.path.exists("/bin/plymouth"):
logging.debug("Running plymouth --splash")
@ -1091,38 +1134,62 @@ class UpdateInstallMode():
if self.inhibit_lock == None:
logging.error("Prepare inhibit lock failed...")
#当检查失败时 再切换到ping再进行一次检查
def _check_network_ping(self):
header = ''
desc = ''
slist = apt_pkg.SourceList()
slist.read_main_list()
#判断是否为光盘源
#光盘源格式 deb file:///home/someone/packs/
def check_source(self):
logging.info("Check: Whether to use CD-ROM source updates Successfully...")
if os.path.exists(self.DIR_MRDIA):
for first_dir in os.listdir(self.DIR_MRDIA):
#到/media/x
check_dir_one = self.DIR_MRDIA + first_dir + "/"
#多个源 也只循环一次
for uri in [lis.uri for lis in slist.list]:
#只要是使用光盘源 就不进行检查了 默认检查网络成功 进行之后的动作
if "file://" in uri:
logging.info("Current exites of CD-ROM source in sources.list and return network ok...")
return True,header,desc
if not os.path.isdir(check_dir_one):
continue
if "localhost:9977" in uri:
#deb http://localhost:9977/172.17.126.249:8098/deb/kylin/ 需要去除localhost:9977 在apt-p2p的模式下
network_uri = uri.split("//")[1].split("/")[1]
for second_dir in os.listdir(check_dir_one):
#到/media/x/test
check_dir_two = check_dir_one + second_dir + "/"
if not os.path.isdir(check_dir_two):
continue
check_file = check_dir_two + "ss.map"
logging.info("Check: CD-ROM source File(%s)",check_file)
if os.path.exists(check_file):
self.is_disc = True
logging.info("Use to CD-Source and Turn off NetworkCheck and CloseFiter...")
return
#没有返回存在光盘源就说明不存在
self.is_disc = False
return
else:
#只拿去 网站主地址 例如http://ppa.launchpad.dev/luoxueyi/v101/kylin-desktop 只截取ppa.launchpad.dev 使用此来检查网络
network_uri = uri.split("//")[1].split("/")[0]
self.is_disc = False
return
#去除这个问题172.17.126.249:8098 带端口号的
if ":" in network_uri:
network_uri = network_uri.split(":")[0]
# #当检查失败时 再切换到ping再进行一次检查
# def mount_squashfs(self,mount_source):
# args = ["mount", "-o","loop",mount_source,self.MOUNT_SQUASHFS_PATH]
logging.info("Check network connectivity to use ping %s...",network_uri)
#ping 一次总超时时间为5S
response = os.system("ping -c 1 -w 5 "+network_uri+" 2>&1 >/dev/null")
if response == 0:
return True,header,desc
else:
header = _("Please check your network connection and retry.")
return False,header,desc
#当源列表为空时 从此反回,这种认为这是一种正常的状况 进行之后的动作
return True,header,desc
# p = subprocess.run(args, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
# logging.info(str(p.stdout))
# if p.returncode == 0:
# self.is_mounted = True
# return True,' '
# elif p.returncode == 1:
# self.is_mounted = True
# return True,' '
# else:
# self.is_mounted = False
# return False,str(p.stdout)
# def check_mount(self):
# if self.is_mounted == True:
# args = ["umount",self.MOUNT_SQUASHFS_PATH]
# logging.info("Will be to umount the offlinesource...")
# p = subprocess.run(args, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
# logging.info(str(p.stdout))
# if p.returncode == 0:
# self.is_mounted = False
# return True
# else:
# return False

View File

@ -1,6 +1,7 @@
#!/usr/bin/python3
import os
import dbus
import time
import dbus.service
import logging
@ -10,7 +11,6 @@ from .backend import InstallBackend
from .Core.loop import mainloop
import SystemUpdater.Core.enums as enums
from .Core.errors import *
# from .Core.enums import *
from .Core.utils import humanize_size
from SystemUpdater.Core.utils import get_proc_from_dbus_name,PolicyKit_Authority
from SystemUpdater.Core.UpdaterConfigParser import UpgradeConfig
@ -54,6 +54,16 @@ UU_UPGRADE_MODE_BEFORE_SHUTDOWN = 1
class UpdateManagerDbusController(dbus.service.Object):
""" this is a helper to provide the UpdateManagerIFace """
RETURN_SUCCESS_CODE = 0
RETURN_SUCCESS_DESC = ""
RETURN_UNKNOWN_CODE = -1
RETURN_UNKNOWN_DESC = ""
RETURN_BUSY_STATE = 1
RETURN_BUSY_DESC = "In the process of updating or Upgrading..."
def __init__(self, parent, bus_name,
object_path=UPDATER_DBUS_PATH):
dbus.service.Object.__init__(self, bus_name, object_path)
@ -112,6 +122,9 @@ class UpdateManagerDbusController(dbus.service.Object):
return retval
except Exception as e:
logging.error(str(e))
if key == "init" and value == "config":
self.make_aptdeamon_restart()
time.sleep(0.5)
return False
def check_connectivity(self):
@ -239,68 +252,70 @@ class UpdateManagerDbusController(dbus.service.Object):
return self.parent.now_working
except Exception as e:
logging.error(str(e))
return False
return self.parent.now_working
#apt install -f
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='b')
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='is')
def FixBrokenDepends(self):
try:
#处于更新和升级中的话 不进行更新
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.warning('FixBrokenDepends In the process of updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' FixBrokenDepends ...')
self.parent.start_fix_broken()
return True
except Exception:
return False
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return self.RETURN_UNKNOWN_CODE,str(e)
#dpkg configure -a
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='b')
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='is')
def FixIncompleteInstall(self):
try:
#处于更新和升级中的话 不进行更新
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.warning('FixIncompleteInstall In the process of updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' FixIncompleteInstall ...')
self.parent.start_fix_incomplete()
return True
except Exception:
return False
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return self.RETURN_UNKNOWN_CODE,str(e)
#更新的dbus
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='bs',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='is',sender_keyword='sender')
def UpdateDetect(self,sender=None):
try:
#处于更新和升级中的话 不进行更新
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.warning('UpdateDetect In the process of Updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UpdateDetect sender:%s...',sender_name)
self._check_prohibit_user(sender_name)
self.parent.start_update()
return True,'success'
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return False,str(e)
return self.RETURN_UNKNOWN_CODE,str(e)
#部分升级
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='bas',out_signature='bs',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='bas',out_signature='is',sender_keyword='sender')
def DistUpgradePartial(self,_is_install,_partial_upgrade_list,sender=None):
try:
not_resolver = bool(_is_install)
if not self.parent.update_list:
logging.warning('Perform \"UpdateDetect\" first')
return False,'Perform \"UpdateDetect\" first'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
#处于更新和升级中的话 不进行升级
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.warning('DistUpgradePartial In the process of updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
sender_name = get_proc_from_dbus_name(sender)
partial_upgrade_list = [str(i) for i in _partial_upgrade_list]
@ -313,38 +328,38 @@ class UpdateManagerDbusController(dbus.service.Object):
if new_upgrade_list:
self.parent.start_install(InstallBackend.MODE_INSTALL_PARTIAL,not_resolver,partial_upgrade_list)
return True,'dbus upgrading'
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
else:
logging.warning('input upgrade list(%s) not in local upgrade_list(%s)',partial_upgrade_list,local_upgrade_groups+local_single_pkgs)
return False,'upgrade_list is empty'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
except Exception as e:
logging.info(str(e))
return False,str(e)
return self.RETURN_UNKNOWN_CODE,str(e)
#全部升级
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='b',out_signature='bs',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='b',out_signature='is',sender_keyword='sender')
def DistUpgradeAll(self,_is_install,sender=None):
try:
not_resolver = bool(_is_install)
if not self.parent.update_list:
logging.warning('Perform \"UpdateDetect\" first')
return False,'Perform \"UpdateDetect\" first'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
#处于更新和升级中的话 不进行升级
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.warning('DistUpgradeAll In the process of updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
sender_name = get_proc_from_dbus_name(sender)
self._check_prohibit_user(sender_name)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' DistUpgradeAll and not_resolver:%r...',not_resolver)
self.parent.start_install(InstallBackend.MODE_INSTALL_ALL,not_resolver)
return True,'success'
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.info(str(e))
return False,str(e)
return self.RETURN_UNKNOWN_CODE,str(e)
# 全盘升级 也就是 apt dist-upgrade 升级的方式
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='b',out_signature='bs',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='b',out_signature='is',sender_keyword='sender')
def DistUpgradeSystem(self,_is_install,sender=None):
try:
not_resolver = bool(_is_install)
@ -352,19 +367,19 @@ class UpdateManagerDbusController(dbus.service.Object):
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' DistUpgradeSystem and not_resolver:%r...',not_resolver)
logging.warning('DistUpgradeSystem In the process of updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
sender_name = get_proc_from_dbus_name(sender)
self._check_prohibit_user(sender_name)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' DistUpgradeSystem and not_resolver:%r...',not_resolver)
self.parent.start_install(InstallBackend.MODE_INSTALL_SYSTEM,not_resolver)
return True,'success'
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(False, str(e))
return (False, str(e))
return self.RETURN_UNKNOWN_CODE,str(e)
#卸载包
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='asss',out_signature='bs',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='asss',out_signature='is',sender_keyword='sender')
def PurgePackages(self,_purge_list,cur_user,user_lang = '', sender=None):
try:
#当传入为空时 直接返回
@ -378,7 +393,7 @@ class UpdateManagerDbusController(dbus.service.Object):
#合法性的校验
if input_lang == None or input_lang == '':
logging.info("The incoming language is Illegal...")
return self.parent.now_working
return self.RETURN_UNKNOWN_CODE,"The incoming language is Illegal..."
#处于更新和升级中的话 不进行更新
if input_lang != local_language or input_lang != local_lang:
@ -393,7 +408,7 @@ class UpdateManagerDbusController(dbus.service.Object):
(status, details) = PolicyKit_Authority(get_source_name_from_enum(sender_name)+_(" requires authentication to uninstall software packages."), sender)
if not status:
self.PurgePackagesFinished(False,details,'')
return False,details
return self.RETURN_UNKNOWN_CODE,details
purge_list = [str(pkg) for pkg in _purge_list]
@ -407,15 +422,15 @@ class UpdateManagerDbusController(dbus.service.Object):
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
self.PurgePackagesFinished(False,_("Other tasks are being updated and upgraded, please uninstall them later."),'')
logging.warning('PurgePackages In the process of updating or Upgrading...')
return False,'PurgePackages In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
self._check_prohibit_user(sender_name)
self.parent.start_purge_pkgs(purge_list)
return True,'success'
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return False,str(e)
return self.RETURN_UNKNOWN_CODE,str(e)
# 取消transaction
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='b')
@ -444,7 +459,7 @@ class UpdateManagerDbusController(dbus.service.Object):
# 安装本地deb包
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='ssbbs',out_signature='b',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='ssbbs',out_signature='is',sender_keyword='sender')
def InstallDebFile(self,source = "unKnown", path = "", _check_local_dep = False, _auto_satisfy = False, user_lang = '', sender=None):
try:
#当传入为空时 直接返回
@ -458,7 +473,7 @@ class UpdateManagerDbusController(dbus.service.Object):
#合法性的校验
if input_lang == None or input_lang == '':
logging.info("The incoming language is Illegal...")
return self.parent.now_working
return self.RETURN_UNKNOWN_CODE,"The incoming language is Illegal..."
#处于更新和升级中的话 不进行更新
if input_lang != local_language or input_lang != local_lang:
@ -474,70 +489,74 @@ class UpdateManagerDbusController(dbus.service.Object):
check_local_dep = bool(_check_local_dep)
auto_satisfy = bool(_auto_satisfy)
deb_path = str(path)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' InstallDebFile and check_local_dep:%r, auto_satisfy:%r, current_lang:%s .',\
check_local_dep,auto_satisfy,user_lang)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' InstallDebFile and check_local_dep:%r, auto_satisfy:%r, current_lang:%s , InstallDebFile sender: %s .',\
check_local_dep,auto_satisfy,user_lang,sender_name)
logging.info("Will install: %s.",path)
self.parent.start_deb_install(deb_path, _check_local_dep, _auto_satisfy, source, sender)
return True
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return (False)
return self.RETURN_UNKNOWN_CODE,str(e)
# commitpackages
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='as',out_signature='b',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='as',out_signature='is',sender_keyword='sender')
def InstallPackages(self, pkg_list = [], sender=None):
try:
sender_name = get_proc_from_dbus_name(sender)
self._check_prohibit_user(sender_name)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' InstallPackages : [%s].', ", ".join(list(pkg_list)))
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' InstallPackages : [%s], InstallPackages sender: %s .', ", ".join(list(pkg_list)), sender_name)
self.parent.start_back_upgrade(pkg_list)
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return (False)
return True
return self.RETURN_UNKNOWN_CODE,str(e)
#更新的dbus
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='bs',sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE,out_signature='is',sender_keyword='sender')
def UpdateCache(self,sender=None):
try:
#处于更新和升级中的话 不进行更新
if self.parent.now_working != InstallBackend.ACTION_DEFUALT_STATUS:
logging.warning('UpdateDetect In the process of Updating or Upgrading...')
return False,'In the process of updating or Upgrading...'
return self.RETURN_BUSY_STATE,self.RETURN_BUSY_DESC
else:
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UpdateCache sender:%s...',sender_name)
self._check_prohibit_user(sender_name)
self.parent.start_update_backend(InstallBackend.MODE_UPDATE_CACHE)
return True,'success'
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return False,str(e)
return self.RETURN_UNKNOWN_CODE,str(e)
# dbus接口向数据库display表中插入数据
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='b', sender_keyword='sender')
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='is', sender_keyword='sender')
def InsertInstallState(self, item, value, sender=None):
try:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' InsertInstallState, options:%svalue:%s' % (item, value))
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' InsertInstallState, options:%svalue:%s, InsertInstallState sender: %s .' % (item, value, sender_name))
self.parent.sqlite3_server.insert_into_display(item, value)
logging.info("Database inserted successfullyoptions:%svalue:%s" % (item, value))
return True
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error("Database insert failedoptions:%svalue:%s" % (item, value))
return False
return self.RETURN_UNKNOWN_CODE,str(e)
# TODO 已迁移
# 是否允许关机前更新
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='bs')
def UnattendedUpgradeValue(self, operation, value="false"):
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='is', sender_keyword='sender')
def UnattendedUpgradeValue(self, operation, value="false", sender=None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UnattendedUpgradeValue sender:%s ', sender_name)
if operation.lower() != "get" and operation.lower() != "set":
return False, 'Please input [\"set\", \"value\"] to set. \nor [\"get\"] to get whether updates are allowed before shutdown.'
return self.RETURN_UNKNOWN_CODE, 'Please input [\"set\", \"value\"] to set. \nor [\"get\"] to get whether updates are allowed before shutdown.'
if operation == "set":
try:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UnattendedUpgradeValue is going to %s [allow_unattended_upgrades_shutdown] value to %s.'%(operation,value))
self.parent.sqlite3_server.insert_into_display("allow_unattended_upgrades_shutdown", value.lower())
except Exception as e:
logging.error(str(e))
return False,str(e)
return self.RETURN_UNKNOWN_CODE,str(e)
else:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UnattendedUpgradeValue is going to %s [allow_unattended_upgrades_shutdown] value.'%(operation))
try:
@ -545,24 +564,28 @@ class UpdateManagerDbusController(dbus.service.Object):
logging.info("[allow_unattended_upgrades_shutdown] value is %s."%(value))
except Exception as e:
logging.error(str(e))
return False,str(e)
return True,"success"
return self.RETURN_UNKNOWN_CODE,str(e)
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
# TODO 已迁移
# 设置自动更新时间
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='s', out_signature='bs')
def SetAutoUpgradePeriod(self, period):
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetAutoUpgradePeriod will be set value %s.'%(period))
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='s', out_signature='is',sender_keyword='sender')
def SetAutoUpgradePeriod(self, period, sender = None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetAutoUpgradePeriod will be set value %s, SetAutoUpgradePeriod sender: %s.'%(period, sender_name))
try:
self.parent.sqlite3_server.insert_into_display("update_period", period.lower())
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
except Exception as e:
logging.error(str(e))
return True,"success"
return self.RETURN_UNKNOWN_CODE,str(e)
# TODO 已迁移
# # dbus接口改变apt下载速度
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='sb', out_signature='b')
def SetDownloadspeedMax(self, speed, set):
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetDownloadspeedMax, speed:%s, set:%r.'%(speed, set))
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='sb', out_signature='is',sender_keyword='sender')
def SetDownloadspeedMax(self, speed, set,sender = None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetDownloadspeedMax, speed:%s, set:%r, sender name: %s .'%(speed, set, sender_name))
#来重启Aptdeamon
self.parent.init_config_aptdeamon = True
if set:
@ -575,25 +598,25 @@ class UpdateManagerDbusController(dbus.service.Object):
self.parent.sqlite3_server.insert_into_display("download_limit_value",str(speed))
#发送信号
self.ButtonStatusChange("speed" , str(speed))
return True
except Exception as e:
logging.error(e)
return False
return self.RETURN_UNKNOWN_CODE,str(e)
else:
if os.path.exists("/etc/apt/apt.conf.d/80apt-download"):
os.remove("/etc/apt/apt.conf.d/80apt-download")
self.parent.sqlite3_server.insert_into_display("download_limit","false")
self.ButtonStatusChange("speed", "0")
return True
else:
self.parent.sqlite3_server.insert_into_display("download_limit","false")
self.ButtonStatusChange("speed", "0")
return True
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
# TODO 已迁移
# # dbus接口获取apt下载速度
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='bs')
def GetDownloadspeedLimitValue(self):
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetDownloadspeedLimitValue...')
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='bs',sender_keyword='sender')
def GetDownloadspeedLimitValue(self,sender = None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetDownloadspeedLimitValue sender: %s .', sender_name)
try:
download_limit = self.parent.sqlite3_server.select_from_display("download_limit")
if download_limit == "true":
@ -606,10 +629,11 @@ class UpdateManagerDbusController(dbus.service.Object):
## dbus接口: 开启或关闭预下载功能
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='b', out_signature='b')
def SetPreDownloadState(self, _state):
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='b', out_signature='b',sender_keyword='sender')
def SetPreDownloadState(self, _state,sender = None):
state = bool(_state)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetPreDownloadState, state is %r ...',state)
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetPreDownloadState, state is %r, sender name: %s .',state,sender_name)
try:
if state:
self.parent.uuconfigs.setValue("autoUpgradePolicy", "preDownload", "on", True)
@ -723,6 +747,7 @@ class UpdateManagerDbusController(dbus.service.Object):
return False
return True
# TODO 已迁移
# kill 进程
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='i', out_signature='b')
def KillProcessSignal(self, pid):
@ -739,6 +764,7 @@ class UpdateManagerDbusController(dbus.service.Object):
return False
return True
# TODO 已迁移
# 获取数据库值
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='bss', out_signature='s')
def GetSetDatabaseInfo(self, gs, table, field):
@ -760,9 +786,10 @@ class UpdateManagerDbusController(dbus.service.Object):
return Text
# 获取系统版本号
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='ss')
def GetSystemUpdateVersion(self):
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetSystemUpdateVersion.')
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='ss',sender_keyword='sender')
def GetSystemUpdateVersion(self,sender=None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetSystemUpdateVersion sender: %s .', sender_name)
os_version = ''
update_version = ''
try:
@ -1070,9 +1097,10 @@ class UpdateManagerDbusControllerUtils(dbus.service.Object):
raise dbus.exceptions.DBusException("ERROR: You are not allowed to perform this action.")
# # dbus接口: 后端大数据采集
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='b')
def DataBackendCollect(self, messageType, uploadMessage):
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' DataBackendCollect, messageType is %s ...',messageType)
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='b',sender_keyword='sender')
def DataBackendCollect(self, messageType, uploadMessage, sender=None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' DataBackendCollect, messageType is %s, called by: %s .',messageType,sender_name)
logging.debug("uploadMessage: %s.", uploadMessage)
try:
self.parent.collector.UpdateMsg(messageType, uploadMessage)
@ -1082,7 +1110,7 @@ class UpdateManagerDbusControllerUtils(dbus.service.Object):
# 检查更新
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='as', out_signature='as', sender_keyword='sender')
def CheckInstalledOrUpgrade(self, pkgs, sender=None):
# logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' CheckInstalledOrUpgrade Parsed silent upgrade ...')
sender_name = get_proc_from_dbus_name(sender)
try:
pkglist = []
cache = MyCache(None)
@ -1098,7 +1126,8 @@ class UpdateManagerDbusControllerUtils(dbus.service.Object):
self.parent.collector.background_upgradable.append(pkg.name)
except:
logging.error("CheckInstalledOrUpgrade: Failed to obtain package information: %s" % str(i), exc_info=True)
logging.info("All silent upgrade: %s.",pkglist)
# if len(pkglist) != 0:
# logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' CheckInstalledOrUpgrade, called by: %s, Upgrade list: %s .', sender_name, ", ".join(pkglist))
return pkglist
# 提供插入更新历史的接口

View File

@ -0,0 +1,101 @@
# UpdateManager.py
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*-
import os
import sys
import time
import dbus
import logging
import dbus.service
import traceback
from gettext import gettext as _
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
DBusGMainLoop(set_as_default=True)
from .UpgradeStrategiesDbus import UpgradeStrategiesDbusController,UPDATER_DBUS_INTERFACE,UPDATER_DBUS_PATH,UPDATER_DBUS_SERVICE
from .Core.Database import Sqlite3Server
from .Core.loop import mainloop
from SystemUpdater.Core.UpdaterConfigParser import UpgradeConfig
STRATEGY_IDLE_INTERVAL = 2*60
STRATEGY_IDLE_TIMEOUT = 6*60
class UpgradeStrategies():
def __init__(self,options):
try:
self.options = options
#dbus
self.dbusController = self._setup_dbus()
#config
self.uuconfigs = UpgradeConfig(datadir = "/var/lib/unattended-upgrades/", name = "unattended-upgrades-policy.conf")
self.sqlite3_server = Sqlite3Server(self)
#策略配置接口的超时退出机制
self.strategy_timestamp = 0
GLib.timeout_add_seconds(STRATEGY_IDLE_INTERVAL,
self._check_strategy_inactivity)
except Exception as e:
logging.error(e)
traceback.print_exc()
def run(self):
"""Start the daemon and listen for calls."""
logging.info("Waiting for calls...")
try:
mainloop.run()
except KeyboardInterrupt:
self.dbusController.Quit(None)
def _setup_dbus(self):
# check if there is another g-a-i already and if not setup one
# listening on dbus
bus = dbus.SystemBus()
try:
bus_name = dbus.service.BusName(UPDATER_DBUS_SERVICE,
bus,
do_not_queue=True)
logging.info("Initiate dbus success ...")
return UpgradeStrategiesDbusController(self, bus_name)
except dbus.exceptions.NameExistsException:
if self.options.replace is False:
logging.critical("Another daemon is already running")
sys.exit(1)
logging.warning("Replacing already running daemon")
retry_reboot_times = 0
the_other_guy = bus.get_object(UPDATER_DBUS_SERVICE,
UPDATER_DBUS_PATH)
the_other_guy.Quit(dbus_interface=UPDATER_DBUS_INTERFACE,
timeout=300)
time.sleep(1)
while True:
retry_reboot_times = retry_reboot_times + 1
#当重试次数超过5次时退出程序
if retry_reboot_times > 5:
logging.critical("Reboot backend is Failed...")
sys.exit(1)
try:
bus_name = dbus.service.BusName(UPDATER_DBUS_SERVICE,
bus,
do_not_queue=True)
logging.warning("Replacing already running daemon to Success...")
return UpgradeStrategiesDbusController(self, bus_name)
except dbus.exceptions.NameExistsException:
the_other_guy = bus.get_object(UPDATER_DBUS_SERVICE,
UPDATER_DBUS_PATH)
the_other_guy.Quit(dbus_interface=UPDATER_DBUS_INTERFACE,
timeout=300)
logging.error("Dbus has not withdrawn and retry reboot times:%d...",retry_reboot_times)
time.sleep(1)
def _check_strategy_inactivity(self):
logging.info("Checking for inactivity in Strategies daemon ...")
timestamp = self.strategy_timestamp
if timestamp == 0:
self.strategy_timestamp = time.time()
return True
#超时退出
if self.strategy_timestamp != 0 and time.time() - self.strategy_timestamp > STRATEGY_IDLE_TIMEOUT:
logging.warning("Quitting due to inactivity")
self.dbusController.Quit(None)
return False
return True

View File

@ -0,0 +1,559 @@
#!/usr/bin/python3
import os
import dbus
import dbus.service
import logging
import subprocess
from gettext import gettext as _
from .Core.loop import mainloop
from SystemUpdater.Core.utils import get_proc_from_dbus_name
UPDATER_DBUS_INTERFACE = 'com.kylin.UpgradeStrategies.interface'
UPDATER_DBUS_PATH = '/com/kylin/UpgradeStrategies'
UPDATER_DBUS_SERVICE = 'com.kylin.UpgradeStrategies'
RUN_UNATTENDED_UPGRADE = '/var/run/unattended-upgrades.pid'
SYSTEM_VERSION = '/etc/kylin-version/kylin-system-version.conf'
#颜色设置
COLORLOG_SUFFIX = "\033[0m"
# Define some foreground colors
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
#字体颜色
FRONT_COLOR_SEQ = "\033[1;%dm"
#背景颜色
BACK_COLOR_SEQ = "\033[%d;1m"
COLORLOG_PREFIX = FRONT_COLOR_SEQ % GREEN
COLORMETHOR_PREFIX = FRONT_COLOR_SEQ % CYAN
UU_UPGRADE_MODE_AUTOMATIC_DOWNLOAD = 0
UU_UPGRADE_MODE_MANUAL = 1
UU_UPGRADE_MODE_AUTOMATIC_INSTALL = 2
UU_UPGRADE_MODE_BEFORE_SHUTDOWN = 3
#dbus 建立
class UpgradeStrategiesDbusController(dbus.service.Object):
""" this is a helper to provide the UpdateManagerIFace """
P2P_DEDAULT_PATH = "/etc/default/apt-p2p"
RETURN_SUCCESS_CODE = 0
RETURN_SUCCESS_DESC = ""
RETURN_UNKNOWN_CODE = -1
RETURN_UNKNOWN_DESC = ""
def __init__(self, parent, bus_name,
object_path=UPDATER_DBUS_PATH):
dbus.service.Object.__init__(self, bus_name, object_path)
self.parent = parent
self.bus = dbus.SystemBus()
self.transaction = None
def __check_change__(self, _config = None, _section = "", _option = "", _value = ""):
if _config == None:
return False
if _value == _config.getWithDefault(_section,_option,_value," "):
return True
return False
@dbus.service.method(UPDATER_DBUS_INTERFACE,
in_signature="", out_signature="",
sender_keyword="caller_name")
def Quit(self, caller_name):
"""Request a shutdown of the daemon."""
#如果在下载就请求 取消
logging.info("Quitting was requested")
logging.debug("Quitting main loop...")
mainloop.quit()
logging.debug("Exit")
## dbus接口: 开启或关闭预下载功能
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='s', out_signature='is',sender_keyword='sender')
def ChangingP2PStatus(self,_status,sender = None):
status = str(_status)
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' ChangingP2PStatus, _status = %s , sender name: %s',status,sender_name)
if os.path.exists(self.P2P_DEDAULT_PATH):
if status == "enable":
with open(self.P2P_DEDAULT_PATH, 'w+') as configfile:
configfile.write("#enable=true\n")
elif status == "disable":
with open(self.P2P_DEDAULT_PATH, 'w+') as configfile:
configfile.write("enable=false\n")
else:
logging.waring("error: input value _status=%s",status)
args = ["systemctl","restart","apt-p2p.service"]
p = subprocess.run(args, stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
logging.info(str(p.stdout))
if p.returncode == 0:
logging.info("Execute successfully")
return self.RETURN_SUCCESS_CODE,self.RETURN_SUCCESS_DESC
else:
logging.info("Failed to execute reboot")
return self.RETURN_UNKNOWN_CODE,str(p.stdout)
else:
logging.waring("apt-p2p function is not install...")
## dbus接口: 开启或关闭预下载功能
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='bs', out_signature='b',sender_keyword='sender')
def SetPreDownloadState(self, _state, _time, sender = None):
state = bool(_state)
time = str(_time)
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetPreDownloadState, state is %r, time: %s, sender name: %s .',state,time,sender_name)
try:
if state:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "preDownload", "on"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "preDownload", "on", True)
self.PropertyChanged("preDownload","on")
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "preDownloadTime", time):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "preDownloadTime", time, True)
self.PropertyChanged("preDownloadTime",time)
else:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "preDownload", "off"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "preDownload", "off", True)
self.PropertyChanged("preDownload","off")
except Exception as e:
logging.error(str(e))
return False
return True
## 设置更新周期
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='i', out_signature='b',sender_keyword='sender')
def SetUpdateDays(self, days, sender = None):
_days = int(days)
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetUpdateDays, days: %d , sender:%s .'\
,_days,sender_name)
try:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "updateDays", _days):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "updateDays", str(_days), True)
self.PropertyChanged("updateDays",str(_days))
except Exception as e:
logging.error(str(e))
return False
return True
# 设置自动更新时间
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='s', out_signature='bs',sender_keyword='sender')
def SetAutoUpgradeRandomRange(self,randomRange,sender=None):
_randomRange = str(randomRange)
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetAutoUpgradeRandomRange will be set value %s, sender: %s .',\
_randomRange,sender_name)
try:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "randomRange", _randomRange):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "randomRange", _randomRange, True)
self.PropertyChanged("randomRange",_randomRange)
except Exception as e:
logging.error(str(e))
return True,"success"
## 设置是否开启自动重启,以及设置自动重启的时间
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='bs', out_signature='b',sender_keyword='sender')
def SetAutomaticReboot(self, status, reboot_time, sender = None):
_state = bool(status)
_reboot_time = str(reboot_time)
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetAutomaticReboot, status is %r, reboot_time: %s, sender name: %s .'\
,_state,_reboot_time,sender_name)
try:
if _state:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "automaticReboot", "on"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "automaticReboot", "on", True)
self.PropertyChanged("automaticReboot","on")
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "automaticRebootTime", _reboot_time):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "automaticRebootTime", _reboot_time, True)
self.PropertyChanged("automaticRebootTime",_reboot_time)
else:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "automaticReboot", "off"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "automaticReboot", "off", True)
self.PropertyChanged("automaticReboot","off")
except Exception as e:
logging.error(str(e))
return False
return True
## dbus接口: 开启关闭自动更新功能
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='b', out_signature='b')
def SetAutoUpgradeState(self, _state):
state = bool(_state)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetAutoUpgradeState, state is %r ...',state)
try:
if state:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "autoUpgradeState", "on"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "autoUpgradeState", "on", True)
self.parent.sqlite3_server.insert_into_display("autoupdate_allow", "true")
self.PropertyChanged("autoUpgradeState","on")
self.ButtonStatusChange("autoUpgradeStatus", "true")
else :
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "autoUpgradeState", "off"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "autoUpgradeState", "off", True)
self.parent.sqlite3_server.insert_into_display("autoupdate_allow", "false")
self.PropertyChanged("autoUpgradeState","off")
self.ButtonStatusChange("autoUpgradeStatus", "false")
except Exception as e:
logging.error(str(e))
return False
return True
## dbus接口: 设置自动更新策略
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='is', out_signature='b')
def SetAutoUpgradeMode(self, mode, time):
_time = str(time)
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' SetAutoUpgradeMode, mode is %s, time is %s ...',mode,_time)
try:
if mode == UU_UPGRADE_MODE_AUTOMATIC_DOWNLOAD:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "downloadMode", "timing"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "downloadMode", "timing", True)
self.PropertyChanged("downloadMode","timing")
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "downloadTime", str(_time)):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "downloadTime", str(_time), True)
self.PropertyChanged("downloadTime",str(_time))
self.ButtonStatusChange("autoUpgradeTime", str(_time))
elif mode == UU_UPGRADE_MODE_AUTOMATIC_INSTALL:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "installMode", "timing"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "installMode", "timing", True)
self.PropertyChanged("installMode","timing")
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "installTime", str(_time)):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "installTime", str(_time), True)
self.PropertyChanged("installTime",str(_time))
elif mode == UU_UPGRADE_MODE_BEFORE_SHUTDOWN:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "installTime", "bshutdown"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "installMode", "bshutdown", True)
self.PropertyChanged("installMode","bshutdown")
elif mode == UU_UPGRADE_MODE_MANUAL:
if not self.__check_change__(self.parent.uuconfigs, "autoUpgradePolicy", "downloadMode", "manual"):
self.parent.uuconfigs.setValue("autoUpgradePolicy", "downloadMode", "manual", True)
self.PropertyChanged("downloadMode","manual")
except Exception as e:
logging.error(str(e))
return False
return True
# # dbus接口改变apt下载速度
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='sb', out_signature='b',sender_keyword='sender')
def SetDownloadspeedMax(self, speed, set,sender = None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetDownloadspeedMax, speed:%s, set:%r, sender name: %s .'%(speed, set, sender_name))
#来重启Aptdeamon
self.parent.init_config_aptdeamon = True
if set:
with open("/etc/apt/apt.conf.d/80apt-download", "w+") as f:
try:
f.write("Acquire::http::Dl-Limit" + " \"" + "%s" % str(speed) + "\";\n")
f.write("Acquire::https::Dl-Limit" + " \"" + "%s" % str(speed) + "\";\n")
#更改数据库值
self.parent.sqlite3_server.insert_into_display("download_limit","true")
self.parent.sqlite3_server.insert_into_display("download_limit_value",str(speed))
#发送信号
self.ButtonStatusChange("speed" , str(speed))
return True
except Exception as e:
logging.error(e)
return False
else:
if os.path.exists("/etc/apt/apt.conf.d/80apt-download"):
os.remove("/etc/apt/apt.conf.d/80apt-download")
self.parent.sqlite3_server.insert_into_display("download_limit","false")
self.ButtonStatusChange("speed", "0")
return True
else:
self.parent.sqlite3_server.insert_into_display("download_limit","false")
self.ButtonStatusChange("speed", "0")
return True
# # dbus接口获取apt下载速度
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='bs',sender_keyword='sender')
def GetDownloadspeedLimitValue(self,sender = None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetDownloadspeedLimitValue sender: %s .', sender_name)
try:
download_limit = self.parent.sqlite3_server.select_from_display("download_limit")
if download_limit == "true":
download_limit_value = self.parent.sqlite3_server.select_from_display("download_limit_value")
return True,str(download_limit_value)
else:
return False,str("0")
except:
return False, "0"
# 是否允许关机前更新
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='ss', out_signature='bs', sender_keyword='sender')
def UnattendedUpgradeValue(self, operation, value="false", sender=None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UnattendedUpgradeValue sender:%s ', sender_name)
if operation.lower() != "get" and operation.lower() != "set":
return False, 'Please input [\"set\", \"value\"] to set. \nor [\"get\"] to get whether updates are allowed before shutdown.'
if operation == "set":
try:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UnattendedUpgradeValue is going to %s [allow_unattended_upgrades_shutdown] value to %s.'%(operation,value))
self.parent.sqlite3_server.insert_into_display("allow_unattended_upgrades_shutdown", value.lower())
except Exception as e:
logging.error(str(e))
return False,str(e)
else:
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' UnattendedUpgradeValue is going to %s [allow_unattended_upgrades_shutdown] value.'%(operation))
try:
value = self.parent.sqlite3_server.select_from_display("allow_unattended_upgrades_shutdown")
logging.info("[allow_unattended_upgrades_shutdown] value is %s."%(value))
except Exception as e:
logging.error(str(e))
return False,str(e)
return True,"success"
# 设置自动更新时间
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='s', out_signature='bs',sender_keyword='sender')
def SetAutoUpgradePeriod(self, period, sender = None):
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetAutoUpgradePeriod will be set value %s, SetAutoUpgradePeriod sender: %s.'%(period, sender_name))
try:
self.parent.sqlite3_server.insert_into_display("update_period", period.lower())
except Exception as e:
logging.error(str(e))
return True,"success"
# 获取数据库值
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='bss', out_signature='s')
def GetSetDatabaseInfo(self, gs, table, field):
Text = 'NULL'
try:
if gs: #get
if table == 'display':
Text = self.parent.sqlite3_server.select_from_display(str(field))
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetDatabaseInfo Table:%s Field:%s Text:%s',table,field,Text)
else: #set
if table == 'display' and "=" in field:
field, value = str(field).split("=")
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetDatabaseInfo Table:%s Field:%s', table, field)
self.parent.sqlite3_server.insert_into_display(field, value)
return "success"
except Exception as e:
logging.error(str(e))
return Text
return Text
## dbus接口: 发送立即更新的信号
@dbus.service.method(UPDATER_DBUS_INTERFACE, out_signature='b')
def AutoUpgradeAllNow(self):
logging.info(COLORMETHOR_PREFIX+'method'+COLORLOG_SUFFIX+' AutoUpgradeAllNow ...')
try:
self.UpgradeAllNow()
except Exception as e:
logging.error(str(e))
return False
return True
# kill 进程
@dbus.service.method(UPDATER_DBUS_INTERFACE, in_signature='i', out_signature='b')
def KillProcessSignal(self, pid):
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' KillProcessSignal is %d', pid)
try:
# 判断文件是否存在
if (os.path.exists(RUN_UNATTENDED_UPGRADE)):
os.kill(int(pid), 9)
logging.info('%s has been killed', pid)
else:
logging.warning('%s is not exist.', RUN_UNATTENDED_UPGRADE)
except Exception as e:
logging.error(str(e))
return False
return True
#设置数据库配置信息
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='ss',out_signature='b',sender_keyword='sender')
def DatabaseInfoSet(self,field_name,field_value,sender=None):
Status = False
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' SetDatabaseInfo,field_name:%s,field_value:%s,caller:%s .',\
field_name,field_value,sender_name)
Status = self.parent.sqlite3_server.insert_into_display(field_name,field_value)
return bool(Status)
#数据库获取配置信息
@dbus.service.method(UPDATER_DBUS_INTERFACE,in_signature='s',out_signature='s',sender_keyword='sender')
def DatabaseInfoGet(self,field_name,sender=None):
field_value = ''
sender_name = get_proc_from_dbus_name(sender)
logging.info(COLORMETHOR_PREFIX+'Method'+COLORLOG_SUFFIX+' GetDatabaseInfo field_name:%s caller:%s',field_name,sender_name)
field_value = self.parent.sqlite3_server.select_from_display(str(field_name))
logging.info("Get field_value:%s",field_value)
return field_value
#限速修改信号
@dbus.service.signal(UPDATER_DBUS_INTERFACE,signature='ss')
def ButtonStatusChange(self, signal_types = '', value=''):
logging.info(COLORLOG_PREFIX + "Emitting"+ COLORLOG_SUFFIX + " ButtonStatusChange signal_types = %s, value = %s.",signal_types, value)
# dbus 信号:用于发送立即更新信号
@dbus.service.signal(UPDATER_DBUS_INTERFACE)
def UpgradeAllNow(self):
logging.info(COLORLOG_PREFIX + "Emitting" + COLORLOG_SUFFIX +" UpgradeAllNow")
# dbus 信号:用于发送自动更新配置更改信号
@dbus.service.signal(UPDATER_DBUS_INTERFACE)
def ChangeUpgradePolicy(self):
logging.info(COLORLOG_PREFIX + "Emitting" + COLORLOG_SUFFIX +" ChangeUpgradePolicy")
#限速修改信号
@dbus.service.signal(UPDATER_DBUS_INTERFACE,signature='ss')
def ButtonStatusChange(self, signal_types = '', value=''):
logging.info(COLORLOG_PREFIX + "Emitting"+ COLORLOG_SUFFIX + " ButtonStatusChange signal_types = %s, value = %s.",signal_types, value)
# signal属性发生改变
@dbus.service.signal(dbus_interface=UPDATER_DBUS_INTERFACE,
signature="ss")
def PropertyChanged(self, property, value):
logging.info(COLORLOG_PREFIX + "Emitting" + COLORLOG_SUFFIX +" PropertyChanged: ( %s, %s )" % (property, value))
# WRITABLE_PROPERTIES = ()
# # pylint: disable-msg=C0103,C0322
# @dbus.service.signal(dbus_interface=dbus.PROPERTIES_IFACE,
# signature="sa{sv}as")
# def PropertiesChanged(self, interface, changed_properties,
# invalidated_properties):
# """The signal gets emitted if a property of the object's
# interfaces changed.
# :param property: The name of the interface.
# :param changed_properties: A dictrionary of changed
# property/value pairs
# :param invalidated_properties: An array of property names which
# changed but the value isn't conveyed.
# :type interface: s
# :type changed_properties: a{sv}
# :type invalidated_properties: as
# """
# logging.info("Emitting PropertiesChanged: %s, %s, %s" %
# (interface, changed_properties, invalidated_properties))
# # pylint: disable-msg=C0103,C0322
# @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
# in_signature='', out_signature='s',
# path_keyword='object_path',
# connection_keyword='connection')
# def Introspect(self, object_path, connection):
# # Inject the properties into the introspection xml data
# data = dbus.service.Object.Introspect(self, object_path, connection)
# xml = ElementTree.fromstring(data)
# for iface in xml.findall("interface"):
# props = self._get_properties(iface.attrib["name"])
# for key, value in props.items():
# attrib = {"name": key}
# if key in self.WRITABLE_PROPERTIES:
# attrib["access"] = "readwrite"
# else:
# attrib["access"] = "read"
# if isinstance(value, dbus.String):
# attrib["type"] = "s"
# elif isinstance(value, dbus.UInt32):
# attrib["type"] = "u"
# elif isinstance(value, dbus.Int32):
# attrib["type"] = "i"
# elif isinstance(value, dbus.UInt64):
# attrib["type"] = "t"
# elif isinstance(value, dbus.Int64):
# attrib["type"] = "x"
# elif isinstance(value, dbus.Boolean):
# attrib["type"] = "b"
# elif isinstance(value, dbus.Struct):
# attrib["type"] = "(%s)" % value.signature
# elif isinstance(value, dbus.Dictionary):
# attrib["type"] = "a{%s}" % value.signature
# elif isinstance(value, dbus.Array):
# attrib["type"] = "a%s" % value.signature
# else:
# raise Exception("Type %s of property %s isn't "
# "convertable" % (type(value), key))
# iface.append(ElementTree.Element("property", attrib))
# new_data = ElementTree.tostring(xml, encoding="UTF-8")
# return new_data
# # pylint: disable-msg=C0103,C0322
# @dbus.service.method(dbus.PROPERTIES_IFACE,
# in_signature="ssv", out_signature="",
# sender_keyword="sender")
# def Set(self, iface, name, value, sender):
# """Set a property.
# Only the user who intiaited the transaction is
# allowed to modify it.
# :param iface: The interface which provides the property.
# :param name: The name of the property which should be modified.
# :param value: The new value of the property.
# :type iface: s
# :type name: s
# :type value: v
# """
# logging.info("Set() was called: %s, %s" % (name, value))
# return self._set_property(iface, name, value, sender)
# # pylint: disable-msg=C0103,C0322
# @dbus.service.method(dbus.PROPERTIES_IFACE,
# in_signature="s", out_signature="a{sv}")
# def GetAll(self, iface):
# """Get all available properties of the given interface."""
# logging.info("GetAll() was called: %s" % iface)
# return self._get_properties(iface)
# # pylint: disable-msg=C0103,C0322
# @dbus.service.method(dbus.PROPERTIES_IFACE,
# in_signature="ss", out_signature="v")
# def Get(self, iface, property):
# """Return the value of the given property provided by the given
# interface.
# """
# logging.info("Get() was called: %s, %s" % (iface, property))
# return self._get_properties(iface)[property]
# def _set_property(self, iface, name, value, sender):
# """Helper to set a property on the properties D-Bus interface."""
# if iface == UPDATER_DBUS_INTERFACE:
# if name == "ShutdownInstall":
# self.parent.configs_uncover.setValue("InstallMode","shutdown_install",str(bool(value)))
# elif name == "UploadUpgradeLog":
# self.parent.configs_uncover.setValue("SystemStatus","upload_upgrade_log",str(bool(value)))
# elif name == "UploadInstallerLog":
# self.parent.configs_uncover.setValue("SystemStatus","upload_installer_log",str(bool(value)))
# else:
# raise dbus.exceptions.DBusException("Unknown or read only "
# "property: %s" % name)
# else:
# raise dbus.exceptions.DBusException("Unknown interface: %s" %
# iface)
# def _get_properties(self, iface):
# """Helper get the properties of a D-Bus interface."""
# if iface == UPDATER_DBUS_INTERFACE:
# return {
# "ShutdownInstall": dbus.Boolean(
# self.parent.configs_uncover.getWithDefault("InstallMode", "shutdown_install", False)),
# "UploadUpgradeLog": dbus.Boolean(
# self.parent.configs_uncover.getWithDefault("SystemStatus", "upload_upgrade_log", True)),
# "UploadInstallerLog": dbus.Boolean(
# self.parent.configs_uncover.getWithDefault("SystemStatus", "upload_installer_log", False))
# }
# else:
# return {}

View File

@ -295,7 +295,8 @@ class InstallBackendAptdaemon(InstallBackend):
def purge_packages(self,pkgs_purge):
"""卸载deb包 """
try:
trans = yield self.client.remove_packages(package_names = pkgs_purge,defer=True)
# trans = yield self.client.remove_packages(package_names = pkgs_purge,defer=True)
trans = yield self.client.commit_packages([],[],[],pkgs_purge,[],[],defer=True)
self.window_main.dbusController.transaction = trans
# 注册回调函数 接收更新的状态
yield self._show_transaction(trans, self.ACTION_REMOVE_PACKAGES,
@ -306,9 +307,9 @@ class InstallBackendAptdaemon(InstallBackend):
error_string='', error_desc='')
except Exception as e:
logging.error(str(e))
self._action_done(self.ACTION_REMOVE_PACKAGES,
is_cancelled=False, success=False,
error_string=str(e), error_desc='')
# self._action_done(self.ACTION_REMOVE_PACKAGES,
# is_cancelled=False, success=False,
# error_string=str(e), error_desc='')
#进度回调
def _on_progress_changed(self, trans,progress,action):
@ -353,7 +354,7 @@ class InstallBackendAptdaemon(InstallBackend):
if progress > 51 and progress < 90 and self.on_install_stage == False:
logging.info("The process is now in the installtion phase")
self.on_install_stage = True
self._start_install_lock()
self._start_install_lock(_("Kylin System Updater"))
#只处理从下载切换到安装时出现的网络问题
#当网络波动时下载某些软件包失败时属于异常状态进行重试时 不发送后续进度 等待重试正常是 进行下载安装
@ -464,10 +465,10 @@ class InstallBackendAptdaemon(InstallBackend):
try:
error_string = ''
error_desc = ''
#退出
self.on_install_stage = False
if status == EXIT_FAILED:
# self.log_audit(str(trans.error.code))
error_string = get_error_string_from_enum(trans.error.code)
error_desc = get_error_description_from_enum(trans.error.code)
if self.trans_failed_msg:
@ -488,3 +489,40 @@ class InstallBackendAptdaemon(InstallBackend):
except Exception as e:
logging.error(e)
traceback.print_exc()
# def log_audit(self,error_code):
# if error_code == "error-package-manager-failed":
# error_msg = self.check_install_error()
# with open("/var/log/kylin-system-updater/error_details.log", 'w+') as configfile:
# configfile.write(str(error_msg))
# def check_install_error(self):
# locate_error = ''
# with open("/var/log/apt/term.log", "r+") as f:
# log_start = None
# log_end = None
# aptterm_log = f.readlines()
# reverse_log = aptterm_log[::-1]
# for logstr in reverse_log:
# if log_end == None and "Log ended:" in logstr:
# log_end = aptterm_log.index(logstr)
# if log_start == None and "Log started:" in logstr:
# log_start = aptterm_log.index(logstr)
# if log_end != None and log_start != None:
# break
# latest_log = aptterm_log[log_start:log_end+1]
# error_deb = latest_log[-2].strip()
# error_msg_line = None
# for log_msg in latest_log:
# if error_deb in log_msg:
# error_msg_line = latest_log.index(log_msg)
# locate_error = latest_log[error_msg_line-5:error_msg_line+5]
# break
# return locate_error

View File

@ -10,6 +10,9 @@ import json
import logging
import subprocess
import traceback
import shutil
import fcntl
import threading
from apt import Cache
from gettext import gettext as _
from SystemUpdater.Core.errors import *
@ -17,6 +20,7 @@ from SystemUpdater.Core.enums import *
from SystemUpdater.Core.DataAcquisition import get_east_8_time
from SystemUpdater.Core.UpdateList import LocalUpgradeDataList
from SystemUpdater.Core.DistUpgradeCache import NotEnoughFreeSpaceError
from SystemUpdater.Core.utils import get_config_patch
class NowUpgradeMeta:
"""
@ -76,7 +80,7 @@ class UpdateEssentialItem():
self.essential_pkgs = []
self.remove_white = []
self.read_path = parent.window_main.config_path + 'kylin-update-desktop-system.json'
self.read_path = get_config_patch() + 'kylin-update-desktop-system.json'
self.update()
def update(self):
@ -97,12 +101,15 @@ class UpdateEssentialItem():
logging.info("Check: For remove of Essential Packages...")
for pkg in remove_pkgs:
if pkg in self.essential_pkgs:
logging.error("Essential Packages(%s) will be Removed...",pkg)
raise UpdateBaseError(ERROR_REMOVE_ESSENTIAL_PACKAGES)
def check_white(self,remove_pkgs):
logging.info("Check: remove pkg in White Packages...")
for pkg in remove_pkgs:
if pkg in self.remove_white:
new_upgrade_list = list(set(remove_pkgs) & set(self.remove_white))
for pkg in new_upgrade_list:
if pkg in remove_pkgs:
logging.info("%s will be remove in remove pkg...",pkg)
remove_pkgs.remove(pkg)
@ -199,7 +206,8 @@ class InstallBackend():
#检查是否存在可升级的包
if len(pkgs_install) == 0 and len(pkgs_upgrade) == 0 and len(pkgs_remove) == 0 and len(pkgs_downgrade) == 0:
raise UpdateBaseError(ERROR_NOT_UPGRADE_PACKAGES)
pkgs_install,pkgs_upgrade = self._make_pkgs_list(self.cache,self.upgrade_data.groups_pkgs,self.now_upgrade.upgrade_groups,self.now_upgrade.single_pkgs)
logging.warning("There is an exception in the update package install = %r upgrade = %r",pkgs_install,pkgs_upgrade)
# if self.action_mode == self.MODE_INSTALL_SINGLE:
# logging.warning("MODE_INSTALL_SINGLE install:%s , upgrade:%s remove:%s",str(pkgs_install),str(pkgs_upgrade),str(pkgs_remove))
@ -227,12 +235,8 @@ class InstallBackend():
#计算依赖解决方案
elif self.action == self.ACTION_CHECK_RESOLVER:
#被删除的包列表
delete_pkgs = []
#被删除包的描述
raw_description = []
#那些包升级导致删除包 全盘升级不包含
delete_desc = []
#判断是否配置aptdaemon的限速
self.window_main.check_conifg_aptdeamon()
@ -243,16 +247,8 @@ class InstallBackend():
#获取要升级和安装的包列表
pkgs_install,pkgs_upgrade = self._make_pkgs_list(self.cache,self.upgrade_data.groups_pkgs,self.now_upgrade.upgrade_groups,self.now_upgrade.single_pkgs)
#计算解决依赖关系
delete_pkgs,delete_desc = self._make_problem_resolver(self.cache,pkgs_install,pkgs_upgrade,self.upgrade_data.adjust_pkgs)
self._make_problem_resolver(self.cache,pkgs_install,pkgs_upgrade,self.upgrade_data.adjust_pkgs)
pkgs_install,pkgs_upgrade,pkgs_remove,pkgs_downgrade = self._get_mark_from_cache(self.cache,self.upgrade_data.adjust_pkgs,self.action_mode)
if len(pkgs_remove) != len(delete_pkgs):
logging.warning("Simulation of the deletion package list:%s",str(delete_pkgs))
logging.warning("ProblemResolver of the deletion package list:%s",str(pkgs_remove))
delete_desc = []
self.update_essential.check_white(pkgs_remove)
else:
pkgs_remove = delete_pkgs
else:
# 使用全盘升级 全盘使用dist-upgrade
if self.cache.get_changes():
@ -260,10 +256,13 @@ class InstallBackend():
self.cache._depcache.upgrade(True)
pkgs_install,pkgs_upgrade,pkgs_remove,pkgs_downgrade = self._get_mark_from_cache(self.cache,self.upgrade_data.adjust_pkgs,self.action_mode)
logging.warning("ProblemResolver of the deletion package list:%s",str(pkgs_remove))
self.update_essential.check_white(pkgs_remove)
logging.info("RESOLVER install:%d , upgrade:%d remove:%d pkgs_downgrade:%d",len(pkgs_install),len(pkgs_upgrade),\
len(pkgs_remove),len(pkgs_downgrade))
is_remove_pkgs = len(pkgs_remove) != 0
# 数据上报
self.window_main.collector.Generate_Msg(self.now_upgrade.upgrade_groups+self.now_upgrade.single_pkgs, self.action_mode)
errorCode = ""
if is_remove_pkgs:
@ -271,13 +270,11 @@ class InstallBackend():
for ul in self.window_main.collector.upgrade_list:
self.window_main.collector.Upgrade_Process_Msg(self.action, {"appname":ul, "status":is_remove_pkgs, "errorCode":errorCode})
#添加关于删除包的描述信息
#补充删除包的描述信息,删除描述
delete_desc = []
for pkg in pkgs_remove:
pkg_obj = self.cache[pkg]
raw_description.append(getattr(pkg_obj.candidate, "summary", ''))
#补充删除描述
if pkgs_remove != [] and delete_desc == []:
for pkg in pkgs_remove:
delete_desc.append('')
if self.action_mode != self.MODE_INSTALL_SYSTEM:
@ -287,6 +284,10 @@ class InstallBackend():
self._action_done(self.action,False,True,'','')
if is_remove_pkgs:
threading_emulate = threading.Thread(target=self._emulate_calcul_delete,args=((pkgs_upgrade + pkgs_install),))
threading_emulate.start()
#修复未满足的依赖关系 与apt-get -f install匹配
elif self.action == self.ACTION_CHECK_BROKEN:
try:
@ -325,7 +326,7 @@ class InstallBackend():
self.fix_incomplete()
#卸载包
elif self.action == self.ACTION_REMOVE_PACKAGES:
self._start_install_lock()
self._start_install_lock(_("Kylin System Updater"))
self.purge_packages(partial_upgrade_list)
elif self.action == self.ACTION_CLEAN:
self.clean()
@ -362,6 +363,7 @@ class InstallBackend():
# 没找到包或格式不正确
self.window_main.dbusController.UpdateInstallFinished(False, pkgs_install, "'"+pkg_name+"' is not in cache", "")
return
self._start_install_lock(caller=caller)
self.commit(self.ACTION_INSTALL,pkgs_install,[],[])
except Exception as e:
logging.error(str(e))
@ -538,10 +540,6 @@ class InstallBackend():
#将获取本次升级的包 进行计算依赖关系 解决依赖问题
def _make_problem_resolver(self,cache,pkgs_install = [],pkgs_upgrade = [],adjust_pkgs = []):
last_broken_count = 0
#计算出来的需要删除的包列表
delete_pkgs = []
delete_desc = []
try:
logging.info("ProblemResolver install:%d , upgrade:%d",len(pkgs_install),len(pkgs_upgrade))
logging.info("Start calculating dependencies...")
@ -551,7 +549,7 @@ class InstallBackend():
if cache.get_changes():
cache.clear()
resolver = apt.cache.ProblemResolver(cache)
#调整候选版本强制更改版本
for pkg_name, pkg_ver, pkg_rel in [self._split_package_id(pkg)
for pkg in adjust_pkgs]:
try:
@ -561,70 +559,70 @@ class InstallBackend():
logging.warning("The version %s of %s isn't available",pkg_ver, pkg_name)
continue
#标记计算所有需要安装的
for pkg in pkgs_upgrade + pkgs_install:
pkg_cache = cache[pkg]
#将第二个参数调整为False 当为True时就不能检查缺少依赖的包 默认自动移除掉了
if pkg_cache.is_upgradable == False and pkg_cache.is_installed == True:
logging.warning("pkg(%s) not upgrade or install and will be continue...",pkg)
continue
pkg_cache.mark_install(False, True, True)
#将可自动升级的标记为自动安装
if pkg_cache.is_upgradable == True:
auto = pkg_cache.is_auto_installed
pkg_cache.mark_auto(auto)
if pkg_cache.marked_keep == True:
pkg_cache.mark_install(False, False, True)
if pkg_cache.marked_keep == True:
raise
resolver.clear(pkg_cache)
resolver.protect(pkg_cache)
#出现破损的原因有 升级一个包需要安装其他的包或者需要删除其他的软件包
if cache._depcache.broken_count != last_broken_count and \
self.window_main.configs_cover.getWithDefault("ConfigPkgStatus", "check_resover_remove", False) == True:
last_broken_count = cache._depcache.broken_count
fresh_cache = Cache()
tmp_pkgs,tmp_desc = self._emulate_calcul_delete(pkg,fresh_cache)
delete_pkgs.extend(tmp_pkgs)
delete_desc.extend(tmp_desc)
resolver.resolve()
return delete_pkgs,delete_desc
return
except Exception as e:
logging.info(str(e))
logging.error(str(e))
pkg_string = ''
for pkg in pkgs_install + pkgs_upgrade:
pkg_string = pkg_string + ' ' + str(pkg)
logging.info('Resolver calculation Packages List: '+pkg_string+'\n')
logging.error('Resolver calculation Packages List: '+pkg_string+'\n')
terminal_msg = self.window_main.simulate_mode.dependencies_broken(pkgs_install + pkgs_upgrade)
logging.error(terminal_msg)
raise UpdateBaseError(ERROR_RESOLVER_FAILED,
desc= terminal_msg)
def _emulate_calcul_delete(self,pkg,cache):
def _emulate_calcul_delete(self,total_pkg):
logging.info("[DELETE_DETAILS] Start calculating delete dependencies...")
delete_pkgs = []
last_delete_count = 0
cache = Cache()
with cache.actiongroup():
if cache.get_changes():
cache.clear()
for pkg in total_pkg:
if '#' in pkg:
pkg = pkg.split("#")[0]
elif '=' in pkg:
pkg = pkg.split("=")[0]
try:
deleted_pkgs = []
delete_desc = []
fresh_cache = cache
fresh_cache.clear()
fresh_pkg = fresh_cache[pkg]
fresh_pkg.mark_install(True,True,True)
wouldDelete = fresh_cache._depcache.del_count
if wouldDelete > 0:
for pkg_obj in cache.get_changes():
if pkg_obj.marked_delete:
deleted_pkgs.append(pkg_obj.name)
for d_pkg in deleted_pkgs:
tmp_desc = str(d_pkg) + _(" Will be deleted Due to Install or Upgrade ") + str(pkg)
delete_desc.append(tmp_desc)
logging.warning(tmp_desc)
return deleted_pkgs,delete_desc
cache[pkg].mark_install()
except Exception as e:
logging.error("Package("+pkg+") "+ str(e))
return [],[]
logging.error(str(e))
break
if cache.delete_count != last_delete_count:
last_delete_count = cache.delete_count
for pkg_obj in cache.get_changes():
if pkg_obj.marked_delete and pkg_obj.name not in delete_pkgs:
delete_pkgs.append(pkg_obj.name)
delete_pkgs.append(pkg)
logging.info("[DELETE_DETAILS] %s Will be deleted Due to Install or Upgrade %s",pkg_obj.name,pkg)
logging.info("[DELETE_DETAILS] End calculating delete dependencies...")
cache.close()
def _send_error_code(self,error_code):
if error_code == ERROR_NOT_DISK_SPACE:
@ -665,6 +663,7 @@ class InstallBackend():
#升级完成后走的分支
if action == self.ACTION_INSTALL:
false_num = 0
self._release_install_lock()
self._send_error_code(error_code)
@ -678,8 +677,10 @@ class InstallBackend():
self.window_main.start_install(self.action_mode,True,self.now_upgrade.upgrade_content)
self.window_main.retry_limit = self.window_main.retry_limit - 1
return
try:
false_num = self._make_insert_info(success,is_cancelled,self.now_upgrade,error_string,error_desc)
except Exception as e:
logging.error(e)
if success == False:
logging.info("The number of failed installations or upgrades is %d",false_num)
@ -688,7 +689,7 @@ class InstallBackend():
#这个 为True的很低 大多数为False 只有当系统中apt 出现问题时 才会复现这种问题
if success == False and false_num == 0 and self.now_upgrade.upgrade_content != []:
logging.warning("Special Case switch success status from False to True...")
success = True
# success = True
if success:
#当组列表为空时 表示现在的单独进行安装某些包或卸载,不发信号到控制面板
@ -777,6 +778,8 @@ class InstallBackend():
error_desc = get_error_description_from_enum(ERROR_UPDATE_NET_AUTHENTICATION)
elif ERROR_UPDATE_NOTREAD_SOURCES in self.aptd_base.error_details:
error_desc = get_error_description_from_enum(ERROR_UPDATE_NOTREAD_SOURCES)
elif ERROR_UPDATE_INVALID_TIME in self.aptd_base.error_details:
error_desc = get_error_description_from_enum(ERROR_UPDATE_INVALID_TIME)
if success:
#开始生成列表
@ -929,7 +932,7 @@ class InstallBackend():
#判断是否是源过滤调整的包 调整的话 判断安装版本 来解决是否安装成功
if pkg in adjust_pkgs:
if pkg_obj.is_installed == True and pkg_obj.is_now_broken == False and pkg_obj.name + '=' + pkg_obj.installed.source_version in self.upgrade_data.adjust_pkgs:
if pkg_obj._pkg.inst_state == apt_pkg.INSTSTATE_OK and pkg_obj._pkg.current_state == apt_pkg.CURSTATE_INSTALLED and pkg_obj.name + '=' + pkg_obj.installed.source_version in self.upgrade_data.adjust_pkgs:
self.window_main.sqlite3_server.insert_info(self.action_mode,[pkg],[],self.upgrade_data.adjust_pkgs,True,'', '')
else:
false_num += 1
@ -937,7 +940,7 @@ class InstallBackend():
self.window_main.sqlite3_server.insert_info(self.action_mode,[pkg],[],self.upgrade_data.adjust_pkgs,False,error_string, error_desc)
else:
#非调整版本的计算方式
if pkg_obj.is_installed == True and pkg_obj.is_upgradable == False and pkg_obj.is_now_broken == False:
if pkg_obj._pkg.inst_state == apt_pkg.INSTSTATE_OK and pkg_obj._pkg.current_state == apt_pkg.CURSTATE_INSTALLED and pkg_obj.is_now_broken == False:
self.window_main.sqlite3_server.insert_info(self.action_mode,[pkg],[],self.upgrade_data.adjust_pkgs,True,'', '')
else:
false_num += 1
@ -947,11 +950,10 @@ class InstallBackend():
#组的计算是否升级成功的方式 将组按照单包来计算的
if _now_upgrade.upgrade_groups != []:
pkgs_install,pkgs_upgrade = self._make_pkgs_list(self.cache,self.upgrade_data.groups_pkgs,_now_upgrade.upgrade_groups,[])
# group_error_log = ''
install_error_pkgs = []
total_pkg = pkgs_install + pkgs_upgrade
for pkg in pkgs_install + pkgs_upgrade:
for pkg in total_pkg[::-1]:
pkg_obj = fresh_cache[pkg]
if pkg in adjust_pkgs:
if pkg_obj.is_installed == True and pkg_obj.is_now_broken == False and pkg_obj.installed.source_version + pkg_obj.name in self.upgrade_data.adjust_pkgs:
@ -959,7 +961,7 @@ class InstallBackend():
else:
install_error_pkgs.append(pkg)
else:
if pkg_obj.is_installed == True and pkg_obj.is_upgradable == False and pkg_obj.is_now_broken == False:
if pkg_obj._pkg.inst_state == apt_pkg.INSTSTATE_OK and pkg_obj._pkg.current_state == apt_pkg.CURSTATE_INSTALLED and pkg_obj.is_now_broken == False:
total_pkg.remove(pkg)
else:
install_error_pkgs.append(pkg)
@ -1080,9 +1082,13 @@ def get_backend(*args, **kwargs):
"aptdaemon or synaptic")
class InhibitShutdownLock():
# 禁止关机锁文件路径
FILELOCK_PATH = "/tmp/lock/"
SHUTDOWN_BLOCK_FILELOCK = "kylin-update.lock"
def __init__(self):
self.inhibit_lock = None
self.pidfile = None
#安装时禁止关机 进行加锁
def lock(self, caller='Kylin System Updater'):
@ -1103,6 +1109,8 @@ class InhibitShutdownLock():
'block')),
None, 0, -1, None, None)
self.inhibit_lock = Gio.UnixInputStream(fd=fdlist.steal_fds()[var[0]])
self.LockedPreventShutdown()
logging.info("Shutdown Has been locked...")
except Exception as e:
logging.error(e)
@ -1110,6 +1118,7 @@ class InhibitShutdownLock():
#解锁禁止关机
def unlock(self):
try:
self.unLockedEnableShutdown()
if self.inhibit_lock != None:
self.inhibit_lock.close()
self.inhibit_lock == None
@ -1118,3 +1127,58 @@ class InhibitShutdownLock():
logging.info("Not locked and Quitting ...")
except Exception as e:
logging.error("unlock failed." + str(e))
#安装时禁止关机 进行加锁
def LockedPreventShutdown(self):
#不为空是表示以及被锁
if self.pidfile != None:
logging.error("self.pidfile file disc not is None,Has been locked...")
return False
if not os.path.exists(self.FILELOCK_PATH):
#不存在创建
logging.info("File(%s) is not exists and will be create",self.FILELOCK_PATH)
os.makedirs(self.FILELOCK_PATH)
else:
#当目录存在时进行删除 不删除进行创建文件的话会报错
# file cannot be locked.[Errno 11] Resource temporarily unavailable
# 资源被占用报错
shutil.rmtree(self.FILELOCK_PATH)
logging.info("File(%s) is exists and will be delete and create",self.FILELOCK_PATH)
os.makedirs(self.FILELOCK_PATH)
try:
self.pidfile = open(os.path.join(self.FILELOCK_PATH, self.SHUTDOWN_BLOCK_FILELOCK), "w+")
fcntl.flock(self.pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
return True
except Exception as e:
logging.error("file cannot be locked." + str(e))
self.pidfile.close()
self.pidfile = None
return False
#解锁禁止关机
def unLockedEnableShutdown(self):
#未加锁退出
if not self.pidfile:
logging.info("Not locked and Quitting ...")
return False
try:
fcntl.flock(self.pidfile, fcntl.LOCK_UN)
self.pidfile.close()
self.pidfile = None
# Fix 修复权限问题 当普通用户无法使用 所以直接删除目录
if os.path.exists(self.FILELOCK_PATH):
shutil.rmtree(self.FILELOCK_PATH)
logging.info('Emptying the lockPath(%s) is complete...',self.FILELOCK_PATH)
else:
logging.info("Emptying the lockPath(%s) is Failed...",self.FILELOCK_PATH)
return True
except Exception as e:
logging.error("unlock failed." + str(e))
self.pidfile.close()
self.pidfile = None
return False

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
"-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1.0/policyconfig.dtd">
<policyconfig>
<vendor>Kylin System Updater Config Manager</vendor>
<vendor_url>www.kylinos.cn</vendor_url>
<icon_name>kylin-upgrade-strategies</icon_name>
<action id="com.kylin.UpgradeStrategies.action">
<_description>
system level settings
</_description>
<_message>
To Change the settings, you need to authenticate.
</_message>
<defaults>
<allow_any>auth_admin_keep</allow_any>
<allow_inactive>auth_admin_keep</allow_inactive>
<allow_active>auth_admin_keep</allow_active>
</defaults>
</action>
</policyconfig>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?> <!-- -*- XML -*- -->
<!DOCTYPE busconfig PUBLIC
"-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<!-- Only root can own the service -->
<policy user="root">
<allow own="com.kylin.UpgradeStrategies"/>
<allow send_interface="com.kylin.UpgradeStrategies.interface"/>
</policy>
<!-- Allow anyone to invoke methods on the interfaces -->
<policy context="default">
<allow send_destination="com.kylin.UpgradeStrategies"
send_interface="com.kylin.UpgradeStrategies.interface"/>
<allow send_destination="com.kylin.UpgradeStrategies"
send_interface="org.freedesktop.DBus.Introspectable"/>
<allow send_destination="com.kylin.UpgradeStrategies"
send_interface="org.freedesktop.DBus.Properties"/>
</policy>
</busconfig>

View File

@ -0,0 +1,4 @@
[D-BUS Service]
Name=com.kylin.UpgradeStrategies
Exec=/bin/python3 /usr/share/kylin-system-updater/kylin-upgrade-strategies -r -d
User=root

View File

@ -0,0 +1,14 @@
[whitelist]
key1 = /usr/bin/kylin-background-upgrade
key2 = /usr/bin/ukui-control-center
key3 = /usr/bin/kylin-installer
key4 = /usr/bin/kylin-uninstaller
key5 = /usr/bin/kylin-software-properties-service
key6 = /usr/bin/kylin-source-update
key7 = /usr/bin/kylin-source-manager
key8 = /usr/bin/kylin-unattended-upgrade
key9 = /usr/bin/kylin-software-center
key10 = /usr/bin/kylin-printer
key11 = /usr/bin/kylin-printer-applet
key12 = /usr/bin/hedron-client
key13 = /usr/bin/kylin-software-center-plugin-synchrodata

View File

@ -0,0 +1,10 @@
/var/log/kylin-system-updater/kylin-system-updater.log.1
{
weekly
missingok
rotate 3
compress
notifempty
minsize 10M
copytruncate
}

Binary file not shown.

View File

@ -0,0 +1,3 @@
[SYSTEM]
os_version =
update_version =

View File

@ -1,3 +1,4 @@
#此配置文件内的所有配置项,在新装时都会被替换掉
[SystemStatusCover]
close_source_filter = False
priority_upgrade_restart = True

View File

@ -1,6 +1,30 @@
[autoUpgradePolicy]
preDownload = off
#自动更新的开关
autoUpgradeState = off
#预下载开关
preDownload = off
# 预下载的时间为时间段 例如10:00-11:00
preDownloadTime = 10:00
#添加检查更新的周期 以天为单位
updateDays = 1
# timing 为定时下载 manaual手动下载
downloadMode = timing
# 下载的时间为时间段 例如10:00-11:00
downloadTime = 10:00
#安装存在定时timing 手动:manual 关机安装bshutdown
installMode = timing
#安装也为时间段 例如00:00
installTime = 10:00
#是否开启自动重启 以及自动重启时间可以调节
automaticReboot = off
#自动重启时间的调节 now为立即重启 重启时间调节 例如00:00
automaticRebootTime = now

0
backend/interface.md Executable file → Normal file
View File

View File

@ -83,7 +83,7 @@ if __name__ == "__main__":
signal.signal(signal.SIGINT,signal_handler_term)
if options.debug:
logging.basicConfig(format=FORMAT,level=logging.DEBUG,datefmt='%m-%d,%H:%M:%S')
logging.basicConfig(format=FORMAT,level=logging.INFO,datefmt='%m-%d,%H:%M:%S')
else:
logging.basicConfig(format=FORMAT,level=logging.DEBUG,datefmt='%m-%d,%H:%M:%S',filename = logfile(),filemode = 'a')

View File

@ -0,0 +1,81 @@
#!/usr/bin/python3
from SystemUpdater.UpgradeStrategies import UpgradeStrategies
from gettext import gettext as _
import logging
from optparse import OptionParser
import dbus
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
import signal
import os
import sys
import gettext
from SystemUpdater.Core.LogManager import upgrade_strategies_logfile as logfile
gettext.bindtextdomain('kylin-system-updater', '/usr/share/locale')
gettext.textdomain('kylin-system-updater')
_ = gettext.gettext
#定义日志的格式
FORMAT = "%(asctime)s [%(levelname)s]: %(message)s"
FORMAT_DEBUG = '%(asctime)-15s %(levelname)s(%(filename)s:%(lineno)d):%(message)s'
def signal_handler_term(signal, frame):
# type: (int, object) -> None
logging.warning("SIGTERM received, will stop")
app.dbusController.Quit(None)
if __name__ == "__main__":
# Begin parsing of options
parser = OptionParser()
parser.add_option ("-d", "--debug", action="store_true", default=False,
help=_("Show debug messages"))
parser.add_option("-r", "--replace",
default=False,
action="store_true", dest="replace",
help=_("Quit and replace an already running "
"daemon"))
(options, args) = parser.parse_args()
if os.getuid() != 0:
print(_("You need to be root to run this application"))
sys.exit(1)
# set debconf to NON_INTERACTIVE
os.environ["DEBIAN_FRONTEND"] = "noninteractive"
os.environ["TERM"] = "xterm"
os.environ["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
#当不存在语言变量时 默认显示中文
if not "LANGUAGE" in os.environ:
os.environ["LANGUAGE"] = "zh_CN.UTF-8"
#当不存在语言变量时 默认显示中文
if not "LANG" in os.environ:
os.environ["LANG"] = "zh_CN.UTF-8"
#做一些规范处理
if os.environ["LANGUAGE"] == "en":
os.environ["LANGUAGE"] = "en_US.UTF-8"
if os.environ["LANGUAGE"] == "zh_CN:en" or os.environ["LANGUAGE"] == "zh_CN:zh":
os.environ["LANGUAGE"] = "zh_CN.UTF-8"
# ensure that we are not killed when the terminal goes away e.g. on
# shutdown
signal.signal(signal.SIGHUP, signal.SIG_IGN)
signal.signal(signal.SIGINT,signal_handler_term)
if options.debug:
logging.basicConfig(format=FORMAT,level=logging.INFO,datefmt='%m-%d,%H:%M:%S')
else:
logging.basicConfig(format=FORMAT,level=logging.DEBUG,datefmt='%m-%d,%H:%M:%S',filename = logfile(),filemode = 'a')
logging.info('Updater Config Manager Daemon(LANGUAGE:%s LANG:%s) starting ...',os.environ["LANGUAGE"],os.environ["LANG"])
app = UpgradeStrategies(options)
app.run()

View File

@ -2590,7 +2590,7 @@ msgstr "本次更新无法检测到可升级的软件包。"
msgid "read important list failed"
msgstr "无法读取推送升级列表,请稍后再试"
msgid "Group configuration being updated"
msgid "Priority Upgrade Package being updated"
msgstr "正在更新分组配置"
msgid "Exceptions of Priority Upgrade."
@ -2665,8 +2665,8 @@ msgstr "检查网络连接中"
msgid "Updating Source Template"
msgstr "更新源模板中"
msgid "Update Manager upgrade is complete, please restart the control panel before performing the system update"
msgstr "更新管理器升级完成,请重启设置-更新后再进行系统更新"
msgid "Update Manager upgrade is complete, please restart the setting panel before performing the system update."
msgstr "更新管理器升级完成,请重启设置-更新后再进行系统更新"
msgid "Uninstallation completed"
msgstr "卸载完成。"
@ -2752,3 +2752,9 @@ msgstr "安装软件包失败。"
msgid "Upgrade System"
msgstr "全盘升级"
msgid "kylin-unattended-upgrade"
msgstr "自动更新"
msgid "Please check the system time and synchronize the system time before updating."
msgstr "请检查系统时间,同步系统时间后再进行更新。"

View File

@ -2523,3 +2523,171 @@ msgstr "因 grub 已安裝,移除 lilo (詳情見 bug #314004"
#~ "Fetching and installing the upgrade can take several hours. Once the "
#~ "download has finished, the process cannot be cancelled."
#~ msgstr "提取檔案及安裝升級可能要花數小時。一旦下載完成即不能取消升級程序。"
msgid "Unable to access the source management server"
msgstr "無法存取來源管理伺服器,請稍後再試"
msgid "Check if your network requires authentication?"
msgstr "檢查您的網路需要認證嗎?"
msgid "Check your source public key signature"
msgstr "檢查您的源數字簽名"
msgid "update important list occur Exception"
msgstr "獲取推送出現異常,請稍後再試"
msgid "You need to be root to run this application"
msgstr "你需要root許可權運行"
msgid "There is an exception in the update package."
msgstr "更新包存在異常!"
msgid "You request the removal of a system-essential package."
msgstr "您要求刪除系統必要的套件。"
msgid "This update cannot detect the upgradeable package."
msgstr "本次更新無法檢測到可升級的軟體包。"
msgid "read important list failed"
msgstr "無法讀取推送升級清單,請稍後再試"
msgid "Priority Upgrade Package being updated"
msgstr "正在更新分組配置"
msgid "Exceptions of Priority Upgrade."
msgstr "優先升級異常"
msgid "Due to the presence of deleted packages."
msgstr "由於存在刪除的套件"
msgid "The system update configuration file is read abnormally, please check if the system update configuration file format is correct."
msgstr "讀取系統更新設定檔異常,請檢查系統更新配置檔格式是否正確。"
msgid "Installation progress: "
msgstr "安裝進度: "
msgid "Installation successful, about to shut down"
msgstr "安裝成功,即將關機"
msgid "Installation failed, about to shut down"
msgstr "安裝失敗,即將關機"
msgid "groups JSON ConfigPkgs install failed"
msgstr "無法安裝分組配置檔"
msgid "Installtion timeout to exit Due to inactivity"
msgstr "安裝超時退出由於"
msgid "Command execution error"
msgstr "命令執行報錯"
msgid "Unsupported architecture"
msgstr "架構不符合"
msgid "Other Error"
msgstr "其他錯誤"
msgid "dependency is not satisfied"
msgstr "依賴關係不滿足"
msgid "dependency is not satisfied will download"
msgstr "依賴關係不滿足"
msgid "Disk space is insufficient, please clean the disk and then upgrade"
msgstr "磁碟空間不足,請清理磁碟後進行升級更新。"
msgid "Network anomaly, can't check for updates!"
msgstr "網路異常,無法檢查更新!"
msgid "Check for update exceptions!"
msgstr "檢查更新異常!"
msgid "Check for update exceptions,fix system APT environment error."
msgstr "檢查更新異常修復系統APT環境出現錯誤。"
msgid "The system APT environment is abnormal, please check the system APT environment."
msgstr "修復系統APT環境異常請檢查系統APT環境。"
msgid "Priority upgrade status exception."
msgstr "優先升級狀態異常。"
msgid "Upgrade configuration acquisition exception."
msgstr "升級配置獲取異常。"
msgid "Please check your network connection and retry."
msgstr "請檢查您的網路連接后再試。"
msgid "Please check your source list and retry."
msgstr "請檢查您的源清單後再試。"
msgid "Checking network connection"
msgstr "檢查網路連接中"
msgid "Updating Source Template"
msgstr "更新源範本中"
msgid "Update Manager upgrade is complete, please restart the setting panel before performing the system update."
msgstr "更新管理器升級完成,請重啟設置-更新后再進行系統更新。"
msgid "Uninstallation completed"
msgstr "卸載完成。"
msgid "Package validation failed and installation was rejected."
msgstr "套件驗證失敗,拒絕安裝。"
msgid "Other tasks are being updated and upgraded, please uninstall them later."
msgstr "其他任務正在更新升級中,請稍後再卸載。"
#: ../SystemUpdater/Core/enums.py:763
msgid "Kylin System Updater"
msgstr "麒麟更新器"
#: ../SystemUpdater/Core/enums.py:609
msgid "Kylin Installer"
msgstr "麒麟安裝器"
#: ../SystemUpdater/Core/enums.py:610
msgid "Kylin Uninstaller"
msgstr "麒麟卸載器"
#: ../SystemUpdater/Core/enums.py:611
msgid "Kylin Background Upgrade"
msgstr "靜默更新"
#: ../SystemUpdater/Core/enums.py:612
msgid "Kylin Software Center"
msgstr "軟體商店"
#: ../SystemUpdater/UpdateManagerDbus.py:355
msgid " requires authentication to uninstall software packages."
msgstr "卸載套件需要認證。"
#: ../SystemUpdater/UpdateManager.py:463
msgid " requires authentication to install software packages."
msgstr "安裝套件需要認證。"
#: ../SystemUpdater/Core/utils.py:750
msgid "Authentication success."
msgstr "認證成功。"
#: ../SystemUpdater/Core/utils.py:753
msgid "Authentication failure."
msgstr "認證失敗。"
#: ../SystemUpdater/Core/enums.py:101
msgid "Deb format exception, read local deb file error."
msgstr "軟體包格式異常,讀取失敗。"
#: ../SystemUpdater/Core/enums.py:102
msgid "Install deb error."
msgstr "安裝套件失敗。"
msgid "Upgrade System"
msgstr "全盤升級"
msgid "kylin-unattended-upgrade"
msgstr "自動更新"
msgid "Please check the system time and synchronize the system time before updating."
msgstr "請檢查系統時間,同步系統時間后再進行更新。"

View File

@ -2555,3 +2555,171 @@ msgstr "因已安裝 grub移除 lilo。詳情見 bug #314004。"
#~ msgstr ""
#~ "自從這個 Ubuntu 版本發行後已經發布這些軟體更新。如果您現在還不想安裝它們,"
#~ "請稍後從「管理」選單選擇「更新管理員」。"
msgid "Unable to access the source management server"
msgstr "無法存取來源管理伺服器,請稍後再試"
msgid "Check if your network requires authentication?"
msgstr "檢查您的網路需要認證嗎?"
msgid "Check your source public key signature"
msgstr "檢查您的源數字簽名"
msgid "update important list occur Exception"
msgstr "獲取推送出現異常,請稍後再試"
msgid "You need to be root to run this application"
msgstr "你需要root許可權運行"
msgid "There is an exception in the update package."
msgstr "更新包存在異常!"
msgid "You request the removal of a system-essential package."
msgstr "您要求刪除系統必要的套件。"
msgid "This update cannot detect the upgradeable package."
msgstr "本次更新無法檢測到可升級的軟體包。"
msgid "read important list failed"
msgstr "無法讀取推送升級清單,請稍後再試"
msgid "Priority Upgrade Package being updated"
msgstr "正在更新分組配置"
msgid "Exceptions of Priority Upgrade."
msgstr "優先升級異常"
msgid "Due to the presence of deleted packages."
msgstr "由於存在刪除的套件"
msgid "The system update configuration file is read abnormally, please check if the system update configuration file format is correct."
msgstr "讀取系統更新設定檔異常,請檢查系統更新配置檔格式是否正確。"
msgid "Installation progress: "
msgstr "安裝進度: "
msgid "Installation successful, about to shut down"
msgstr "安裝成功,即將關機"
msgid "Installation failed, about to shut down"
msgstr "安裝失敗,即將關機"
msgid "groups JSON ConfigPkgs install failed"
msgstr "無法安裝分組配置檔"
msgid "Installtion timeout to exit Due to inactivity"
msgstr "安裝超時退出由於"
msgid "Command execution error"
msgstr "命令執行報錯"
msgid "Unsupported architecture"
msgstr "架構不符合"
msgid "Other Error"
msgstr "其他錯誤"
msgid "dependency is not satisfied"
msgstr "依賴關係不滿足"
msgid "dependency is not satisfied will download"
msgstr "依賴關係不滿足"
msgid "Disk space is insufficient, please clean the disk and then upgrade"
msgstr "磁碟空間不足,請清理磁碟後進行升級更新。"
msgid "Network anomaly, can't check for updates!"
msgstr "網路異常,無法檢查更新!"
msgid "Check for update exceptions!"
msgstr "檢查更新異常!"
msgid "Check for update exceptions,fix system APT environment error."
msgstr "檢查更新異常修復系統APT環境出現錯誤。"
msgid "The system APT environment is abnormal, please check the system APT environment."
msgstr "修復系統APT環境異常請檢查系統APT環境。"
msgid "Priority upgrade status exception."
msgstr "優先升級狀態異常。"
msgid "Upgrade configuration acquisition exception."
msgstr "升級配置獲取異常。"
msgid "Please check your network connection and retry."
msgstr "請檢查您的網路連接后再試。"
msgid "Please check your source list and retry."
msgstr "請檢查您的源清單後再試。"
msgid "Checking network connection"
msgstr "檢查網路連接中"
msgid "Updating Source Template"
msgstr "更新源範本中"
msgid "Update Manager upgrade is complete, please restart the setting panel before performing the system update."
msgstr "更新管理器升級完成,請重啟設置-更新后再進行系統更新。"
msgid "Uninstallation completed"
msgstr "卸載完成。"
msgid "Package validation failed and installation was rejected."
msgstr "套件驗證失敗,拒絕安裝。"
msgid "Other tasks are being updated and upgraded, please uninstall them later."
msgstr "其他任務正在更新升級中,請稍後再卸載。"
#: ../SystemUpdater/Core/enums.py:763
msgid "Kylin System Updater"
msgstr "麒麟更新器"
#: ../SystemUpdater/Core/enums.py:609
msgid "Kylin Installer"
msgstr "麒麟安裝器"
#: ../SystemUpdater/Core/enums.py:610
msgid "Kylin Uninstaller"
msgstr "麒麟卸載器"
#: ../SystemUpdater/Core/enums.py:611
msgid "Kylin Background Upgrade"
msgstr "靜默更新"
#: ../SystemUpdater/Core/enums.py:612
msgid "Kylin Software Center"
msgstr "軟體商店"
#: ../SystemUpdater/UpdateManagerDbus.py:355
msgid " requires authentication to uninstall software packages."
msgstr "卸載套件需要認證。"
#: ../SystemUpdater/UpdateManager.py:463
msgid " requires authentication to install software packages."
msgstr "安裝套件需要認證。"
#: ../SystemUpdater/Core/utils.py:750
msgid "Authentication success."
msgstr "認證成功。"
#: ../SystemUpdater/Core/utils.py:753
msgid "Authentication failure."
msgstr "認證失敗。"
#: ../SystemUpdater/Core/enums.py:101
msgid "Deb format exception, read local deb file error."
msgstr "軟體包格式異常,讀取失敗。"
#: ../SystemUpdater/Core/enums.py:102
msgid "Install deb error."
msgstr "安裝套件失敗。"
msgid "Upgrade System"
msgstr "全盤升級"
msgid "kylin-unattended-upgrade"
msgstr "自動更新"
msgid "Please check the system time and synchronize the system time before updating."
msgstr "請檢查系統時間,同步系統時間后再進行更新。"

View File

@ -8,35 +8,21 @@ mkdir updaterlog
date >> updaterlog/base-info
dpkg -l | grep kylin-system-updater >> updaterlog/base-info
dpkg -l | grep ukui-control-center >> updaterlog/base-info
dpkg -l | grep kylin-update-manager >> updaterlog/base-info
dpkg -l | grep apt-p2p >> updaterlog/base-info
dpkg -l | grep aptdaemon >> updaterlog/base-info
echo $1 >> updaterlog/base-info
echo "记录BUG产生时间系统当前时间以及升级相关的版本信息"
cat updaterlog/base-info
cp /etc/apt/sources.list updaterlog || true
cp -r /etc/apt/sources.list.d/ updaterlog || true
cp -r /etc/apt/apt.conf.d/ updaterlog || true
cp -r /usr/share/kylin-update-desktop-config/config/ updaterlog || true
#复制后端的日志
cp -r /var/log/kylin-system-updater/ updaterlog || true
#复制旧版后端
cp -r /var/log/kylin-update-manager/ updaterlog || true
#收集apt的日志
cp -r /var/log/apt/ updaterlog || true
cp -r /var/log/apt/term.log updaterlog || true
#收集dpkg日志
cp /var/log/dpkg.log updaterlog || true
#收集aptdamon的日志
cp /var/log/syslog updaterlog || true
#收集aptdamon的日志
cp /var/log/apt-p2p.log updaterlog || true
cp -r /var/log/apt/history.log updaterlog || true
#收集aptdamon的日志
cp -r /var/log/kylin-unattended-upgrades/ updaterlog || true

View File

@ -1,11 +1,15 @@
[build_i18n]
domain=kylin-system-updater
# xml_files=[("share/metainfo/",
# ("data/update-manager.appdata.xml.in",)),
# ]
[sdist]
formats = bztar
[nosetests]
match=test
[install]
skip-build=0
# [install]
# skip-build=0

View File

@ -1,53 +1,21 @@
#!/usr/bin/env python3
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4; coding: utf-8 -*-
import os
import glob
from distutils.core import setup
from subprocess import check_output
from DistUtilsExtra.command import (
build_extra, build_i18n, build_help)
disabled = []
def plugins():
return []
return [os.path.join('janitor/plugincore/plugins', name)
for name in os.listdir('janitor/plugincore/plugins')
if name.endswith('_plugin.py') and name not in disabled]
#for line in check_output('dpkg-parsechangelog --format rfc822'.split(),
# universal_newlines=True).splitlines():
# header, colon, value = line.lower().partition(':')
# if header == 'version':
# version = value.strip()
# break
#else:
# raise RuntimeError('No version found in debian/changelog')
class CustomBuild(build_extra.build_extra):
def run(self):
# with open("SystemUpdater/UpdateManagerVersion.py", "w") as f:
# f.write("VERSION = '%s'\n" % version)
build_extra.build_extra.run(self)
setup(name='kylin-system-updater',
# version=version,
packages=['SystemUpdater',
setup(
packages=[ 'SystemUpdater',
'SystemUpdater.backend',
'SystemUpdater.Core',],
scripts=['kylin-system-updater'],
data_files=[('share/man/man8',
glob.glob('data/*.8')),
'SystemUpdater.Core'
],
cmdclass={"build": CustomBuild,
"build_i18n": build_i18n.build_i18n,
"build_help": build_help.build_help}
)
cmdclass={ "build": CustomBuild,
"build_i18n": build_i18n.build_i18n
# "build_help": build_help.build_help
}
)

83
debian/changelog vendored
View File

@ -1,11 +1,88 @@
kylin-system-updater (2.0.5.5.1) v101; urgency=medium
kylin-system-updater (2.0.5.13) v101; urgency=medium
* BUG: #120948 【在线更新】断网时检测更新失败的文案何设计图不符
* BUG: #141330 【在线更新】0521系统在线升级到2203-update1时提示依赖冲突
* 需求号: 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Mon, 17 Oct 2022 11:25:38 +0800
kylin-system-updater (2.0.5.12) v101; urgency=medium
* BUG: #141197 【在线更新】更新升级安装软件包过程中点击电源后还可以正常关机重启、
#141309 【在线更新】自动更新失败
#142560 【2203自适应升级2209】用命令升级完成后控制面板-关于界面的版本号和系统补丁版本号均为2203
#143275 【2203自适应升级2209】使用自动更新下载安装命令升级成功后控制面板-更新界面依然能检测出“系统更新”和“系统基础组件”
#143274 【2203自适应升级2209】使用自动更新下载安装命令升级成功后开始菜单缺少部分软件
* 需求号: 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Thu, 13 Oct 2022 17:39:44 +0800
kylin-system-updater (2.0.5.11) v101; urgency=medium
* BUG: #140451 【2203自适应升级2209】自动更新下载报错
#139133 【需求12242】【软件商店客户端】软件卸载后未自动清除卸载后的残留
* 需求号: 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Fri, 16 Sep 2022 17:57:01 +0800
kylin-system-updater (2.0.5.10) v101; urgency=medium
* BUG: #138243 修复优先升级,安装的部分检查出计算依赖错误
* 需求号: 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Fri, 09 Sep 2022 11:17:10 +0800
kylin-system-updater (2.0.5.9) v101; urgency=medium
* BUG: #138243 修复优先升级,安装的部分检查出计算依赖错误
* 需求号: 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Fri, 09 Sep 2022 09:17:10 +0800
kylin-system-updater (2.0.5.8) v101; urgency=medium
* BUG: #135190【2203自适应升级2209】系统更新自动下载和安装内核未更新
#136765 【离线更新】使用U盘源时控制面板-更新中,“有更新应用时通知”打开无效果
* 需求号: 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Fri, 02 Sep 2022 11:36:58 +0800
kylin-system-updater (2.0.5.7) v101; urgency=medium
* BUG: #126438 【reopen】【安装器】中文环境下安装失败或者未授权的错误日志信息显示为英文
#134470 【设计】安装失败日志语言显示异常
#127975 【reopen】【云桌面】【在线更新】累计更新成功后系统版本号以及补丁包版本号未发生变化
#135020 【在线更新】【PTOF】更新成功后系统版本号以及补丁包版本号不会变化
#136748 【在线更新】从安装器安装和更新软件后,本地日志未记录数据,未进行上传。
* 需求号: # 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Thu, 04 Aug 2022 09:28:58 +0800
-- luoxueyi <luoxueyi@kylinos.cn> Tue, 30 Aug 2022 09:46:29 +0800
kylin-system-updater (2.0.5.6) v101; urgency=medium
* BUG: #135270【解决方案|更新升级V1.6】【系统更新客户端】客户端进行自动更新,更新失败后,查看更新历史,历史内容显示为空
#135227 【解决方案|更新升级V1.6】【更新升级】未连接网络时,更新界面显示“检查更新异常!”,悬浮提示为“无法访问源管理服务器,请稍后再试”
#136093 【解决方案|更新升级V1.6】【更新升级】使用安装器安装deb包旧的服务没有收集到数据
#135372 【解决方案|更新升级V1.6】【系统更新客户端】客户端进行自动更新,更新后,查看更新历史分组名称显示了包名,应该显示软件名称
#120948 【在线更新】断网时检测更新失败的文案何设计图不符
* 需求号: # 无
* 其他改动说明: 无
* 其他改动影响域:系统更新
-- luoxueyi <luoxueyi@kylinos.cn> Wed, 24 Aug 2022 17:56:46 +0800
kylin-system-updater (2.0.5.5) v101; urgency=medium

View File

@ -4,6 +4,7 @@ backend/data/kylin-system-updater.db /usr/share/kylin-system-updater/
backend/report-updater-bug /usr/bin
backend/data/30kylin-system-updater /etc/apt/apt.conf.d/
backend/data/com.kylin.systemupgrade.conf /etc/dbus-1/system.d/
#backend/data/com.kylin.systemupgrade.limit /etc/dbus-1/conf/
backend/data/kylin-system-updater.service /usr/lib/systemd/system/
backend/data/kylin-logout-required /usr/share/kylin-system-updater/
backend/data/kylin-reboot-required /usr/share/kylin-system-updater/
@ -17,6 +18,14 @@ backend/data/system-updater-coverable.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/kylin-system-version.conf /etc/kylin-version/
#configDaemon
backend/kylin-upgrade-strategies /usr/share/kylin-system-updater/
backend/data/com.kylin.UpgradeStrategies.conf /etc/dbus-1/system.d/
backend/data/com.kylin.UpgradeStrategies.service /usr/share/dbus-1/system-services/
backend/data/cn.kylinos.UpgradeStrategies.policy /usr/share/polkit-1/actions/
backend/data/kylin-system-updater /etc/logrotate.d
#uu
unattended-upgrades/*.service /lib/systemd/system/

1
debian/postinst vendored
View File

@ -20,4 +20,5 @@ if [ -f /usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py ];th
/usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -t=tid_search
/usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -u status_cn=
/usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -u changelog=
/usr/share/kylin-system-updater/SystemUpdater/Core/DataMigration.py -f init_version="yes"
fi