You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

common.cc 14 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /**
  2. * Copyright 2020-2021 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. #include "debug/common.h"
  17. #include <memory>
  18. #include <iomanip>
  19. #include <optional>
  20. #include <fstream>
  21. #include "utils/system/env.h"
  22. #include "utils/system/file_system.h"
  23. #include "utils/log_adapter.h"
  24. #include "utils/file_utils.h"
  25. #include "utils/utils.h"
  26. namespace mindspore {
  27. std::optional<std::string> Common::CreatePrefixPath(const std::string &input_path) {
  28. std::optional<std::string> prefix_path;
  29. std::optional<std::string> file_name;
  30. FileUtils::SplitDirAndFileName(input_path, &prefix_path, &file_name);
  31. if (!file_name.has_value()) {
  32. MS_LOG(ERROR) << "Cannot get file_name from: " << input_path;
  33. return std::nullopt;
  34. }
  35. auto file_name_str = file_name.value();
  36. #if defined(SYSTEM_ENV_POSIX)
  37. if (file_name_str.length() > NAME_MAX) {
  38. MS_LOG(ERROR) << "The length of file name: " << file_name_str.length() << " exceeds limit: " << NAME_MAX;
  39. return std::nullopt;
  40. }
  41. #endif
  42. std::string prefix_path_str;
  43. if (prefix_path.has_value()) {
  44. auto create_prefix_path = FileUtils::CreateNotExistDirs(prefix_path.value());
  45. if (!create_prefix_path.has_value()) {
  46. return std::nullopt;
  47. }
  48. prefix_path_str = create_prefix_path.value();
  49. } else {
  50. auto pwd_path = FileUtils::GetRealPath("./");
  51. if (!pwd_path.has_value()) {
  52. MS_LOG(ERROR) << "Cannot get pwd path";
  53. return std::nullopt;
  54. }
  55. prefix_path_str = pwd_path.value();
  56. }
  57. return std::string(prefix_path_str + "/" + file_name_str);
  58. }
  59. bool Common::CommonFuncForConfigPath(const std::string &default_path, const std::string &env_path, std::string *value) {
  60. MS_EXCEPTION_IF_NULL(value);
  61. value->clear();
  62. if (!env_path.empty()) {
  63. char real_path[PATH_MAX] = {0};
  64. #if defined(SYSTEM_ENV_WINDOWS)
  65. if (_fullpath(real_path, common::SafeCStr(env_path), PATH_MAX) == nullptr) {
  66. MS_LOG(ERROR) << "The dir " << env_path << " does not exist.";
  67. return false;
  68. }
  69. *value = real_path;
  70. return true;
  71. #else
  72. if (realpath(env_path.c_str(), real_path)) {
  73. *value = real_path;
  74. return true;
  75. }
  76. MS_LOG(ERROR) << "Invalid env path, path : " << env_path;
  77. return false;
  78. #endif
  79. }
  80. *value = default_path;
  81. return true;
  82. }
  83. std::optional<std::string> Common::GetRealPath(const std::string &input_path) {
  84. if (input_path.length() >= PATH_MAX) {
  85. MS_LOG(ERROR) << "The length of path: " << input_path << " exceeds limit: " << PATH_MAX;
  86. return std::nullopt;
  87. }
  88. auto path_split_pos = input_path.find_last_of('/');
  89. if (path_split_pos == std::string::npos) {
  90. path_split_pos = input_path.find_last_of('\\');
  91. }
  92. // get real path
  93. char real_path[PATH_MAX] = {0};
  94. // input_path is dir + file_name
  95. if (path_split_pos != std::string::npos) {
  96. std::string prefix_path = input_path.substr(0, path_split_pos);
  97. std::string file_name = input_path.substr(path_split_pos);
  98. if (!CreateNotExistDirs(prefix_path)) {
  99. MS_LOG(ERROR) << "Create dir " << prefix_path << " Failed!";
  100. return std::nullopt;
  101. }
  102. #if defined(SYSTEM_ENV_POSIX)
  103. if (file_name.length() > NAME_MAX) {
  104. MS_LOG(ERROR) << "The length of file name : " << file_name.length() << " exceeds limit: " << NAME_MAX;
  105. return std::nullopt;
  106. }
  107. if (realpath(common::SafeCStr(prefix_path), real_path) == nullptr) {
  108. MS_LOG(ERROR) << "The dir " << prefix_path << " does not exist.";
  109. return std::nullopt;
  110. }
  111. #elif defined(SYSTEM_ENV_WINDOWS)
  112. if (_fullpath(real_path, common::SafeCStr(prefix_path), PATH_MAX) == nullptr) {
  113. MS_LOG(ERROR) << "The dir " << prefix_path << " does not exist.";
  114. return std::nullopt;
  115. }
  116. #endif
  117. return std::string(real_path) + file_name;
  118. }
  119. // input_path is only file_name
  120. #if defined(SYSTEM_ENV_POSIX)
  121. if (input_path.length() > NAME_MAX) {
  122. MS_LOG(ERROR) << "The length of file name : " << input_path.length() << " exceeds limit: " << NAME_MAX;
  123. return std::nullopt;
  124. }
  125. if (realpath(common::SafeCStr(input_path), real_path) == nullptr) {
  126. MS_LOG(INFO) << "The file " << input_path << " does not exist, it will be created.";
  127. }
  128. #elif defined(SYSTEM_ENV_WINDOWS)
  129. if (_fullpath(real_path, common::SafeCStr(input_path), PATH_MAX) == nullptr) {
  130. MS_LOG(INFO) << "The file " << input_path << " does not exist, it will be created.";
  131. }
  132. #endif
  133. return std::string(real_path);
  134. }
  135. bool Common::CreateNotExistDirs(const std::string &path) {
  136. std::shared_ptr<system::FileSystem> fs = system::Env::GetFileSystem();
  137. MS_EXCEPTION_IF_NULL(fs);
  138. char temp_path[PATH_MAX] = {0};
  139. if (path.length() >= PATH_MAX) {
  140. MS_LOG(ERROR) << "Path length is equal to or max than " << PATH_MAX;
  141. return false;
  142. }
  143. for (uint32_t i = 0; i < path.length(); i++) {
  144. temp_path[i] = path[i];
  145. if (temp_path[i] == '\\' || temp_path[i] == '/') {
  146. if (i != 0) {
  147. char tmp_char = temp_path[i];
  148. temp_path[i] = '\0';
  149. std::string path_handle(temp_path);
  150. if (!fs->FileExist(path_handle)) {
  151. MS_LOG(INFO) << "Dir " << path_handle << " does not exit, creating...";
  152. if (!fs->CreateDir(path_handle)) {
  153. MS_LOG(ERROR) << "Create " << path_handle << " dir error";
  154. return false;
  155. }
  156. }
  157. temp_path[i] = tmp_char;
  158. }
  159. }
  160. }
  161. if (!fs->FileExist(path)) {
  162. MS_LOG(INFO) << "Dir " << path << " does not exit, creating...";
  163. if (!fs->CreateDir(path)) {
  164. MS_LOG(ERROR) << "Create " << path << " dir error";
  165. return false;
  166. }
  167. }
  168. return true;
  169. }
  170. std::optional<std::string> Common::GetConfigFile(const std::string &env) {
  171. if (env.empty()) {
  172. MS_LOG(EXCEPTION) << "Invalid env";
  173. }
  174. auto config_path_str = std::getenv(env.c_str());
  175. if (config_path_str == nullptr) {
  176. MS_LOG(ERROR) << "Please export env:" << env;
  177. return std::nullopt;
  178. }
  179. MS_LOG(INFO) << "Async Dump Getenv env:" << env << "=" << config_path_str;
  180. auto real_path = FileUtils::GetRealPath(common::SafeCStr(config_path_str));
  181. if (!real_path.has_value()) {
  182. MS_LOG(ERROR) << "Can't get real_path";
  183. return std::nullopt;
  184. }
  185. std::string dump_config_file = real_path.value();
  186. std::shared_ptr<system::FileSystem> fs = system::Env::GetFileSystem();
  187. MS_EXCEPTION_IF_NULL(fs);
  188. if (!fs->FileExist(dump_config_file)) {
  189. MS_LOG(ERROR) << dump_config_file << " not exist.";
  190. return std::nullopt;
  191. }
  192. auto point_pos = dump_config_file.find_last_of('.');
  193. if (point_pos == std::string::npos) {
  194. MS_LOG(EXCEPTION) << "Invalid json file name:" << dump_config_file;
  195. }
  196. auto suffix = dump_config_file.substr(point_pos + 1);
  197. if (suffix != "json") {
  198. MS_LOG(EXCEPTION) << "[DataDump] dump config file suffix only supports json! But got:." << suffix;
  199. }
  200. return dump_config_file;
  201. }
  202. bool Common::IsStrLengthValid(const std::string &str, size_t length_limit, const std::string &error_message) {
  203. auto len_str = str.length();
  204. if (len_str > length_limit) {
  205. MS_LOG(ERROR) << error_message << "The length is " << str.length() << ", exceeding the limit of " << length_limit
  206. << ".";
  207. return false;
  208. }
  209. return true;
  210. }
  211. bool Common::IsEveryFilenameValid(const std::string &path, size_t length_limit, const std::string &error_message) {
  212. if (path.empty()) {
  213. MS_LOG(WARNING) << error_message << "The path is empty.";
  214. return false;
  215. }
  216. size_t len_path = path.length();
  217. size_t left_pos = 0;
  218. for (size_t i = 0; i < len_path; i++) {
  219. if (i != 0) {
  220. if (path[i] == '\\' || path[i] == '/') {
  221. auto cur_len = i - left_pos;
  222. if (cur_len > length_limit) {
  223. MS_LOG(WARNING) << error_message << "The name length of '" << path.substr(left_pos, cur_len) << "' is "
  224. << cur_len << ". It is out of the limit which is " << length_limit << ".";
  225. return false;
  226. }
  227. left_pos = i + 1;
  228. }
  229. }
  230. }
  231. if (!(path[len_path - 1] == '\\' || path[len_path - 1] == '/')) {
  232. auto cur_len = len_path - left_pos;
  233. if (cur_len > length_limit) {
  234. MS_LOG(WARNING) << error_message << "The name length of '" << path.substr(left_pos, cur_len) << "' is " << cur_len
  235. << ". It is out of the limit which is " << length_limit << ".";
  236. return false;
  237. }
  238. }
  239. return true;
  240. }
  241. bool Common::IsPathValid(const std::string &path, size_t length_limit, const std::string &error_message) {
  242. std::string err_msg = "Detail: ";
  243. if (!error_message.empty()) {
  244. err_msg = error_message + " " + err_msg;
  245. }
  246. if (path.empty()) {
  247. MS_LOG(WARNING) << err_msg << "The path is empty.";
  248. return false;
  249. }
  250. if (!IsStrLengthValid(path, length_limit, err_msg)) {
  251. return false;
  252. }
  253. if (!std::all_of(path.begin(), path.end(), [](char c) {
  254. return ::isalpha(c) || ::isdigit(c) || c == '-' || c == '_' || c == '.' || c == '/';
  255. })) {
  256. MS_LOG(ERROR) << err_msg << "The path only supports alphabets, digit or {'-', '_', '.', '/'}, but got:" << path
  257. << ".";
  258. return false;
  259. }
  260. if (path[0] != '/') {
  261. MS_LOG(ERROR) << err_msg << "The path only supports absolute path and should start with '/'.";
  262. return false;
  263. }
  264. if (!IsEveryFilenameValid(path, MAX_OS_FILENAME_LENGTH, err_msg)) {
  265. return false;
  266. }
  267. return true;
  268. }
  269. bool Common::IsFilenameValid(const std::string &filename, size_t length_limit, const std::string &error_message) {
  270. std::string err_msg = "Detail: ";
  271. if (!error_message.empty()) {
  272. err_msg = error_message + " " + err_msg;
  273. }
  274. if (filename.empty()) {
  275. MS_LOG(WARNING) << err_msg << "The filename is empty.";
  276. return false;
  277. }
  278. if (!IsStrLengthValid(filename, length_limit, err_msg)) {
  279. return false;
  280. }
  281. auto func = [](char c) { return ::isalpha(c) || ::isdigit(c) || c == '-' || c == '_' || c == '.'; };
  282. if (!std::all_of(filename.begin(), filename.end(), func)) {
  283. MS_LOG(ERROR) << err_msg << "The filename only supports alphabets, digit or {'-', '_', '.'}, but got:" << filename
  284. << ".";
  285. return false;
  286. }
  287. return true;
  288. }
  289. std::string Common::AddId(const std::string &filename, const std::string &suffix) {
  290. static size_t g_id = 0;
  291. std::ostringstream s;
  292. auto i = filename.rfind(suffix);
  293. const int spaces = 4;
  294. if (i >= filename.size()) {
  295. s << filename;
  296. s << "_" << std::setfill('0') << std::setw(spaces) << g_id;
  297. } else {
  298. s << filename.substr(0, i);
  299. s << "_" << std::setfill('0') << std::setw(spaces) << g_id;
  300. if (i + 1 < filename.size()) {
  301. s << filename.substr(i);
  302. }
  303. }
  304. g_id++;
  305. return s.str();
  306. }
  307. bool Common::SaveStringToFile(const std::string filename, const std::string string_info) {
  308. if (filename.size() >= PATH_MAX) {
  309. MS_LOG(ERROR) << "File path " << filename << " is too long.";
  310. return false;
  311. }
  312. auto real_path = GetRealPath(filename);
  313. if (!real_path.has_value()) {
  314. MS_LOG(ERROR) << "Get real path failed. path=" << filename;
  315. return false;
  316. }
  317. ChangeFileMode(real_path.value(), S_IRWXU);
  318. std::ofstream ofs;
  319. ofs.open(real_path.value());
  320. if (!ofs.is_open()) {
  321. MS_LOG(ERROR) << "Open dump file '" << real_path.value() << "' failed!"
  322. << " Errno:" << errno << " ErrInfo:" << strerror(errno);
  323. return false;
  324. }
  325. ofs << string_info << std::endl;
  326. ofs.close();
  327. // set file mode to read only by user
  328. ChangeFileMode(real_path.value(), S_IRUSR);
  329. return true;
  330. }
  331. bool Common::FileExists(const std::string &filepath) {
  332. std::ifstream f(filepath);
  333. bool cache_file_existed = f.good();
  334. f.close();
  335. return cache_file_existed;
  336. }
  337. struct GlogLogDirRegister {
  338. GlogLogDirRegister() {
  339. const char *logtostderr = std::getenv("GLOG_logtostderr");
  340. const char *log_dir = std::getenv("GLOG_log_dir");
  341. if (logtostderr != nullptr && log_dir != nullptr) {
  342. std::string logtostderr_str = std::string(logtostderr);
  343. std::string log_dir_str = std::string(log_dir);
  344. const char *rank_id = std::getenv("RANK_ID");
  345. const char *gpu_rank_id = std::getenv("OMPI_COMM_WORLD_RANK");
  346. std::string rank = "0";
  347. bool both_exist = false;
  348. if (rank_id != nullptr && gpu_rank_id == nullptr) {
  349. rank = std::string(rank_id);
  350. } else if (rank_id == nullptr && gpu_rank_id != nullptr) {
  351. rank = std::string(gpu_rank_id);
  352. } else if (rank_id != nullptr && gpu_rank_id != nullptr) {
  353. rank = std::string(rank_id);
  354. both_exist = true;
  355. }
  356. log_dir_str += "/rank_" + rank + "/logs";
  357. auto real_log_dir_str = Common::CreatePrefixPath(log_dir_str);
  358. // While 'GLOG_logtostderr' = 0, logs output to files. 'GLOG_log_dir' must be specified as the path of log files.
  359. // Here can not throw exception and use python to catch, because the PYBIND11_MODULE is not yet been initialed.
  360. if (logtostderr_str == "0" && real_log_dir_str.has_value()) {
  361. if (!Common::IsPathValid(real_log_dir_str.value(), MAX_DIRECTORY_LENGTH, "")) {
  362. MS_LOG(ERROR) << "The path of log files, which set by 'GLOG_log_dir', is invalid";
  363. exit(EXIT_FAILURE);
  364. } else if (!FileUtils::CreateNotExistDirs(real_log_dir_str.value())) {
  365. MS_LOG(ERROR) << "Create the path of log files, which set by 'GLOG_log_dir', failed.";
  366. exit(EXIT_FAILURE);
  367. }
  368. } else if (logtostderr_str == "0") {
  369. MS_LOG(ERROR) << "The path of log files, which set by 'GLOG_log_dir', is invalid.";
  370. exit(EXIT_FAILURE);
  371. }
  372. if (both_exist) {
  373. MS_LOG(WARNING) << "Environment variables RANK_ID and OMPI_COMM_WORLD_RANK both exist, we will use RANK_ID to "
  374. "get rank id by default.";
  375. }
  376. }
  377. }
  378. } _glog_log_dir_register;
  379. } // namespace mindspore