• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2023 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 "utils/temp_file_manager.h"
18 
19 #include <exception>
20 #include "utils/log_adapter.h"
21 #include "utils/system/env.h"
22 
23 namespace mindspore {
GetInstance()24 TempFileManager &TempFileManager::GetInstance() {
25   static TempFileManager instance{};
26   return instance;
27 }
28 
~TempFileManager()29 TempFileManager::~TempFileManager() {
30   try {
31     CleanTempFiles();
32   } catch (const std::exception &e) {
33     MS_LOG(ERROR) << "Exception occurred when cleaning temp files. Error info " << e.what();
34   } catch (...) {
35     MS_LOG(ERROR) << "Exception occurred when cleaning temp files.";
36   }
37 }
38 
Register(const std::string & file_path)39 void TempFileManager::Register(const std::string &file_path) { (void)temp_file_paths_.insert(file_path); }
40 
UnRegister(const std::string & file_path)41 void TempFileManager::UnRegister(const std::string &file_path) { (void)temp_file_paths_.erase(file_path); }
42 
RemoveFile(const std::string & file_path) const43 void TempFileManager::RemoveFile(const std::string &file_path) const {
44   auto fs = system::Env::GetFileSystem();
45   MS_EXCEPTION_IF_NULL(fs);
46   if (file_path.empty()) {
47     return;
48   }
49   if (fs->FileExist(file_path)) {
50     if (!fs->DeleteFile(file_path)) {
51       MS_LOG(WARNING) << "Delete tensor file path: " << file_path << " failed!";
52     }
53   } else {
54     MS_LOG(WARNING) << "Invalid tensor file path: " << file_path;
55   }
56 }
57 
CleanTempFiles()58 void TempFileManager::CleanTempFiles() {
59   MS_LOG(INFO) << "Start delete temp files.";
60   for (auto file_path : temp_file_paths_) {
61     RemoveFile(file_path);
62   }
63   MS_LOG(INFO) << "End delete temp files.";
64 }
65 }  // namespace mindspore
66