#include "stdafx.h" #include "SpBase.h" #include "Event.h" #include "mod_centersetting.h" #include "publicFunExport.h" #include "array.h" #include "fileutil.h" #include "iniutil.h" #include "array.h" #include "EventCode.h" #include "SpIni.h" #include "SpUtility.h" #include "CommEntitySettings.hpp" #include "CommEntityHelpAgge.hpp" #include #include "microservices/api_comm.h" using namespace std; #define DOWNLOAD_CENTERSETTINGS_TIMER_ID 1 #define DOWNLOAD_CENTERSETTINGS_TIMER_INTERVAL (5 * 60 * 1000) CServerSessionBase *CCenterSettingEntity::OnNewSession(const char* /*pszRemoteEntityName*/, const char * /*pszClass*/) { return new CCenterSettingService(this); } void CCenterSettingEntity::OnPreStart(CAutoArray strArgs, CSmartPointer pTransactionContext) { ErrorCodeEnum result(Error_Succeed); if (!SP::Module::Comm::Settings::IsInConfigScheduleMode(this)) { CSimpleStringA strFilePath; GetFunction()->GetPath("CenterSetting", strFilePath); if (!ExistsFileA(strFilePath)) { std::map srcData; srcData.insert(std::make_pair("reason", "empty")); srcData.insert(std::make_pair("errmsg", "集中配置文件不存在,请先下载集中配置再重启应用!")); srcData.insert(std::make_pair("rebootTime", "")); auto ret = generateJsonStr(srcData); if (ret.first) { LogNotify(Notify_Error, Error_InvalidState, EVENT_CENTERSETTING_NOTIFY_LACK_OF_CENTER_CONFIG, ret.second.c_str()); m_CenterFileNotExists = true; } } } pTransactionContext->SendAnswer(result); } void CCenterSettingEntity::OnStarted() { if (SP::Module::Comm::Settings::IsInConfigScheduleMode(this)) { Dbg("in config mode, do nothing about centersetting sync"); return; } CSimpleStringA strPath; GetFunction()->GetPath("Cfg", strPath); auto arr = fileutil_get_sub_files(strPath); if (arr != NULL) { for (int i = 0; i < arr->nelts; ++i) { ConfigFileInfo info = {}; char *pszFile = ARRAY_IDX(arr, i, char*); CSimpleStringA strSite; if (TryExtractSiteFromFileName(pszFile, info.strFileName, strSite)) { char szTmp[80]; inifile_read_str_s("Main", "SyncHash", "", szTmp, 80, pszFile); info.strFileHash = szTmp; inifile_read_str_s("Main", "SyncTime", "", szTmp, 80, pszFile); DWORD nValue; sscanf(szTmp, "0x%X", &nValue); info.dwSyncTime = nValue; m_SyncFileInfo[(const char*)strSite] = info; } } toolkit_array_free2(arr); } CSimpleStringA strFilePath; GetFunction()->GetPath("CenterSetting", strFilePath); CSimpleStringA strNoUsed; TryExtractSiteFromFileName(strFilePath, strNoUsed, m_strCurSiteExtName); // 缓存当前RVCWeb版本 char szVersion[64] = {}; inifile_read_str_s("IEBrowser", "RvcWebVersion", "", szVersion, 64, strFilePath); m_strRvcWebVersion = szVersion; // 立刻同步配置 if (!m_CenterFileNotExists) { /** 让用户主动去处理*/ GetFunction()->PostEntityTaskFIFO(new DownloadCenterSettingsTask(this)); } //订阅首页状态 GetFunction()->RegistSysVarEvent("UIState", this); // 启动轮询定时器 5min if (!m_CenterFileNotExists) { /** 让用户主动去处理*/ GetFunction()->SetTimer(DOWNLOAD_CENTERSETTINGS_TIMER_ID, this, DOWNLOAD_CENTERSETTINGS_TIMER_INTERVAL); } } void CCenterSettingEntity::OnTimeout(DWORD dwTimerID) { BeginDownloadCenterSetting(GetCenterSettingsACSTypeDownloadUrl()); } void CCenterSettingEntity::OnPreClose(EntityCloseCauseEnum eCloseCause,CSmartPointer pTransactionContext) { DisconnectForSure(); GetFunction()->KillTimer(DOWNLOAD_CENTERSETTINGS_TIMER_ID); pTransactionContext->SendAnswer(Error_Succeed); } ErrorCodeEnum CCenterSettingEntity::BeginDownloadCenterSetting(LPCTSTR serverIP, int port) { LOG_FUNCTION(); CSimpleStringA strServiceLink(serverIP == NULL ? "" : serverIP); if (SP::Module::Ulitily::IsValidUrl(strServiceLink)) { Dbg("download centersettings file from head branch micro service!"); CenterSettingsMicroServiceHelper microHelper(this); if (strServiceLink.IndexOf(URLPATH_CENTERSETTING_UPDATE_CONFIG) == -1) { microHelper.SetServicesUrl(strServiceLink + URLPATH_CENTERSETTING_UPDATE_CONFIG); } else { microHelper.SetServicesUrl(strServiceLink); } CSimpleStringA strLastErrInfo(true); const ErrorCodeEnum rc = microHelper.GetCenterSetting(strLastErrInfo); if (rc != Error_Succeed) { LogWarn(Severity_Middle, rc, ERR_MOD_CENTERSETTING_CONNECT_FAILED, CSimpleStringA::Format("Get centersetting failed:%s", strLastErrInfo.GetData())); } else { if (SP::Module::Comm::Settings::IsUsingSubBranchServerConfig(this)) { LogWarn(Severity_Middle, Error_Debug, ERR_MOD_CENTERSETTING_CHANGE_FROM_SUB2HEADBRANCH, "CenterSetting Source Change: from branch to head"); } else if (!SP::Module::Comm::Settings::IsUsingHeadBranchServices(this)) { LogWarn(Severity_Middle, Error_Debug, ERR_MOD_CENTERSETTING_CHANGE_FROM_NONE2HEADBRANCH, "CenterSetting Source Change: from unknown to head"); } SP::Module::Comm::Settings::StoreHeadBranchServicesMode(this, TRUE); LogWarn(Severity_Middle, Error_Succeed, EVENT_MOD_CENTERSETTING_CONNECT_SUCC, "Get centersetting succ."); } ReturnAndClearDownloadContext(rc); return rc; } else if (SP::Module::Ulitily::CheckIPv4(strServiceLink.GetData()) && port > 0) { /*指定分行服务IP和端口下载集中配置文件*/ if (!ConnectToServiceWithType(ConnectServerType::PARAM, serverIP, port)) { return Error_NetBroken; } else { m_nConnectFailCount = 0; LOG_ASSERT(IsServerConnectedNow()); CSystemStaticInfo info; ErrorCodeEnum rc = GetFunction()->GetSystemStaticInfo(info); rc = m_pConnection->BeginPollConfig(info); return rc; } } else if (strServiceLink.IsNullOrEmpty() && port == 0) { //计时器同步 if (SP::Module::Comm::Settings::IsUsingHeadBranchServices(this)) { CenterSettingsMicroServiceHelper microHelper(this); if (microHelper.IsConfigureValid()) { CSimpleStringA strLastErrInfo(true); const ErrorCodeEnum rc = microHelper.GetCenterSetting(strLastErrInfo); if (rc != Error_Succeed) { LogWarn(Severity_Middle, rc, ERR_MOD_CENTERSETTING_CONNECT_FAILED, CSimpleStringA::Format("Get centersetting failed:%s", strLastErrInfo.GetData())); } else { LogWarn(Severity_Middle, Error_Succeed, EVENT_MOD_CENTERSETTING_CONNECT_SUCC, "Get centersetting succ."); } ReturnAndClearDownloadContext(rc); return rc; } else { LogWarn(Severity_High, Error_DataCheck, ERR_MOD_CENTERSETTING_FILE_LEGALITY_UNEXPECTED, "CenterSetting file is illegality!"); ReturnAndClearDownloadContext(Error_DataCheck); return Error_DataCheck; } } else { if (!ConnectToServiceWithType(ConnectServerType::DEFAULT)) { return Error_NetBroken; } else { m_nConnectFailCount = 0; LOG_ASSERT(IsServerConnectedNow()); CSystemStaticInfo info; ErrorCodeEnum rc = GetFunction()->GetSystemStaticInfo(info); rc = m_pConnection->BeginPollConfig(info); return rc; } } } else { LogWarn(Severity_Middle, Error_Param, 0, CSimpleStringA::Format("%s,%d", strServiceLink.GetData(), port)); ReturnAndClearDownloadContext(Error_Param); return Error_Param; } } ErrorCodeEnum CCenterSettingEntity::EndDownloadCenterSetting(ErrorCodeEnum rc) { // 备份地址只使用短连接,用于应急切换,使用后立即释放,仍尝试使用新地址 //if (m_bUseBackupNow) // xkm@20160803: 改为短连接 DisconnectForSure(); if (rc == Error_Succeed) { if (SP::Module::Comm::Settings::IsUsingHeadBranchServices(this)) { LogWarn(Severity_Middle, Error_Debug, ERR_MOD_CENTERSETTING_CHANGE_FROM_HEAD2SUBBRANCH, "CenterSetting Source Change: from head to branch"); } else if (!SP::Module::Comm::Settings::IsUsingSubBranchServerConfig(this)) { LogWarn(Severity_Middle, Error_Debug, ERR_MOD_CENTERSETTING_CHANGE_FROM_NONE2SUBBRANCH, "CenterSetting Source Change: from unknown to branch"); } SP::Module::Comm::Settings::StoreHeadBranchServicesMode(this, FALSE); LogEvent(Severity_Middle, EVENT_MOD_CENTERSETTING_DOWNOK, "集中配置同步成功"); } ReturnAndClearDownloadContext(rc); return rc; } ErrorCodeEnum CCenterSettingEntity::DownloadCenterSetting(SpReqAnsContext::Pointer sp) { if (IsDownloadPending()) { Dbg("last download call not complet"); if (sp != NULL) { sp->Answer(Error_Duplication); } return Error_Duplication; } m_spDownloadCall = sp; ErrorCodeEnum error = (sp != NULL ? BeginDownloadCenterSetting(sp->Req.strAddr, sp->Req.nPort) : BeginDownloadCenterSetting(GetCenterSettingsACSTypeDownloadUrl())); if (error == Error_NetBroken) { // 如果返回特定的错误码 Error_NetBroken 则立即返回到上下文调用层 m_spDownloadCall = nullptr; if (sp != NULL) { sp->Answer(Error_Unexpect); } return error; } return Error_Succeed; } void CCenterSettingEntity::OnPrePause(CSmartPointer pTransactionContext) { LOG_ASSERT(SP::Module::Ulitily::IsValidUrl("http://centerconfig.paasst.cmbchina.cn/api/terminal/center/config")); LOG_ASSERT(SP::Module::Ulitily::IsValidUrl("https://centerconfig.paasst.cmbchina.cn/api/terminal/center/config")); LOG_ASSERT(SP::Module::Ulitily::IsValidUrl("https://rvcgateway.paas.cmbchina.cn")); LOG_ASSERT(SP::Module::Ulitily::IsValidUrl("http://rvcgateway.paas.cmbchina.cn")); LOG_ASSERT(!SP::Module::Ulitily::IsValidUrl("99.1.100.215")); LOG_ASSERT(!SP::Module::Ulitily::IsValidUrl("rvcgateway.paas.cmbchina.cn")); LOG_ASSERT(SP::Module::Ulitily::CheckIPv4("99.1.100.215")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("99")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.1")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.1.2")); LOG_ASSERT(SP::Module::Ulitily::CheckIPv4("1.1.2.3")); LOG_ASSERT(SP::Module::Ulitily::CheckIPv4("255.255.255.255")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.01.2.3")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.501.2.3")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.2.256.3")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.2.3.256")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("256.2.3.255")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1. 1.2.3")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4(" 1.1.2.3")); LOG_ASSERT(!SP::Module::Ulitily::CheckIPv4("1.1.2.3 ")); pTransactionContext->SendAnswer(Error_Succeed); } void CCenterSettingEntity::EditWebUrl(SpReqAnsContext::Pointer ctx) { ErrorCodeEnum result(Error_Unexpect); ctx->Ans.result = 0; ctx->Ans.msg = ""; switch (ctx->Req.operation) { case 1: //new { CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int count(0); bool newCreate = true; pConfig->ReadConfigValueInt("CustomWebUrl", "Count", count); int newIndex(count + 1); for (int i = 1; i <= count; ++i) { CustomWebUrlConfig item; CSimpleStringA strSection = CSimpleStringA::Format("CustomWebUrl%d", i); pConfig->ReadConfigValue(strSection, "FultureUrl", item.strFutureUrl); pConfig->ReadConfigValue(strSection, "AdUrl", item.strAdUrl); pConfig->ReadConfigValue(strSection, "Remark", item.strRemark); pConfig->ReadConfigValueInt(strSection, "Env", item.useEnv); pConfig->ReadConfigValueInt(strSection, "Status", item.curStatus); if (!item.IsValid()) { newIndex = i; newCreate = false; break; } } CSimpleStringA strNewSection = CSimpleStringA::Format("CustomWebUrl%d", newIndex); pConfig->WriteConfigValue(strNewSection, "FultureUrl", ctx->Req.futureUrl); pConfig->WriteConfigValue(strNewSection, "AdUrl", ctx->Req.adUrl); CSimpleStringA strRemark(ctx->Req.remark); if (strRemark.IsNullOrEmpty()) { if (ctx->Req.env == 1) strRemark = "DEV:"; else if(ctx->Req.env == 2) strRemark = "ST:"; if (ctx->Req.env == 3) strRemark = "UAT:"; strRemark += ctx->Req.futureUrl; } pConfig->WriteConfigValue(strNewSection, "Remark", strRemark); pConfig->WriteConfigValueInt(strNewSection, "Env", ctx->Req.env); pConfig->WriteConfigValueInt(strNewSection, "Status", WEBURL_STATUS_PROVIDE); if (ctx->Req.setDefault) { pConfig->WriteConfigValueInt("CustomWebUrl", "Current", newIndex); } if (newCreate) { pConfig->WriteConfigValueInt("CustomWebUrl", "Count", newIndex); } ctx->Ans.addition = newIndex; result = Error_Succeed; } break; case 2: //delete { if (ctx->Req.index >= WEBURL_ITEM_INDEX_CENTERSETTING) { result = Error_NoPrivilege; } else { CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int oldStatus(0); CSimpleStringA strSection = CSimpleStringA::Format("CustomWebUrl%d", ctx->Req.index); pConfig->ReadConfigValueInt(strSection, "Status", oldStatus); pConfig->WriteConfigValueInt(strSection, "Status", WEBURL_STATUS_DEPRECATE); int currentUsing(0); pConfig->ReadConfigValueInt("CustomWebUrl", "Current", currentUsing); if (ctx->Req.index == currentUsing) { pConfig->WriteConfigValueInt("CustomWebUrl", "Current", 0); } result = Error_Succeed; } } break; case 3: //update { if (ctx->Req.index >= WEBURL_ITEM_INDEX_CENTERSETTING) { //如果当前是集中配置文件 CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int currentUsing(0); pConfig->ReadConfigValueInt("CustomWebUrl", "Current", currentUsing); if (currentUsing != 0 && ctx->Req.setDefault) { pConfig->WriteConfigValueInt("CustomWebUrl", "Current", 0); result = Error_Succeed; } else { result = Error_NoPrivilege; } break; } CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); CSimpleStringA strExistedSection = CSimpleStringA::Format("CustomWebUrl%d", ctx->Req.index); pConfig->WriteConfigValue(strExistedSection, "FultureUrl", ctx->Req.futureUrl); pConfig->WriteConfigValue(strExistedSection, "AdUrl", ctx->Req.adUrl); CSimpleStringA strRemark(ctx->Req.remark); if (strRemark.IsNullOrEmpty()) { if (ctx->Req.env == 1) strRemark = "DEV:"; else if (ctx->Req.env == 2) strRemark = "ST:"; if (ctx->Req.env == 3) strRemark = "UAT:"; strRemark += ctx->Req.futureUrl; } pConfig->WriteConfigValue(strExistedSection, "Remark", strRemark); pConfig->WriteConfigValueInt(strExistedSection, "Env", ctx->Req.env); pConfig->WriteConfigValueInt(strExistedSection, "Status", WEBURL_STATUS_PROVIDE); if (ctx->Req.setDefault) { pConfig->WriteConfigValueInt("CustomWebUrl", "Current", ctx->Req.index); } ctx->Ans.addition = ctx->Req.index; result = Error_Succeed; } break; default: result = Error_NotSupport; break; } ctx->Answer(result); return; } void CCenterSettingEntity::GetWebUrlList(SpReqAnsContext::Pointer ctx) { ErrorCodeEnum result(Error_Succeed); CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int cnt(0), curIndex(0), realCnt(0); bool hasDefaultFromCustom(false); pConfig->ReadConfigValueInt("CustomWebUrl", "Count", cnt); int currentUsing(0); pConfig->ReadConfigValueInt("CustomWebUrl", "Current", currentUsing); CAutoArray< CustomWebUrlConfig> configs(cnt); Dbg("custom count: %d", cnt); for (int i = 1; i <= cnt; ++i) { CustomWebUrlConfig& item = configs[i - 1]; item.configFrom = WEBURL_CONFIG_CUSTOM; item.index = i; CSimpleStringA strSection = CSimpleStringA::Format("CustomWebUrl%d", i); pConfig->ReadConfigValue(strSection, "FultureUrl", item.strFutureUrl); pConfig->ReadConfigValue(strSection, "AdUrl", item.strAdUrl); pConfig->ReadConfigValue(strSection, "Remark", item.strRemark); pConfig->ReadConfigValueInt(strSection, "Env", item.useEnv); pConfig->ReadConfigValueInt(strSection, "Status", item.curStatus); if (item.IsValid()) { realCnt++; if (currentUsing == i) { hasDefaultFromCustom = true; item.curStatus = WEBURL_STATUS_DEFAULT; } else { item.curStatus = WEBURL_STATUS_PROVIDE; } } } CustomWebUrlConfig defaultOne; ErrorCodeEnum resultFromFetch = GetWebUrlInfoFromCenterSettings(defaultOne); if (resultFromFetch == Error_Succeed) { Dbg("add centersettings config"); realCnt += 1; if (!hasDefaultFromCustom) { defaultOne.curStatus = WEBURL_STATUS_DEFAULT; } } Dbg("total count: %d", realCnt); ctx->Ans.index.Init(realCnt); ctx->Ans.futureUrl.Init(realCnt); ctx->Ans.adUrl.Init(realCnt); ctx->Ans.remark.Init(realCnt); ctx->Ans.env.Init(realCnt); ctx->Ans.type.Init(realCnt); ctx->Ans.status.Init(realCnt); if (resultFromFetch == Error_Succeed) { ctx->Ans.index[curIndex] = WEBURL_ITEM_INDEX_CENTERSETTING; ctx->Ans.futureUrl[curIndex] = defaultOne.strFutureUrl; ctx->Ans.adUrl[curIndex] = defaultOne.strAdUrl; ctx->Ans.remark[curIndex] = defaultOne.strRemark; ctx->Ans.env[curIndex] = defaultOne.useEnv; ctx->Ans.type[curIndex] = defaultOne.configFrom; ctx->Ans.status[curIndex] = defaultOne.curStatus; curIndex++; } for (int i = 0; i < configs.GetCount(); ++i) { CustomWebUrlConfig& item = configs[i]; if (item.IsValid()) { ctx->Ans.index[curIndex] = item.index; ctx->Ans.futureUrl[curIndex] = item.strFutureUrl; ctx->Ans.adUrl[curIndex] = item.strAdUrl; ctx->Ans.remark[curIndex] = item.strRemark; ctx->Ans.env[curIndex] = item.useEnv; ctx->Ans.type[curIndex] = item.configFrom; ctx->Ans.status[curIndex] = item.curStatus; curIndex++; } } ctx->Answer(result); } void CCenterSettingEntity::GetActiveCustomUrl( SpReqAnsContext::Pointer ctx) { ErrorCodeEnum result(Error_Succeed); CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int cnt(0), currentUsing(0); pConfig->ReadConfigValueInt("CustomWebUrl", "Count", cnt); pConfig->ReadConfigValueInt("CustomWebUrl", "Current", currentUsing); if (cnt == 0 || currentUsing == 0) { result = Error_NotConfig; } else { CSimpleStringA strSection = CSimpleStringA::Format("CustomWebUrl%d", currentUsing); pConfig->ReadConfigValue(strSection, "FultureUrl", ctx->Ans.fultureUrl); pConfig->ReadConfigValue(strSection, "AdUrl", ctx->Ans.adUrl); if (!ctx->Ans.fultureUrl.IsNullOrEmpty()) { result = Error_Succeed; } else { result = Error_CheckSum; } } ctx->Answer(result); return; } void CCenterSettingEntity::EditTerminalBackupInfo(SpReqAnsContext::Pointer ctx) { ErrorCodeEnum result(Error_Succeed); CSimpleStringA errMsg(true); ErrorCodeEnum tmpResult(Error_Succeed); switch (ctx->Req.operation) { case 1: //new { CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int count(0); bool newCreate = true; pConfig->ReadConfigValueInt("TerminalBackup", "Count", count); int newIndex(count + 1); for (int i = 1; i <= count; ++i) { CustomWebUrlConfig item; CSimpleStringA strSection = CSimpleStringA::Format("TerminalBackup%d", i); pConfig->ReadConfigValue(strSection, "TerminalNo", item.strFutureUrl); pConfig->ReadConfigValue(strSection, "ServerIP", item.strAdUrl); pConfig->ReadConfigValue(strSection, "Remark", item.strRemark); pConfig->ReadConfigValueInt(strSection, "Env", item.useEnv); pConfig->ReadConfigValueInt(strSection, "Status", item.curStatus); if (!item.IsValid()) { newIndex = i; newCreate = false; break; } } CSimpleStringA strNewSection = CSimpleStringA::Format("TerminalBackup%d", newIndex); pConfig->WriteConfigValue(strNewSection, "TerminalNo", ctx->Req.terminalNo); pConfig->WriteConfigValue(strNewSection, "ServerIP", ctx->Req.branchIP); CSimpleStringA strRemark(ctx->Req.remark); if (strRemark.IsNullOrEmpty()) { if (ctx->Req.env == 1) strRemark = "DEV:"; else if (ctx->Req.env == 2) strRemark = "ST:"; if (ctx->Req.env == 3) strRemark = "UAT:"; strRemark += ctx->Req.terminalNo; } pConfig->WriteConfigValue(strNewSection, "Remark", strRemark); pConfig->WriteConfigValueInt(strNewSection, "Env", ctx->Req.env); pConfig->WriteConfigValueInt(strNewSection, "Status", WEBURL_STATUS_PROVIDE); if (ctx->Req.setDefault) { tmpResult = UpdateTerminalInfoAtChange(ctx->Req.terminalNo); if (!(tmpResult == Error_Succeed || tmpResult == Error_AlreadyExist)) { pConfig->WriteConfigValueInt(strNewSection, "Status", WEBURL_STATUS_DEPRECATE); errMsg = CSimpleStringA::Format("更新终端号信息失败!"); break; } } if (newCreate) { pConfig->WriteConfigValueInt("TerminalBackup", "Count", newIndex); } ctx->Ans.addition = (int)ConfirmCenterSettingsFileAndUpdateIfNecessary(ctx->Req.branchIP); result = Error_Succeed; } break; case 2: //delete { CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); CSimpleStringA strSection = CSimpleStringA::Format("TerminalBackup%d", ctx->Req.index); int oldStatus(0); pConfig->ReadConfigValueInt(strSection, "Status", oldStatus); pConfig->WriteConfigValueInt(strSection, "Status", WEBURL_STATUS_DEPRECATE); } break; case 3: //update { CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); CSimpleStringA strExistedSection = CSimpleStringA::Format("TerminalBackup%d", ctx->Req.index); if (ctx->Req.setDefault) { tmpResult = UpdateTerminalInfoAtChange(ctx->Req.terminalNo); if (!(tmpResult == Error_Succeed || tmpResult == Error_AlreadyExist)) { errMsg = CSimpleStringA::Format("更新终端号信息失败!"); break; } } pConfig->WriteConfigValue(strExistedSection, "TerminalNo", ctx->Req.terminalNo); pConfig->WriteConfigValue(strExistedSection, "ServerIP", ctx->Req.branchIP); CSimpleStringA strRemark(ctx->Req.remark); if (strRemark.IsNullOrEmpty()) { if (ctx->Req.env == 1) strRemark = "DEV:"; else if (ctx->Req.env == 2) strRemark = "ST:"; if (ctx->Req.env == 3) strRemark = "UAT:"; strRemark += ctx->Req.terminalNo; } pConfig->WriteConfigValue(strExistedSection, "Remark", strRemark); pConfig->WriteConfigValueInt(strExistedSection, "Env", ctx->Req.env); pConfig->WriteConfigValueInt(strExistedSection, "Status", WEBURL_STATUS_PROVIDE); ctx->Ans.addition = (int)ConfirmCenterSettingsFileAndUpdateIfNecessary(ctx->Req.branchIP); result = Error_Succeed; } break; default: result = Error_NotSupport; break; } ctx->Ans.result = tmpResult; ctx->Ans.msg = errMsg; ctx->Answer(result); return; } void CCenterSettingEntity::GetTerminalBackupInfoList(SpReqAnsContext::Pointer ctx) { ErrorCodeEnum result(Error_Succeed); CSmartPointer pConfig; GetFunction()->OpenConfig(Config_Cache, pConfig); int cnt(0), curIndex(0), realCnt(0); bool hasDefaultFromCustom(false); pConfig->ReadConfigValueInt("TerminalBackup", "Count", cnt); CAutoArray< CustomWebUrlConfig> configs(cnt); Dbg("custom count: %d", cnt); for (int i = 1; i <= cnt; ++i) { CustomWebUrlConfig& item = configs[i - 1]; item.configFrom = WEBURL_CONFIG_CUSTOM; item.index = i; CSimpleStringA strSection = CSimpleStringA::Format("TerminalBackup%d", i); pConfig->ReadConfigValue(strSection, "TerminalNo", item.strFutureUrl); pConfig->ReadConfigValue(strSection, "ServerIP", item.strAdUrl); pConfig->ReadConfigValue(strSection, "Remark", item.strRemark); pConfig->ReadConfigValueInt(strSection, "Env", item.useEnv); pConfig->ReadConfigValueInt(strSection, "Status", item.curStatus); if (item.IsValid()) { realCnt++; DWORD dwMask(0); if (IsParamCurrentUsed(item.strFutureUrl, item.strAdUrl, dwMask)) { hasDefaultFromCustom = true; item.curStatus = WEBURL_STATUS_DEFAULT; } else { item.curStatus = WEBURL_STATUS_PROVIDE; } } } ErrorCodeEnum resultFromFetch(Error_NotInit); CustomWebUrlConfig defaultOne; if (!hasDefaultFromCustom) { resultFromFetch = GetParamCurrentUseing(defaultOne); if (resultFromFetch == Error_Succeed) { Dbg("add root config"); realCnt += 1; defaultOne.curStatus = WEBURL_STATUS_DEFAULT; } } Dbg("total count: %d", realCnt); ctx->Ans.index.Init(realCnt); ctx->Ans.terminalNo.Init(realCnt); ctx->Ans.branchIP.Init(realCnt); ctx->Ans.remark.Init(realCnt); ctx->Ans.env.Init(realCnt); ctx->Ans.status.Init(realCnt); if (resultFromFetch == Error_Succeed) { ctx->Ans.index[curIndex] = defaultOne.index; ctx->Ans.terminalNo[curIndex] = defaultOne.strFutureUrl; ctx->Ans.branchIP[curIndex] = defaultOne.strAdUrl; ctx->Ans.remark[curIndex] = defaultOne.strRemark; ctx->Ans.env[curIndex] = defaultOne.useEnv; ctx->Ans.status[curIndex] = defaultOne.curStatus; Dbg("index: %d", ctx->Ans.index[curIndex]); Dbg("terminalNo: %s", ctx->Ans.terminalNo[curIndex].GetData()); Dbg("branchIP: %s", ctx->Ans.branchIP[curIndex].GetData()); Dbg("remark: %s", ctx->Ans.remark[curIndex].GetData()); Dbg("env: %d", ctx->Ans.env[curIndex]); Dbg("status: %d", ctx->Ans.status[curIndex]); curIndex++; } for (int i = 0; i < configs.GetCount(); ++i) { CustomWebUrlConfig& item = configs[i]; if (item.IsValid()) { ctx->Ans.index[curIndex] = item.index; ctx->Ans.terminalNo[curIndex] = item.strFutureUrl; ctx->Ans.branchIP[curIndex] = item.strAdUrl; ctx->Ans.remark[curIndex] = item.strRemark; ctx->Ans.env[curIndex] = item.useEnv; ctx->Ans.status[curIndex] = item.curStatus; curIndex++; } } ctx->Answer(result); } void CCenterSettingEntity::DownloadCenterFiles( SpReqAnsContext::Pointer ctx) { if (IsDownloadPending()) { Dbg("%s: last download call not complet", __FUNCTION__); ctx->Answer(Error_Duplication); return; } if (ctx->Req.strAddr == NULL || strlen(ctx->Req.strAddr) == 0 || ctx->Req.nPort <= 0) { ctx->Answer(Error_Param); return; } m_spDownloadCallEx = ctx; DisconnectForSure(); m_pConnection = new CCenterSettingConn(this); if (!m_pConnection->Connect(ctx->Req.strAddr, ctx->Req.nPort, 3)) { DisconnectForSure(); ReturnAndClearDownloadContext(Error_NetBroken); } else { Dbg("custom download from server %s:%d", ctx->Req.strAddr.GetData(), ctx->Req.nPort, 3); if (ctx->Req.deleteIfExist) { Dbg("Remove CenterSettings file!"); RemoveAllCenterSettingFiles(); } CSystemStaticInfo info; GetFunction()->GetSystemStaticInfo(info); if (!ctx->Req.additional1.IsNullOrEmpty()) { Dbg("Render TeminalNo from %s to %s", info.strTerminalID.GetData(), ctx->Req.additional1.GetData()); info.strTerminalID = ctx->Req.additional1; } /** 该接口永远返回成功,所以没有做判断 [Gifur@2021127]*/ ErrorCodeEnum ret = m_pConnection->BeginPollConfig(info); } } ErrorCodeEnum CCenterSettingEntity::GetSyncInfo(unsigned int& dwSyncTime, CSimpleStringA& strSyncHash, CSimpleStringA& strSyncFile) { if (m_SyncFileInfo.find((const char*)m_strCurSiteExtName) != m_SyncFileInfo.end()) { auto info = m_SyncFileInfo[(const char*)m_strCurSiteExtName]; dwSyncTime = info.dwSyncTime; strSyncFile = info.strFileName; strSyncHash = info.strFileHash; return Error_Succeed; } return Error_NotExist; } bool CCenterSettingEntity::ParseIPAddress(const char *str, CSimpleStringA &ip, int &port) { if (str) { char tmp1[32] = {}; char tmp2[16] = {}; sscanf(str, "%s %s", tmp1, tmp2); if (tmp1[0] != 0 && tmp2[0] != 0) { ip = tmp1; port = atoi(tmp2); return true; } } return false; } bool CCenterSettingEntity::TryExtractSiteFromFileName( const char *pszPath, CSimpleStringA &strFileName, CSimpleStringA &strSite) { const regex re("(CenterSetting\.(.+)\.ini$)"); cmatch result; if (!regex_search(pszPath, result, re)) return false; strFileName = result[1].str().c_str(); strSite = result[2].str().c_str(); return true; } ErrorCodeEnum CCenterSettingEntity::GetWebUrlInfoFromCenterSettings(CustomWebUrlConfig& config) { CSmartPointer spCerConfig; ErrorCodeEnum err = GetFunction()->OpenConfig(Config_CenterSetting, spCerConfig); SpIniMappingTable table; CSimpleStringA entityName("Chromium"); // clean cache every time table.AddEntryString(entityName, "UserMgrUrlFulture", config.strFutureUrl, ""); table.AddEntryString(entityName, "UserMgrAd", config.strAdUrl, ""); err = table.Load(spCerConfig); if (err == Error_Succeed) { config.configFrom = WEBURL_CONFIG_CENTESETTING; config.curStatus = WEBURL_STATUS_PROVIDE; config.useEnv = WEBURL_ENV_ALL; config.strRemark = "Default Config From CenterSettings"; } if (config.strFutureUrl.IsNullOrEmpty()) { err = Error_NotConfig; } return err; } bool CCenterSettingEntity::ConnectToServiceWithType(ConnectServerType type, LPCTSTR serverIP, int port) { LOG_FUNCTION(); Dbg("connect type:%d, %s::%d", type, serverIP, port); if (type == ConnectServerType::DEFAULT && IsServerConnectedNow()) { Dbg("Connection has been built before."); return true; } DisconnectForSure(); m_pConnection = new CCenterSettingConn(this); m_bUseBackupNow = (type == ConnectServerType::BACKUP); if (m_bUseBackupNow) { CSmartPointer pConfig; auto rc = GetFunction()->OpenConfig(Config_CenterSetting, pConfig); assert(rc == Error_Succeed); CSimpleStringA strLastServer; rc = pConfig->ReadConfigValue("Main", "LastServer", strLastServer); if (rc != Error_Succeed || strLastServer.IsNullOrEmpty()) { Dbg("read last server from center setting fail"); return false; } CSimpleStringA strIP; int nPort(0); if (!ParseIPAddress(strLastServer, strIP, nPort)) { Dbg("parse last server [%s] fail", (const char*)strLastServer); return false; } return m_pConnection->Connect(strIP, nPort, 3); } else if(type == ConnectServerType::PARAM) { Dbg("custom download from server %s:%d", serverIP, port); return m_pConnection->Connect(serverIP, port, 3); } return m_pConnection->ConnectFromCentralSetting(); } void CCenterSettingEntity::DisconnectForSure() { if (m_pConnection !=NULL) { if (m_pConnection->IsConnectionOK()) m_pConnection->Close(); m_pConnection->DecRefCount(); m_pConnection = NULL; } } void CCenterSettingEntity::OnSysVarEvent(const char* pszKey, const char* pszValue, const char* pszOldValue, const char* pszEntityName) { if ((_strnicmp(pszKey, "UIState", strlen("UIState")) == 0)) { if (_strnicmp(pszValue, "M", strlen("M")) == 0) { Dbg("enter main page"); CSimpleStringA strCurFile; GetFunction()->GetPath("CenterSetting", strCurFile); CSimpleStringA strBackFile = CSimpleStringA::Format("%s.backup", strCurFile.GetData()); if (!fileutil_copy_file(strBackFile, strCurFile)) { Dbg("Copy curFile to backFile failed: %d", GetLastError()); } GetFunction()->UnregistSysVarEvent("UIState"); } else { Dbg("not main page[%s]", pszValue); } } } bool CCenterSettingEntity::CheckServerIPIsExist() { LOG_FUNCTION(); CSmartPointer pConfig; auto rc = GetFunction()->OpenConfig(Config_CenterSetting, pConfig); assert(rc == Error_Succeed); CSimpleStringA strServer; rc = pConfig->ReadConfigValue("CenterSetting", "Server", strServer); if (rc != Error_Succeed || strServer.IsNullOrEmpty()) { Dbg("read strServer from center setting fail."); Dbg("use backup center setting..."); CSimpleStringA strBackFile, strCurFile; GetFunction()->GetPath("CenterSetting", strCurFile); strBackFile = CSimpleStringA::Format("%s.backup", strCurFile.GetData()); if(-1 == fileutil_copy_file(strCurFile, strBackFile)) { Dbg("Copy backFile to curFile failed: %d", GetLastError()); return false; } else { rc = pConfig->ReadConfigValue("CenterSetting", "Server", strServer); if (rc != Error_Succeed || strServer.IsNullOrEmpty()) { return false; } } } return true; } ErrorCodeEnum CCenterSettingEntity::UpdateTerminalInfoAtChange(const CSimpleStringA& newTerminalInfo) { ErrorCodeEnum result(Error_Succeed); CSystemStaticInfo sysInfo; result = GetFunction()->GetSystemStaticInfo(sysInfo); if (result == Error_Succeed) { if (sysInfo.strTerminalID == newTerminalInfo) { result = Error_AlreadyExist; } else { CSimpleStringA strTemp = CSimpleStringA::Format("更新终端号信息:%s -> %s", sysInfo.strTerminalID.GetData(), newTerminalInfo.GetData()); LogWarn(Severity_High, Error_Debug, EVENT_CENTERSETTING_CHANGE_ROOT_TERMINALNO, strTemp); CSimpleStringA strRootCfgPath, rootPath; ErrorCodeEnum ec = GetFunction()->GetPath("HardwareCfg", strRootCfgPath); rootPath = strRootCfgPath; rootPath += SPLIT_SLASH_STR; rootPath += "root.ini"; inifile_write_str(rootPath, "Terminal", "TerminalNo", newTerminalInfo); inifile_write_str(rootPath, "Terminal", "LastTerminalNo", sysInfo.strTerminalID); char tmp[32] = {'\0'}; inifile_read_str_s("Terminal", "TerminalNo", "", tmp, 31, rootPath); CSimpleStringA strConfirmTerminalNo(tmp); if (strConfirmTerminalNo != newTerminalInfo) { Dbg("Update TeminalNo failed: read returned: %s, write into: %s", strConfirmTerminalNo.GetData(), newTerminalInfo.GetData()); result = Error_FailVerify; } } } return result; } bool CCenterSettingEntity::IsParamCurrentUsed(const CSimpleStringA& strTerminalInfo, const CSimpleStringA& strServerIP, DWORD& outMask) { bool result(true); outMask = 0; CSystemStaticInfo sysInfo; GetFunction()->GetSystemStaticInfo(sysInfo); if (sysInfo.strTerminalID.IsNullOrEmpty() || sysInfo.strTerminalID != strTerminalInfo) { result = false; } else { outMask |= 0x1; } CSmartPointer pConfig; CSimpleStringA strServer; GetFunction()->OpenConfig(Config_CenterSetting, pConfig); pConfig->ReadConfigValue("CenterSetting", "Server", strServer); CAutoArray ipPorts = strServer.Split(' '); if (strServer.IsNullOrEmpty() || ipPorts.GetCount() != 2 || ipPorts[0] != strServerIP) { result = false; } else { outMask |= 0x2; } return result; } ErrorCodeEnum CCenterSettingEntity::GetParamCurrentUseing(CustomWebUrlConfig& config) { ErrorCodeEnum result(Error_Succeed); CSystemStaticInfo sysInfo; result = GetFunction()->GetSystemStaticInfo(sysInfo); config.strFutureUrl = sysInfo.strTerminalID; CSmartPointer pConfig; CSimpleStringA strServer; result = GetFunction()->OpenConfig(Config_CenterSetting, pConfig); result = pConfig->ReadConfigValue("CenterSetting", "Server", strServer); CAutoArray ipPorts = strServer.Split(' '); if (ipPorts.GetCount() == 2) { config.strAdUrl = ipPorts[0]; } else { config.strAdUrl = ""; } config.index = WEBURL_ITEM_INDEX_CENTERSETTING; config.configFrom = WEBURL_CONFIG_CENTESETTING; config.curStatus = WEBURL_STATUS_PROVIDE; config.useEnv = WEBURL_ENV_ALL; config.strRemark = "root.ini&CenterSetting"; return result; } void CCenterSettingEntity::RemoveAllCenterSettingFiles() { CSimpleStringA strEntityCfgPath; GetFunction()->GetPath("Cfg", strEntityCfgPath); array_header_t* subs = fileutil_get_sub_files_a(strEntityCfgPath); if (subs) { regex_t reg; CSimpleStringA pattern = "CenterSetting\.[a-zA-Z0-9_\\(\\)\\-]*\.ini"; int ret = regcomp(®, pattern, REG_EXTENDED | REG_NOSUB); if (ret) { char ebuff[256]; regerror(ret, ®, ebuff, 256); Dbg("regex failed: %s", ebuff); } else { Dbg("pattern: %s", pattern.GetData()); for (int i = 0; i < subs->nelts; ++i) { char* filenamePath = ARRAY_IDX(subs, i, char*); char* filename = &filenamePath[strEntityCfgPath.GetLength() + 1]; ret = regexec(®, filename, 0, NULL, 0); if (0 == ret) { Dbg("filename %s matched and remove it.", filename); fileutil_delete_file(filenamePath); } } } toolkit_array_free2(subs); } CCenterSettingConn::ClearillegalCenterSettingsFile(strEntityCfgPath); } CSimpleStringA CCenterSettingEntity::GetCenterSettingsACSTypeDownloadUrl() { CSimpleStringA result(true); CSmartPointer pConfig; GetFunction()->OpenConfig(Config_CenterSetting, pConfig); pConfig->ReadConfigValue("CenterSetting", "CenterConfigUrl", result); if (result.IsNullOrEmpty()) { do { CSimpleStringA strFilePath; GetFunction()->GetPath("CenterSetting", strFilePath); if (ExistsFileA(strFilePath)) { LogWarn(Severity_Middle, Error_DataCheck, ERR_MOD_CENTERSETTING_FILE_LEGALITY_UNEXPECTED, "[CenterSetting]CenterConfigUrl empty!"); } } while (false); CSmartPointer pConfigShell; GetFunction()->OpenConfig(Config_Shell, pConfigShell); CSimpleStringA section("CenterSettingsDownloadUrl"); #ifndef UNDER_PRODUCT_ENV section.Append("_ST"); #endif pConfigShell->ReadConfigValue(section, "LAN", result); } return result; } ErrorCodeEnum CCenterSettingEntity::ConfirmCenterSettingsFileAndUpdateIfNecessary(const CSimpleStringA& serverIP) { CSmartPointer pConfig; CSimpleStringA strServer; ErrorCodeEnum result = GetFunction()->OpenConfig(Config_CenterSetting, pConfig); result = pConfig->ReadConfigValue("CenterSetting", "Server", strServer); CAutoArray ipPorts = strServer.Split(' '); if (strServer.IsNullOrEmpty() || ipPorts.GetCount() !=2 || ipPorts[0] != serverIP) { result = Error_FailVerify; } return result; } void CCenterSettingService::Handle_EditWebUrl(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->EditWebUrl(ctx); } void CCenterSettingService::Handle_GetWebUrlList(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->GetWebUrlList(ctx); } void CCenterSettingService::Handle_GetActiveCustomUrl(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->GetActiveCustomUrl(ctx); } void CCenterSettingService::Handle_EditTerminalBackupInfo(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->EditTerminalBackupInfo(ctx); } void CCenterSettingService::Handle_GetTerminalBackupInfoList(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->GetTerminalBackupInfoList(ctx); } void CCenterSettingService::Handle_DownloadCenterFiles(SpReqAnsContext::Pointer ctx) { LOG_FUNCTION(); m_pEntity->DownloadCenterFiles(ctx); } SP_BEGIN_ENTITY_MAP() SP_ENTITY(CCenterSettingEntity) SP_END_ENTITY_MAP()