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