@@ -15,6 +15,7 @@ import (
1515 "errors"
1616 "fmt"
1717 "io"
18+ "io/ioutil"
1819 "net/http"
1920 "net/url"
2021 "os"
@@ -40,6 +41,23 @@ import (
4041
4142var logger = log .NewLogger ("lastore/messageReport" )
4243
44+ type ProcessEvent struct {
45+ TaskID int `json:"taskID"`
46+ EventType int `json:"eventType"`
47+ EventStatus bool `json:"eventStatus"`
48+ EventContent string `json:"eventContent"`
49+ }
50+
51+ const (
52+ CheckEnv int = 1
53+ GetUpdateEvent int = 2
54+ StartDownload int = 3
55+ DownloadComplete int = 4
56+ StartBackUp int = 5
57+ BackUpComplete int = 6
58+ StartInstall int = 7
59+ )
60+
4361type ShellCheck struct {
4462 Name string `json:"name"` //检查脚本的名字
4563 Shell string `json:"shell"` //检查脚本的内容
@@ -64,6 +82,7 @@ type UpdatePlatformManager struct {
6482 checkTime string // 基线检查时间
6583 systemTypeFromPlatform string // 从更新平台获取的系统类型,本地os-baseline.b获取
6684 requestUrl string // 更新平台请求地址
85+ taskID int
6786
6887 PreCheck []ShellCheck // 更新前检查脚本
6988 MidCheck []ShellCheck // 更新后检查脚本
@@ -91,6 +110,7 @@ type UpdatePlatformManager struct {
91110
92111 jobPostMsgMap map [string ]* UpgradePostMsg
93112 jobPostMsgMapMu sync.Mutex
113+ TimerHasChanged bool
94114 inhibitAutoQuit func ()
95115 UnInhibitAutoQuit func ()
96116}
@@ -110,6 +130,7 @@ const (
110130 cacheBaseline = "/var/lib/lastore/os-baseline.b"
111131 realBaseline = "/etc/os-baseline"
112132 realVersion = "/etc/os-version"
133+ cacheTaskInfo = "/var/lib/lastore/os-task-info"
113134
114135 KeyNow string = "now" // 立即更新
115136 KeyShutdown string = "shutdown" // 关机更新
@@ -137,7 +158,7 @@ func NewUpdatePlatformManager(c *Config, updateToken bool) *UpdatePlatformManage
137158 }
138159 var token string
139160 if updateToken {
140- token = UpdateTokenConfigFile (c .IncludeDiskInfo ) // update source时生成即可,初始化时由于授权服务返回SN非常慢(超过25s),因此不在初始化时生成
161+ token = UpdateTokenConfigFile (c .IncludeDiskInfo , c . GetHardwareIdByHelper ) // update source时生成即可,初始化时由于授权服务返回SN非常慢(超过25s),因此不在初始化时生成
141162 }
142163 cache := platformCacheContent {}
143164 if strings .TrimSpace (c .OnlineCache ) != "" {
@@ -154,6 +175,7 @@ func NewUpdatePlatformManager(c *Config, updateToken bool) *UpdatePlatformManage
154175 preBaseline : getCurrentBaseline (),
155176 targetVersion : getTargetVersion (),
156177 targetBaseline : getTargetBaseline (),
178+ taskID : getTaskId (),
157179 requestUrl : platformUrl ,
158180 cvePkgs : make (map [string ][]string ),
159181 Token : token ,
@@ -270,11 +292,15 @@ func getGeneralValueFromKeyFile(path, key string) string {
270292
271293// UpdateBaseline 更新安装并检查成功后,同步baseline文件
272294func (m * UpdatePlatformManager ) UpdateBaseline () {
295+ // 更新成功后,使用内存中的信息更新baseline,防止其他渠道更新了baseline.b影响了系统的baseline
296+ updateBaseline (cacheBaseline , m .targetBaseline )
297+ updateSystemType (cacheBaseline , m .systemTypeFromPlatform )
298+ updateVersion (cacheBaseline , m .targetVersion )
273299 copyFile (cacheBaseline , realBaseline )
274300 m .preBaseline = getCurrentBaseline ()
275301}
276302
277- // 进行安装更新前,需要复制文件替换软连接
303+ // ReplaceVersionCache 进行安装更新前,需要复制文件替换软连接
278304func (m * UpdatePlatformManager ) ReplaceVersionCache () {
279305 if utils .IsSymlink (CacheVersion ) {
280306 // 如果cacheVersion已经是文件了,那么不再用源文件替换
@@ -286,6 +312,26 @@ func (m *UpdatePlatformManager) ReplaceVersionCache() {
286312 }
287313}
288314
315+ func (m * UpdatePlatformManager ) UpdateSourceList () {
316+ if ! system .IsPrivateLastore || ! m .config .PlatformUpdate {
317+ return
318+ }
319+
320+ var toWriteContent string
321+ for _ , repo := range m .repoInfos {
322+ if len (repo .Source ) != 0 {
323+ toWriteContent += repo .Source
324+ toWriteContent += "\n "
325+ }
326+ }
327+ if len (toWriteContent ) != 0 {
328+ err := ioutil .WriteFile (system .OriginSourceFile , []byte (toWriteContent ), 0644 )
329+ if err != nil {
330+ logger .Warning (err )
331+ }
332+ }
333+ }
334+
289335// RecoverVersionLink 安装更新并检查完成后,需要用软连接替换文件
290336func (m * UpdatePlatformManager ) RecoverVersionLink () {
291337 err := os .RemoveAll (CacheVersion )
@@ -371,6 +417,7 @@ func isUnstable() int {
371417type Version struct {
372418 Version string `json:"version"`
373419 Baseline string `json:"baseline"`
420+ TaskID int `json:"taskID"`
374421}
375422
376423type Policy struct {
@@ -388,13 +435,20 @@ type repoInfo struct {
388435 Cdn string `json:"cdn"`
389436 CodeName string `json:"codename"`
390437 Version string `json:"version"`
438+ Source string `json:"source"`
439+ }
440+
441+ type ClientPollSetting struct {
442+ CheckPolicyInterval int `json:"checkPolicyInterval"`
443+ StartCheckRange []int `json:"startCheckRange"`
391444}
392445
393446type updateMessage struct {
394- SystemType string `json:"systemType"`
395- Version Version `json:"version"`
396- Policy Policy `json:"policy"`
397- RepoInfos []repoInfo `json:"repoInfos"`
447+ SystemType string `json:"systemType"`
448+ Version Version `json:"version"`
449+ Policy Policy `json:"policy"`
450+ RepoInfos []repoInfo `json:"repoInfos"`
451+ ClientPollSetting ClientPollSetting `json:"clientPollSetting"`
398452}
399453
400454type tokenMessage struct {
@@ -417,6 +471,7 @@ const (
417471 GetCurrentPkgLists
418472 GetPkgCVEs // CVE 信息
419473 PostProcess
474+ PostProcessEvent
420475 PostResult
421476)
422477
@@ -454,6 +509,10 @@ var Urls = map[requestType]requestContent{
454509 "/api/v1/process" ,
455510 "POST" ,
456511 },
512+ PostProcessEvent : {
513+ "/api/v1/process/events" ,
514+ "POST" ,
515+ },
457516 PostResult : {
458517 "/api/v1/update/status" ,
459518 "POST" ,
@@ -584,7 +643,7 @@ func (m *UpdatePlatformManager) genPostProcessResponse(buf io.Reader, filePath s
584643 if err != nil {
585644 return nil , fmt .Errorf ("%v new request failed: %v " , PostProcess .string (), err .Error ())
586645 }
587- hardwareId := GetHardwareId (m .config .IncludeDiskInfo )
646+ hardwareId := GetHardwareId (m .config .IncludeDiskInfo , m . config . GetHardwareIdByHelper )
588647
589648 request .Header .Set ("X-MachineID" , hardwareId )
590649 request .Header .Set ("X-CurrentBaseline" , m .preBaseline )
@@ -708,14 +767,27 @@ func (m *UpdatePlatformManager) genUpdatePolicyByToken(updateInRelease bool) err
708767 m .targetVersion = msg .Version .Version
709768 m .systemTypeFromPlatform = msg .SystemType
710769 m .repoInfos = msg .RepoInfos
770+ m .taskID = msg .Version .TaskID
771+ logger .Infof ("current policy task id: %v" , m .taskID )
711772 m .checkTime = time .Now ().String ()
712773 // 更新策略处理
713774 m .Tp = msg .Policy .Tp
714775 if m .Tp == UpdateRegularly {
715776 m .UpdateTime , _ = time .Parse (time .RFC3339 , msg .Policy .Data .UpdateTime )
716777 }
778+ m .TimerHasChanged = false
779+ if ! utils .IsElementEqual (m .config .CheckPolicyInterval , msg .ClientPollSetting .CheckPolicyInterval ) && msg .ClientPollSetting .CheckPolicyInterval > 0 {
780+ m .config .SetCheckPolicyInterval (msg .ClientPollSetting .CheckPolicyInterval )
781+ m .TimerHasChanged = true
782+ }
783+ if ! utils .IsElementEqual (m .config .StartCheckRange , msg .ClientPollSetting .StartCheckRange ) && msg .ClientPollSetting .StartCheckRange != nil {
784+ m .TimerHasChanged = true
785+ m .config .SetStartCheckRange (msg .ClientPollSetting .StartCheckRange )
786+ }
717787
788+ m .UpdateSourceList ()
718789 m .UpdateBaselineCache ()
790+ m .saveTaskId ()
719791 // 生成仓库和InRelease
720792 if updateInRelease {
721793 m .genDepositoryFromPlatform ()
@@ -1325,12 +1397,65 @@ func (m *UpdatePlatformManager) UpdateAllPlatformDataSync() error {
13251397 return nil
13261398}
13271399
1400+ func (m * UpdatePlatformManager ) PostProcessEventMessage (body ProcessEvent ) {
1401+ logger .Debug ("post process event msg:" , body )
1402+ body .TaskID = m .taskID
1403+ if (m .config .PlatformDisabled & DisabledProcess ) != 0 {
1404+ logger .Warning ("platform is disabled" )
1405+ return
1406+ }
1407+ if len (body .EventContent ) >= 950 {
1408+ body .EventContent = body .EventContent [:950 ]
1409+ }
1410+ jsonData , err := json .Marshal (body )
1411+ if err != nil {
1412+ logger .Warning ("JSON marshaling error:" , err )
1413+ return
1414+ }
1415+ policyUrl := m .requestUrl + Urls [PostProcessEvent ].path
1416+ client := & http.Client {
1417+ Timeout : 40 * time .Second ,
1418+ }
1419+
1420+ logger .Debugf ("upgrade post process event msg is %v" , string (jsonData ))
1421+ encryptMsg , err := EncryptMsg (jsonData )
1422+ if err != nil {
1423+ logger .Warning (err )
1424+ return
1425+ }
1426+ request , err := http .NewRequest (Urls [PostProcessEvent ].method , policyUrl , strings .NewReader (base64 .StdEncoding .EncodeToString (encryptMsg )))
1427+ if err != nil {
1428+ logger .Warningf ("%v new request failed: %v " , PostProcessEvent .string (), err .Error ())
1429+ return
1430+ }
1431+ hardwareId := GetHardwareId (m .config .IncludeDiskInfo , m .config .GetHardwareIdByHelper )
1432+
1433+ request .Header .Set ("X-MachineID" , hardwareId )
1434+ request .Header .Set ("X-CurrentBaseline" , m .preBaseline )
1435+ request .Header .Set ("X-Baseline" , m .targetBaseline )
1436+ request .Header .Set ("X-Repo-Token" , base64 .RawStdEncoding .EncodeToString ([]byte (m .Token )))
1437+ response , err := client .Do (request )
1438+ if err != nil {
1439+ logger .Warningf ("post process event msg failed:%v" , err )
1440+ return
1441+ }
1442+ _ , err = getResponseData (response , PostProcessEvent )
1443+ if err != nil {
1444+ logger .Warningf ("get post process event msg response failed:%v" , err )
1445+ }
1446+ return
1447+ }
1448+
13281449// PostStatusMessage 将检查\下载\安装过程中所有异常状态和每个阶段成功的正常状态上报
1329- func (m * UpdatePlatformManager ) PostStatusMessage (message StatusMessage ) {
1450+ func (m * UpdatePlatformManager ) PostStatusMessage (message StatusMessage , forceUpload bool ) {
13301451 if (m .config .PlatformDisabled & DisabledProcess ) != 0 {
13311452 return
13321453 }
13331454
1455+ if system .IsPrivateLastore && ! forceUpload {
1456+ return
1457+ }
1458+
13341459 msg , err := json .Marshal (message )
13351460 if err != nil {
13361461 logger .Warningf ("marshal status message failed:%v" , err )
@@ -1409,7 +1534,7 @@ func (m *UpdatePlatformManager) PostUpdateLogFiles(files []string) {
14091534 if (m .config .PlatformDisabled & DisabledProcess ) != 0 {
14101535 return
14111536 }
1412- hardwareId := GetHardwareId (m .config .IncludeDiskInfo )
1537+ hardwareId := GetHardwareId (m .config .IncludeDiskInfo , m . config . GetHardwareIdByHelper )
14131538
14141539 outFilename := fmt .Sprintf ("/tmp/%s_%s_%s_%s.tar" , "update" , hardwareId , utils .GenUuid (), time .Now ().Format ("20231019102233444" ))
14151540 err := tarFiles (files , outFilename )
@@ -1456,6 +1581,7 @@ func (m *UpdatePlatformManager) CreateJobPostMsgInfo(uuid string, updateType sys
14561581 Uuid : uuid ,
14571582 UpgradeStartTime : time .Now ().Unix (),
14581583 PostStatus : NotReady ,
1584+ TaskId : m .taskID ,
14591585 }
14601586 info .save ()
14611587 m .jobPostMsgMapMu .Lock ()
@@ -1473,7 +1599,7 @@ func (m *UpdatePlatformManager) SaveJobPostMsgByUUID(uuid string, upgradeStatus
14731599 if upgradeStatus == UpgradeFailed || upgradeStatus == CheckFailed {
14741600 upgradeErrorMsg = Description
14751601 }
1476- hardwareId := GetHardwareId (m .config .IncludeDiskInfo )
1602+ hardwareId := GetHardwareId (m .config .IncludeDiskInfo , m . config . GetHardwareIdByHelper )
14771603 msg .MachineID = hardwareId
14781604 msg .UpgradeStatus = upgradeStatus
14791605 msg .UpgradeErrorMsg = upgradeErrorMsg
@@ -1649,3 +1775,35 @@ func (m *UpdatePlatformManager) PostUpgradeStatus(uuid string, upgradeStatus Upg
16491775func (m * UpdatePlatformManager ) SetInhibitAutoQuit () {
16501776
16511777}
1778+
1779+ func (m * UpdatePlatformManager ) saveTaskId () {
1780+ kf := keyfile .NewKeyFile ()
1781+ if system .NormalFileExists (cacheTaskInfo ) {
1782+ err := kf .LoadFromFile (cacheTaskInfo )
1783+ if err != nil {
1784+ logger .Warning (err )
1785+ return
1786+ }
1787+ }
1788+ kf .SetInt ("General" , "TaskID" , m .taskID )
1789+ err := kf .SaveToFile (cacheTaskInfo )
1790+ if err != nil {
1791+ logger .Warning (err )
1792+ return
1793+ }
1794+ }
1795+
1796+ func getTaskId () int {
1797+ kf := keyfile .NewKeyFile ()
1798+ err := kf .LoadFromFile (cacheTaskInfo )
1799+ if err != nil {
1800+ logger .Warning (err )
1801+ return 0
1802+ }
1803+ content , err := kf .GetInt ("General" , "TaskID" )
1804+ if err != nil {
1805+ logger .Warning (err )
1806+ return 0
1807+ }
1808+ return content
1809+ }
0 commit comments