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 11 kB

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
4 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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, const bool support_relative_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(), support_relative_path);
  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::GetConfigFile(const std::string &env) {
  84. if (env.empty()) {
  85. MS_LOG(EXCEPTION) << "Invalid env";
  86. }
  87. auto config_path_str = common::GetEnv(env);
  88. if (config_path_str.empty()) {
  89. MS_LOG(ERROR) << "Please export env:" << env;
  90. return std::nullopt;
  91. }
  92. MS_LOG(INFO) << "Async Dump Getenv env:" << env << "=" << config_path_str;
  93. auto real_path = FileUtils::GetRealPath(common::SafeCStr(config_path_str));
  94. if (!real_path.has_value()) {
  95. MS_LOG(ERROR) << "Can't get real_path";
  96. return std::nullopt;
  97. }
  98. std::string dump_config_file = real_path.value();
  99. std::shared_ptr<system::FileSystem> fs = system::Env::GetFileSystem();
  100. MS_EXCEPTION_IF_NULL(fs);
  101. if (!fs->FileExist(dump_config_file)) {
  102. MS_LOG(ERROR) << dump_config_file << " not exist.";
  103. return std::nullopt;
  104. }
  105. auto point_pos = dump_config_file.find_last_of('.');
  106. if (point_pos == std::string::npos) {
  107. MS_LOG(EXCEPTION) << "Invalid json file name:" << dump_config_file;
  108. }
  109. auto suffix = dump_config_file.substr(point_pos + 1);
  110. if (suffix != "json") {
  111. MS_LOG(EXCEPTION) << "[DataDump] dump config file suffix only supports json! But got:." << suffix;
  112. }
  113. return dump_config_file;
  114. }
  115. bool Common::IsStrLengthValid(const std::string &str, size_t length_limit, const std::string &error_message) {
  116. auto len_str = str.length();
  117. if (len_str > length_limit) {
  118. MS_LOG(ERROR) << error_message << "The length is " << str.length() << ", exceeding the limit of " << length_limit
  119. << ".";
  120. return false;
  121. }
  122. return true;
  123. }
  124. bool Common::IsEveryFilenameValid(const std::string &path, size_t length_limit, const std::string &error_message) {
  125. if (path.empty()) {
  126. MS_LOG(WARNING) << error_message << "The path is empty.";
  127. return false;
  128. }
  129. size_t len_path = path.length();
  130. size_t left_pos = 0;
  131. for (size_t i = 0; i < len_path; i++) {
  132. if (i != 0) {
  133. if (path[i] == '\\' || path[i] == '/') {
  134. auto cur_len = i - left_pos;
  135. if (cur_len > length_limit) {
  136. MS_LOG(WARNING) << error_message << "The name length of '" << path.substr(left_pos, cur_len) << "' is "
  137. << cur_len << ". It is out of the limit which is " << length_limit << ".";
  138. return false;
  139. }
  140. left_pos = i + 1;
  141. }
  142. }
  143. }
  144. if (!(path[len_path - 1] == '\\' || path[len_path - 1] == '/')) {
  145. auto cur_len = len_path - left_pos;
  146. if (cur_len > length_limit) {
  147. MS_LOG(WARNING) << error_message << "The name length of '" << path.substr(left_pos, cur_len) << "' is " << cur_len
  148. << ". It is out of the limit which is " << length_limit << ".";
  149. return false;
  150. }
  151. }
  152. return true;
  153. }
  154. bool Common::IsPathValid(const std::string &path, size_t length_limit, const std::string &error_message) {
  155. std::string err_msg = "Detail: ";
  156. if (!error_message.empty()) {
  157. err_msg = error_message + " " + err_msg;
  158. }
  159. if (path.empty()) {
  160. MS_LOG(WARNING) << err_msg << "The path is empty.";
  161. return false;
  162. }
  163. if (!IsStrLengthValid(path, length_limit, err_msg)) {
  164. return false;
  165. }
  166. if (!std::all_of(path.begin(), path.end(), [](char c) {
  167. return ::isalpha(c) || ::isdigit(c) || c == '-' || c == '_' || c == '.' || c == '/';
  168. })) {
  169. MS_LOG(ERROR) << err_msg << "The path only supports alphabets, digit or {'-', '_', '.', '/'}, but got:" << path
  170. << ".";
  171. return false;
  172. }
  173. if (path[0] != '/') {
  174. MS_LOG(ERROR) << err_msg << "The path only supports absolute path and should start with '/'.";
  175. return false;
  176. }
  177. if (!IsEveryFilenameValid(path, MAX_OS_FILENAME_LENGTH, err_msg)) {
  178. return false;
  179. }
  180. return true;
  181. }
  182. bool Common::IsFilenameValid(const std::string &filename, size_t length_limit, const std::string &error_message) {
  183. std::string err_msg = "Detail: ";
  184. if (!error_message.empty()) {
  185. err_msg = error_message + " " + err_msg;
  186. }
  187. if (filename.empty()) {
  188. MS_LOG(WARNING) << err_msg << "The filename is empty.";
  189. return false;
  190. }
  191. if (!IsStrLengthValid(filename, length_limit, err_msg)) {
  192. return false;
  193. }
  194. auto func = [](char c) { return ::isalpha(c) || ::isdigit(c) || c == '-' || c == '_' || c == '.'; };
  195. if (!std::all_of(filename.begin(), filename.end(), func)) {
  196. MS_LOG(ERROR) << err_msg << "The filename only supports alphabets, digit or {'-', '_', '.'}, but got:" << filename
  197. << ".";
  198. return false;
  199. }
  200. return true;
  201. }
  202. std::string Common::AddId(const std::string &filename, const std::string &suffix) {
  203. static size_t g_id = 0;
  204. std::ostringstream s;
  205. auto i = filename.rfind(suffix);
  206. const int spaces = 4;
  207. if (i >= filename.size()) {
  208. s << filename;
  209. s << "_" << std::setfill('0') << std::setw(spaces) << g_id;
  210. } else {
  211. s << filename.substr(0, i);
  212. s << "_" << std::setfill('0') << std::setw(spaces) << g_id;
  213. if (i + 1 < filename.size()) {
  214. s << filename.substr(i);
  215. }
  216. }
  217. g_id++;
  218. return s.str();
  219. }
  220. bool Common::SaveStringToFile(const std::string filename, const std::string string_info) {
  221. if (filename.size() >= PATH_MAX) {
  222. MS_LOG(ERROR) << "File path " << filename << " is too long.";
  223. return false;
  224. }
  225. auto real_path = CreatePrefixPath(filename);
  226. if (!real_path.has_value()) {
  227. MS_LOG(ERROR) << "Get real path failed. path=" << filename;
  228. return false;
  229. }
  230. ChangeFileMode(real_path.value(), S_IRWXU);
  231. std::ofstream ofs;
  232. ofs.open(real_path.value());
  233. if (!ofs.is_open()) {
  234. MS_LOG(ERROR) << "Open dump file '" << real_path.value() << "' failed!" << ErrnoToString(errno);
  235. return false;
  236. }
  237. ofs << string_info << std::endl;
  238. ofs.close();
  239. // set file mode to read only by user
  240. ChangeFileMode(real_path.value(), S_IRUSR);
  241. return true;
  242. }
  243. bool Common::FileExists(const std::string &filepath) {
  244. std::ifstream f(filepath);
  245. bool cache_file_existed = f.good();
  246. f.close();
  247. return cache_file_existed;
  248. }
  249. std::string Common::GetUserDefineCachePath() {
  250. static std::string config_path = "";
  251. if (config_path != "") {
  252. return config_path;
  253. }
  254. const char *value = ::getenv(kCOMPILER_CACHE_PATH);
  255. if (value == nullptr) {
  256. config_path = "./";
  257. } else {
  258. config_path = std::string(value);
  259. FileUtils::CreateNotExistDirs(config_path);
  260. if (config_path[config_path.length() - 1] != '/') {
  261. config_path += "/";
  262. }
  263. }
  264. return config_path;
  265. }
  266. std::string Common::GetCompilerCachePath() {
  267. static const std::string user_defined_path = GetUserDefineCachePath();
  268. static uint32_t rank_id = IsStandAlone() ? 0 : GetRank();
  269. static const std::string compile_cache_dir = user_defined_path + "rank_" + std::to_string(rank_id) + "/";
  270. return compile_cache_dir;
  271. }
  272. struct GlogLogDirRegister {
  273. GlogLogDirRegister() {
  274. const char *logtostderr = std::getenv("GLOG_logtostderr");
  275. const char *log_dir = std::getenv("GLOG_log_dir");
  276. if (logtostderr != nullptr && log_dir != nullptr) {
  277. std::string logtostderr_str = std::string(logtostderr);
  278. std::string log_dir_str = std::string(log_dir);
  279. if (logtostderr_str != "0") {
  280. return;
  281. }
  282. const char *rank_id = std::getenv("RANK_ID");
  283. const char *gpu_rank_id = std::getenv("OMPI_COMM_WORLD_RANK");
  284. std::string rank = "0";
  285. bool both_exist = false;
  286. if (rank_id != nullptr && gpu_rank_id == nullptr) {
  287. rank = std::string(rank_id);
  288. } else if (rank_id == nullptr && gpu_rank_id != nullptr) {
  289. rank = std::string(gpu_rank_id);
  290. } else if (rank_id != nullptr && gpu_rank_id != nullptr) {
  291. rank = std::string(rank_id);
  292. both_exist = true;
  293. }
  294. log_dir_str += "/rank_" + rank + "/logs/";
  295. auto real_log_dir_str = Common::CreatePrefixPath(log_dir_str, true);
  296. // While 'GLOG_logtostderr' = 0, logs output to files. 'GLOG_log_dir' must be specified as the path of log files.
  297. // Here can not throw exception and use python to catch, because the PYBIND11_MODULE is not yet been initialed.
  298. if (!real_log_dir_str.has_value()) {
  299. MS_LOG(ERROR) << "The path of log files, which set by 'GLOG_log_dir', is invalid.";
  300. exit(EXIT_FAILURE);
  301. }
  302. if (both_exist) {
  303. MS_LOG(WARNING) << "Environment variables RANK_ID and OMPI_COMM_WORLD_RANK both exist, we will use RANK_ID to "
  304. "get rank id by default.";
  305. }
  306. }
  307. }
  308. } _glog_log_dir_register;
  309. } // namespace mindspore