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