1 /**
2 * Copyright 2020 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "ps/core/comm_util.h"
18
19 #include <arpa/inet.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22
23 #include <algorithm>
24 #include <cstdio>
25 #include <cstdlib>
26 #include <cstring>
27 #include <functional>
28 #include <iomanip>
29 #include <regex>
30
31 namespace mindspore {
32 namespace ps {
33 namespace core {
34 std::random_device CommUtil::rd;
35 std::mt19937_64 CommUtil::gen(rd());
36 std::uniform_int_distribution<> CommUtil::dis = std::uniform_int_distribution<>{0, 15};
37 std::uniform_int_distribution<> CommUtil::dis2 = std::uniform_int_distribution<>{8, 11};
38
CheckIpWithRegex(const std::string & ip)39 bool CommUtil::CheckIpWithRegex(const std::string &ip) {
40 std::regex pattern(
41 "(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.)"
42 "{3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])");
43 std::smatch res;
44 if (regex_match(ip, res, pattern)) {
45 return true;
46 }
47 return false;
48 }
49
CheckIp(const std::string & ip)50 bool CommUtil::CheckIp(const std::string &ip) {
51 if (!CheckIpWithRegex(ip)) {
52 return false;
53 }
54 uint32_t uAddr = inet_addr(ip.c_str());
55 if (INADDR_NONE == uAddr) {
56 return false;
57 }
58 return true;
59 }
60
CheckHttpUrl(const std::string & http_url)61 bool CommUtil::CheckHttpUrl(const std::string &http_url) {
62 std::regex pattern(
63 "https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)");
64 std::smatch res;
65 if (regex_match(http_url, res, pattern)) {
66 return true;
67 }
68 return false;
69 }
70
CheckPort(const uint16_t & port)71 bool CommUtil::CheckPort(const uint16_t &port) {
72 if (port > kMaxPort) {
73 MS_LOG(ERROR) << "The range of port should be 1 to 65535.";
74 return false;
75 }
76 return true;
77 }
78
GetAvailableInterfaceAndIP(std::string * interface,std::string * ip)79 void CommUtil::GetAvailableInterfaceAndIP(std::string *interface, std::string *ip) {
80 MS_EXCEPTION_IF_NULL(interface);
81 MS_EXCEPTION_IF_NULL(ip);
82 struct ifaddrs *if_address = nullptr;
83 struct ifaddrs *ifa = nullptr;
84
85 interface->clear();
86 ip->clear();
87 if (getifaddrs(&if_address) == -1) {
88 MS_LOG(WARNING) << "Get ifaddrs failed.";
89 }
90 for (ifa = if_address; ifa != nullptr; ifa = ifa->ifa_next) {
91 if (ifa->ifa_addr == nullptr) {
92 continue;
93 }
94
95 if (ifa->ifa_addr->sa_family == AF_INET && (ifa->ifa_flags & IFF_LOOPBACK) == 0) {
96 char address_buffer[INET_ADDRSTRLEN] = {0};
97 void *sin_addr_ptr = &(reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr))->sin_addr;
98 MS_EXCEPTION_IF_NULL(sin_addr_ptr);
99 const char *net_ptr = inet_ntop(AF_INET, sin_addr_ptr, address_buffer, INET_ADDRSTRLEN);
100 MS_EXCEPTION_IF_NULL(net_ptr);
101
102 *ip = address_buffer;
103 *interface = ifa->ifa_name;
104 break;
105 }
106 }
107 MS_EXCEPTION_IF_NULL(if_address);
108 freeifaddrs(if_address);
109 }
110
GetLoopBackInterfaceName()111 std::string CommUtil::GetLoopBackInterfaceName() {
112 struct ifaddrs *if_address = nullptr;
113 struct ifaddrs *ifa = nullptr;
114
115 if (getifaddrs(&if_address) == -1) {
116 MS_LOG(WARNING) << "Get ifaddrs failed.";
117 }
118 for (ifa = if_address; ifa != nullptr; ifa = ifa->ifa_next) {
119 if (ifa->ifa_addr == nullptr) {
120 continue;
121 }
122
123 if (ifa->ifa_flags & IFF_LOOPBACK) {
124 MS_LOG(INFO) << "Loop back interface name is " << ifa->ifa_name;
125 return ifa->ifa_name;
126 }
127 }
128 MS_EXCEPTION_IF_NULL(if_address);
129 freeifaddrs(if_address);
130 return "";
131 }
132
GenerateUUID()133 std::string CommUtil::GenerateUUID() {
134 std::stringstream ss;
135 int i;
136 ss << std::hex;
137 for (i = 0; i < kGroup1RandomLength; i++) {
138 ss << dis(gen);
139 }
140 ss << "-";
141 for (i = 0; i < kGroup2RandomLength; i++) {
142 ss << dis(gen);
143 }
144 ss << "-4";
145 for (i = 0; i < kGroup3RandomLength - 1; i++) {
146 ss << dis(gen);
147 }
148 ss << "-";
149 ss << dis2(gen);
150 for (i = 0; i < kGroup4RandomLength - 1; i++) {
151 ss << dis(gen);
152 }
153 ss << "-";
154 for (i = 0; i < kGroup5RandomLength; i++) {
155 ss << dis(gen);
156 }
157 return ss.str();
158 }
159
NodeRoleToString(const NodeRole & role)160 std::string CommUtil::NodeRoleToString(const NodeRole &role) {
161 switch (role) {
162 case NodeRole::SCHEDULER:
163 return "SCHEDULER";
164 case NodeRole::SERVER:
165 return "SERVER";
166 case NodeRole::WORKER:
167 return "WORKER";
168 default:
169 MS_LOG(EXCEPTION) << "The node role:" << role << " is illegal!";
170 }
171 }
172
StringToNodeRole(const std::string & roleStr)173 NodeRole CommUtil::StringToNodeRole(const std::string &roleStr) {
174 if (roleStr == "SCHEDULER") {
175 return NodeRole::SCHEDULER;
176 } else if (roleStr == "SERVER") {
177 return NodeRole::SERVER;
178 } else if (roleStr == "WORKER") {
179 return NodeRole::WORKER;
180 } else {
181 MS_LOG(EXCEPTION) << "The node role string:" << roleStr << " is illegal!";
182 }
183 }
ValidateRankId(const enum NodeRole & node_role,const uint32_t & rank_id,const int32_t & total_worker_num,const int32_t & total_server_num)184 bool CommUtil::ValidateRankId(const enum NodeRole &node_role, const uint32_t &rank_id, const int32_t &total_worker_num,
185 const int32_t &total_server_num) {
186 if (node_role == NodeRole::SERVER && (rank_id > IntToUint(total_server_num) - 1)) {
187 return false;
188 } else if (node_role == NodeRole::WORKER && (rank_id > IntToUint(total_worker_num) - 1)) {
189 return false;
190 }
191 return true;
192 }
193
Retry(const std::function<bool ()> & func,size_t max_attempts,size_t interval_milliseconds)194 bool CommUtil::Retry(const std::function<bool()> &func, size_t max_attempts, size_t interval_milliseconds) {
195 for (size_t attempt = 0; attempt < max_attempts; ++attempt) {
196 if (func()) {
197 return true;
198 }
199 std::this_thread::sleep_for(std::chrono::milliseconds(interval_milliseconds));
200 }
201 return false;
202 }
203
LogCallback(int severity,const char * msg)204 void CommUtil::LogCallback(int severity, const char *msg) {
205 MS_EXCEPTION_IF_NULL(msg);
206 switch (severity) {
207 case EVENT_LOG_MSG:
208 MS_LOG(INFO) << kLibeventLogPrefix << msg;
209 break;
210 case EVENT_LOG_WARN:
211 MS_LOG(WARNING) << kLibeventLogPrefix << msg;
212 break;
213 case EVENT_LOG_ERR:
214 MS_LOG(ERROR) << kLibeventLogPrefix << msg;
215 break;
216 default:
217 break;
218 }
219 }
220
IsFileExists(const std::string & file)221 bool CommUtil::IsFileExists(const std::string &file) { return access(file.c_str(), F_OK) != -1; }
222
IsFileReadable(const std::string & file)223 bool CommUtil::IsFileReadable(const std::string &file) { return access(file.c_str(), R_OK) != -1; }
224
IsFileEmpty(const std::string & file)225 bool CommUtil::IsFileEmpty(const std::string &file) {
226 if (!IsFileExists(file)) {
227 MS_LOG(EXCEPTION) << "The file does not exist, file path: " << file;
228 }
229
230 std::ifstream fs(file.c_str());
231 std::string str;
232 fs >> str;
233 fs.close();
234
235 return str.empty();
236 }
237
CreateDirectory(const std::string & directoryPath)238 bool CommUtil::CreateDirectory(const std::string &directoryPath) {
239 uint32_t dirPathLen = SizeToUint(directoryPath.length());
240 constexpr uint32_t MAX_PATH_LEN = 512;
241 if (dirPathLen > MAX_PATH_LEN) {
242 return false;
243 }
244 char tmpDirPath[MAX_PATH_LEN] = {0};
245 for (uint32_t i = 0; i < dirPathLen; ++i) {
246 tmpDirPath[i] = directoryPath[i];
247 if (tmpDirPath[i] == '/') {
248 if (access(tmpDirPath, 0) != 0) {
249 int32_t ret = mkdir(tmpDirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
250 if (ret != 0) {
251 return false;
252 }
253 }
254 }
255 }
256 return true;
257 }
258
ClusterStateToString(const ClusterState & state)259 std::string CommUtil::ClusterStateToString(const ClusterState &state) {
260 if (state < SizeToInt(kClusterState.size())) {
261 return kClusterState.at(state);
262 } else {
263 return std::to_string(state);
264 }
265 }
266
ParseConfig(const Configuration & config,const std::string & key)267 std::string CommUtil::ParseConfig(const Configuration &config, const std::string &key) {
268 if (!config.IsInitialized()) {
269 MS_LOG(INFO) << "The config is not initialized.";
270 return "";
271 }
272
273 if (!const_cast<Configuration &>(config).Exists(key)) {
274 MS_LOG(INFO) << "The key:" << key << " is not exist.";
275 return "";
276 }
277
278 std::string path = config.GetString(key, "");
279 return path;
280 }
281
verifyCertTimeStamp(const X509 * cert)282 bool CommUtil::verifyCertTimeStamp(const X509 *cert) {
283 ASN1_TIME *start = X509_getm_notBefore(cert);
284 ASN1_TIME *end = X509_getm_notAfter(cert);
285
286 int day = 0;
287 int sec = 0;
288 int ret = ASN1_TIME_diff(&day, &sec, start, NULL);
289 if (ret != 1) {
290 return false;
291 }
292
293 if (day < 0 || sec < 0) {
294 MS_LOG(ERROR) << "cert start time is later than now time.";
295 return false;
296 }
297 day = 0;
298 sec = 0;
299 ret = ASN1_TIME_diff(&day, &sec, NULL, end);
300 if (ret != 1) {
301 return false;
302 }
303
304 if (day < 0 || sec < 0) {
305 MS_LOG(ERROR) << "cert end time is sooner than now time.";
306 return false;
307 }
308 return true;
309 }
310
VerifyCertTime(const X509 * cert,int64_t time)311 bool CommUtil::VerifyCertTime(const X509 *cert, int64_t time) {
312 MS_EXCEPTION_IF_NULL(cert);
313 ASN1_TIME *start = X509_getm_notBefore(cert);
314 ASN1_TIME *end = X509_getm_notAfter(cert);
315 MS_EXCEPTION_IF_NULL(start);
316 MS_EXCEPTION_IF_NULL(end);
317 int day = 0;
318 int sec = 0;
319 if (!ASN1_TIME_diff(&day, &sec, start, NULL)) {
320 MS_LOG(WARNING) << "ASN1 time diff failed.";
321 return false;
322 }
323
324 if (day < 0 || sec < 0) {
325 MS_LOG(WARNING) << "Cert start time is later than now time.";
326 return false;
327 }
328 day = 0;
329 sec = 0;
330
331 if (!ASN1_TIME_diff(&day, &sec, NULL, end)) {
332 MS_LOG(WARNING) << "ASN1 time diff failed.";
333 return false;
334 }
335
336 int64_t interval = kCertExpireWarningTimeInDay;
337 if (time > 0) {
338 interval = time;
339 }
340
341 if (day < LongToInt(interval) && day >= 0) {
342 MS_LOG(WARNING) << "The certificate will expire in " << day << " days and " << sec << " seconds.";
343 } else if (day < 0 || sec < 0) {
344 MS_LOG(WARNING) << "The certificate has expired.";
345 return false;
346 }
347 return true;
348 }
349
VerifyCRL(const X509 * cert,const std::string & crl_path,X509_CRL ** crl)350 bool CommUtil::VerifyCRL(const X509 *cert, const std::string &crl_path, X509_CRL **crl) {
351 MS_ERROR_IF_NULL_W_RET_VAL(cert, false);
352 MS_ERROR_IF_NULL_W_RET_VAL(crl, false);
353
354 EVP_PKEY *evp_pkey = X509_get_pubkey(const_cast<X509 *>(cert));
355 MS_ERROR_IF_NULL_W_RET_VAL(evp_pkey, false);
356 BIO *bio = BIO_new_file(crl_path.c_str(), "r");
357 MS_ERROR_IF_NULL_W_RET_VAL(bio, false);
358 *crl = PEM_read_bio_X509_CRL(bio, nullptr, nullptr, nullptr);
359 MS_ERROR_IF_NULL_W_RET_VAL(*crl, false);
360
361 int ret = X509_CRL_verify(*crl, evp_pkey);
362 if (ret == 1) {
363 MS_LOG(INFO) << "VerifyCRL success.";
364 } else if (ret == 0) {
365 MS_LOG(ERROR) << "Verify CRL failed.";
366 } else {
367 MS_LOG(ERROR) << "CRL cannot be verified.";
368 }
369 BIO_free_all(bio);
370 EVP_PKEY_free(evp_pkey);
371 return ret == 1;
372 }
373
VerifyCommonName(const X509 * caCert,const X509 * subCert)374 bool CommUtil::VerifyCommonName(const X509 *caCert, const X509 *subCert) {
375 MS_EXCEPTION_IF_NULL(caCert);
376 MS_EXCEPTION_IF_NULL(subCert);
377 char caSubjectCN[256] = "";
378 char subIssuerCN[256] = "";
379
380 X509_NAME *caSubjectX509CN = X509_get_subject_name(caCert);
381 X509_NAME *subIssuerX509CN = X509_get_issuer_name(subCert);
382
383 int ret = X509_NAME_get_text_by_NID(caSubjectX509CN, NID_commonName, caSubjectCN, sizeof(caSubjectCN));
384 if (ret < 0) {
385 return false;
386 }
387 ret = X509_NAME_get_text_by_NID(subIssuerX509CN, NID_commonName, subIssuerCN, sizeof(subIssuerCN));
388 if (ret < 0) {
389 return false;
390 }
391
392 std::string caSubjectCNStr = caSubjectCN;
393 std::string subIssuerCNStr = subIssuerCN;
394
395 if (caSubjectCNStr != subIssuerCNStr) {
396 MS_LOG(EXCEPTION) << "root CA cert subject cn is not equal with equip CA cert issuer cn.";
397 return false;
398 }
399 return true;
400 }
401
Split(const std::string & s,char delim)402 std::vector<std::string> CommUtil::Split(const std::string &s, char delim) {
403 std::vector<std::string> res;
404 std::stringstream ss(s);
405 std::string item;
406
407 while (getline(ss, item, delim)) {
408 res.push_back(item);
409 }
410 return res;
411 }
412
VerifyCipherList(const std::vector<std::string> & list)413 bool CommUtil::VerifyCipherList(const std::vector<std::string> &list) {
414 for (auto &item : list) {
415 if (!kCiphers.count(item)) {
416 MS_LOG(WARNING) << "The ciphter:" << item << " is not supported.";
417 return false;
418 }
419 }
420 return true;
421 }
422
verifyCertKeyID(const X509 * caCert,const X509 * subCert)423 bool CommUtil::verifyCertKeyID(const X509 *caCert, const X509 *subCert) {
424 MS_EXCEPTION_IF_NULL(caCert);
425 MS_EXCEPTION_IF_NULL(subCert);
426 int crit = 0;
427 ASN1_OCTET_STRING *skid =
428 reinterpret_cast<ASN1_OCTET_STRING *>(X509_get_ext_d2i(caCert, NID_subject_key_identifier, &crit, NULL));
429 MS_EXCEPTION_IF_NULL(skid);
430 const size_t keyidLen = 512;
431 char subject_keyid[keyidLen] = {0};
432 for (int i = 0; i < skid->length; i++) {
433 char keyid[8] = {0};
434 size_t base = keyidLen;
435 if (sprintf_s(keyid, sizeof(keyid), "%x ", (uint32_t)skid->data[i]) == -1) {
436 return false;
437 }
438 errno_t ret = strcat_s(subject_keyid, base, keyid);
439 if (ret != EOK) {
440 return false;
441 }
442 }
443
444 AUTHORITY_KEYID *akeyid =
445 reinterpret_cast<AUTHORITY_KEYID *>(X509_get_ext_d2i(subCert, NID_authority_key_identifier, &crit, NULL));
446 MS_EXCEPTION_IF_NULL(akeyid);
447 MS_EXCEPTION_IF_NULL(akeyid->keyid);
448 char issuer_keyid[keyidLen] = {0};
449 for (int i = 0; i < akeyid->keyid->length; i++) {
450 char keyid[8] = {0};
451 size_t base = keyidLen;
452 if (sprintf_s(keyid, sizeof(keyid), "%x ", (uint32_t)(akeyid->keyid->data[i])) == -1) {
453 return false;
454 }
455 int ret = strcat_s(issuer_keyid, base, keyid);
456 if (ret != EOK) {
457 return false;
458 }
459 }
460
461 std::string subject_keyid_str = subject_keyid;
462 std::string issuer_keyid_str = issuer_keyid;
463 if (subject_keyid_str != issuer_keyid_str) {
464 return false;
465 }
466 return true;
467 }
468
verifySingature(const X509 * caCert,const X509 * subCert)469 bool CommUtil::verifySingature(const X509 *caCert, const X509 *subCert) {
470 MS_EXCEPTION_IF_NULL(caCert);
471 MS_EXCEPTION_IF_NULL(subCert);
472 EVP_PKEY *caCertPubKey = X509_get_pubkey(const_cast<X509 *>(caCert));
473
474 int ret = 0;
475 ret = X509_verify(const_cast<X509 *>(subCert), caCertPubKey);
476 if (ret != 1) {
477 EVP_PKEY_free(caCertPubKey);
478 MS_LOG(ERROR) << "sub cert verify is failed, error code " << ret;
479 return false;
480 }
481 MS_LOG(INFO) << "verifyCAChain success.";
482 EVP_PKEY_free(caCertPubKey);
483 return true;
484 }
485
verifyExtendedAttributes(const X509 * caCert)486 bool CommUtil::verifyExtendedAttributes(const X509 *caCert) {
487 MS_EXCEPTION_IF_NULL(caCert);
488 int cirt = 0;
489 BASIC_CONSTRAINTS *bcons =
490 reinterpret_cast<BASIC_CONSTRAINTS *>(X509_get_ext_d2i(caCert, NID_basic_constraints, &cirt, nullptr));
491 if (bcons == nullptr) {
492 return false;
493 }
494 if (!bcons->ca) {
495 MS_LOG(ERROR) << "Subject Type is End Entity.";
496 return false;
497 }
498 MS_LOG(INFO) << "Subject Type is CA.";
499 return true;
500 }
501
InitOpensslLib()502 void CommUtil::InitOpensslLib() {
503 if (!SSL_library_init()) {
504 MS_LOG(EXCEPTION) << "SSL_library_init failed.";
505 }
506 if (!ERR_load_crypto_strings()) {
507 MS_LOG(EXCEPTION) << "ERR_load_crypto_strings failed.";
508 }
509 if (!SSL_load_error_strings()) {
510 MS_LOG(EXCEPTION) << "SSL_load_error_strings failed.";
511 }
512 if (!OpenSSL_add_all_algorithms()) {
513 MS_LOG(EXCEPTION) << "OpenSSL_add_all_algorithms failed.";
514 }
515 }
516
verifyCertPipeline(const X509 * caCert,const X509 * subCert)517 void CommUtil::verifyCertPipeline(const X509 *caCert, const X509 *subCert) {
518 if (!CommUtil::VerifyCommonName(caCert, subCert)) {
519 MS_LOG(EXCEPTION) << "Verify common name failed.";
520 }
521
522 if (!CommUtil::verifySingature(caCert, subCert)) {
523 MS_LOG(EXCEPTION) << "Verify Signature failed.";
524 }
525
526 if (!CommUtil::verifyExtendedAttributes(caCert)) {
527 MS_LOG(EXCEPTION) << "Verify Extended Attributes failed.";
528 }
529
530 if (!CommUtil::verifyCertKeyID(caCert, subCert)) {
531 MS_LOG(EXCEPTION) << "Verify Cert KeyID failed.";
532 }
533
534 if (!CommUtil::verifyCertTimeStamp(caCert) || !CommUtil::verifyCertTimeStamp(subCert)) {
535 MS_LOG(EXCEPTION) << "Verify Cert Time failed.";
536 }
537 }
538
checkCRLTime(const std::string & crlPath)539 bool CommUtil::checkCRLTime(const std::string &crlPath) {
540 if (!IsFileExists(crlPath)) {
541 return true;
542 }
543 BIO *bio = BIO_new_file(crlPath.c_str(), "r");
544 if (bio == nullptr) {
545 return true;
546 }
547 bool result = true;
548 X509_CRL *crl = nullptr;
549 do {
550 crl = PEM_read_bio_X509_CRL(bio, nullptr, nullptr, nullptr);
551 if (crl == nullptr) {
552 MS_LOG(WARNING) << "crl is nullptr. return true.";
553 result = true;
554 break;
555 }
556 const ASN1_TIME *lastUpdate = X509_CRL_get0_lastUpdate(crl);
557 const ASN1_TIME *nextUpdate = X509_CRL_get0_nextUpdate(crl);
558
559 int day = 0;
560 int sec = 0;
561 int ret = ASN1_TIME_diff(&day, &sec, lastUpdate, NULL);
562 if (ret != 1) {
563 result = false;
564 break;
565 }
566
567 if (day < 0 || sec < 0) {
568 MS_LOG(ERROR) << "crl start time is later than now time.";
569 result = false;
570 break;
571 }
572 day = 0;
573 sec = 0;
574 ret = ASN1_TIME_diff(&day, &sec, NULL, nextUpdate);
575 if (ret != 1) {
576 result = false;
577 break;
578 }
579
580 if (day < 0 || sec < 0) {
581 MS_LOG(WARNING) << "crl update time is sooner than now time. please update crl";
582 }
583 MS_LOG(INFO) << "verifyCRL time success.";
584 } while (0);
585
586 X509_CRL_free(crl);
587 BIO_free_all(bio);
588 return result;
589 }
590
BoolToString(bool alive)591 std::string CommUtil::BoolToString(bool alive) {
592 if (alive) {
593 return "True";
594 } else {
595 return "False";
596 }
597 }
598
StringToBool(const std::string & alive)599 bool CommUtil::StringToBool(const std::string &alive) {
600 if (alive == "True") {
601 return true;
602 } else if (alive == "False") {
603 return false;
604 }
605 return false;
606 }
607
GetNowTime()608 Time CommUtil::GetNowTime() {
609 ps::core::Time time;
610 auto time_now = std::chrono::system_clock::now();
611 std::time_t tt = std::chrono::system_clock::to_time_t(time_now);
612 struct tm ptm;
613 (void)localtime_r(&tt, &ptm);
614 std::ostringstream time_mill_oss;
615 time_mill_oss << std::put_time(&ptm, "%Y-%m-%d %H:%M:%S");
616
617 // calculate millisecond, the format of time_str_mill is 2022-01-10 20:22:20.067
618 auto second_time_stamp = std::chrono::duration_cast<std::chrono::seconds>(time_now.time_since_epoch());
619 auto mill_time_stamp = std::chrono::duration_cast<std::chrono::milliseconds>(time_now.time_since_epoch());
620 auto ms_stamp = mill_time_stamp - second_time_stamp;
621 time_mill_oss << "." << std::setfill('0') << std::setw(kMillSecondLength) << ms_stamp.count();
622
623 time.time_stamp = LongToSize(mill_time_stamp.count());
624 time.time_str_mill = time_mill_oss.str();
625 return time;
626 }
627
ParseAndCheckConfigJson(Configuration * file_configuration,const std::string & key,FileConfig * file_config)628 bool CommUtil::ParseAndCheckConfigJson(Configuration *file_configuration, const std::string &key,
629 FileConfig *file_config) {
630 MS_EXCEPTION_IF_NULL(file_configuration);
631 MS_EXCEPTION_IF_NULL(file_config);
632 if (!file_configuration->Exists(key)) {
633 MS_LOG(WARNING) << key << " config is not set. Don't write.";
634 return false;
635 } else {
636 std::string value = file_configuration->Get(key, "");
637 nlohmann::json value_json;
638 try {
639 value_json = nlohmann::json::parse(value);
640 } catch (const std::exception &e) {
641 MS_LOG(EXCEPTION) << "The hyper-parameter data is not in json format.";
642 }
643 // Parse the storage type.
644 uint32_t storage_type = ps::core::CommUtil::JsonGetKeyWithException<uint32_t>(value_json, ps::kStoreType);
645 if (std::to_string(storage_type) != ps::kFileStorage) {
646 MS_LOG(EXCEPTION) << "Storage type " << storage_type << " is not supported.";
647 }
648 // Parse storage file path.
649 std::string file_path = ps::core::CommUtil::JsonGetKeyWithException<std::string>(value_json, ps::kStoreFilePath);
650 file_config->storage_type = storage_type;
651 file_config->storage_file_path = file_path;
652 }
653 return true;
654 }
655 } // namespace core
656 } // namespace ps
657 } // namespace mindspore
658