-
Notifications
You must be signed in to change notification settings - Fork 342
/
util.cpp
1624 lines (1435 loc) · 48.9 KB
/
util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019, QuantStack and Mamba Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <cstring>
#include <cwchar>
#include <fstream>
#include <iomanip>
#include <memory>
#include <mutex>
#include <optional>
#include <regex>
#include <sstream>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
#include <time.h>
#if defined(__PPC64__) || defined(__ppc64__) || defined(_ARCH_PPC64)
#include <iomanip>
#endif
#if defined(__APPLE__) || defined(__linux__)
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#endif
#ifdef _WIN32
#include <cassert>
#include <io.h>
extern "C"
{
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <sys/locking.h>
}
#endif
#include <nlohmann/json.hpp>
#include <tl/expected.hpp>
#include "mamba/core/context.hpp"
#include "mamba/core/error_handling.hpp"
#include "mamba/core/execution.hpp"
#include "mamba/core/invoke.hpp"
#include "mamba/core/output.hpp"
#include "mamba/core/shell_init.hpp"
#include "mamba/core/thread_utils.hpp"
#include "mamba/core/util.hpp"
#include "mamba/core/util_os.hpp"
#include "mamba/fs/filesystem.hpp"
#include "mamba/util/build.hpp"
#include "mamba/util/compare.hpp"
#include "mamba/util/environment.hpp"
#include "mamba/util/random.hpp"
#include "mamba/util/string.hpp"
#include "mamba/util/url.hpp"
namespace mamba
{
namespace
{
std::atomic<bool> persist_temporary_files{ false };
std::atomic<bool> persist_temporary_directories{ false };
}
bool must_persist_temporary_files()
{
return persist_temporary_files;
}
bool set_persist_temporary_files(bool new_value)
{
return persist_temporary_files.exchange(new_value);
}
bool must_persist_temporary_directories()
{
return persist_temporary_directories;
}
bool set_persist_temporary_directories(bool new_value)
{
return persist_temporary_directories.exchange(new_value);
}
// This function returns true even for broken symlinks
// E.g.
// ln -s abcdef emptylink
// fs::exists(emptylink) == false
// lexists(emptylink) == true
bool lexists(const fs::u8path& path, std::error_code& ec)
{
auto status = fs::symlink_status(path, ec).type();
if (status != fs::file_type::none)
{
ec.clear();
return status != fs::file_type::not_found || status == fs::file_type::symlink;
}
return false;
}
bool lexists(const fs::u8path& path)
{
auto status = fs::symlink_status(path);
return status.type() != fs::file_type::not_found || status.type() == fs::file_type::symlink;
}
std::vector<fs::u8path> filter_dir(const fs::u8path& dir, const std::string& suffix)
{
std::vector<fs::u8path> result;
if (fs::exists(dir) && fs::is_directory(dir))
{
for (const auto& entry : fs::directory_iterator(dir))
{
if (suffix.size())
{
if (!entry.is_directory() && entry.path().extension() == suffix)
{
result.push_back(entry.path());
}
}
else
{
if (entry.is_directory() == false)
{
result.push_back(entry.path());
}
}
}
}
return result;
}
// TODO expand variables, ~ and make absolute
bool paths_equal(const fs::u8path& lhs, const fs::u8path& rhs)
{
return lhs == rhs;
}
TemporaryDirectory::TemporaryDirectory()
{
bool success = false;
#ifndef _WIN32
std::string template_path = fs::temp_directory_path() / "mambadXXXXXX";
char* pth = mkdtemp(const_cast<char*>(template_path.c_str()));
success = (pth != nullptr);
template_path = pth;
#else
const std::string template_path = (fs::temp_directory_path() / "mambadXXXXXX").string();
// include \0 terminator
auto err [[maybe_unused]] = _mktemp_s(
const_cast<char*>(template_path.c_str()),
template_path.size() + 1
);
assert(err == 0);
success = fs::create_directory(template_path);
#endif
if (!success)
{
throw std::runtime_error("Could not create temporary directory!");
}
else
{
m_path = template_path;
}
}
TemporaryDirectory::~TemporaryDirectory()
{
if (!must_persist_temporary_directories())
{
fs::remove_all(m_path);
}
}
const fs::u8path& TemporaryDirectory::path() const
{
return m_path;
}
TemporaryDirectory::operator fs::u8path()
{
return m_path;
}
TemporaryFile::TemporaryFile(
const std::string& prefix,
const std::string& suffix,
const std::optional<fs::u8path>& dir
)
{
static std::mutex file_creation_mutex;
bool success = false;
fs::u8path final_path;
fs::u8path temp_path = dir.value_or(fs::temp_directory_path());
std::lock_guard<std::mutex> file_creation_lock(file_creation_mutex);
do
{
std::string random_file_name = util::generate_random_alphanumeric_string(10);
final_path = temp_path / util::concat(prefix, random_file_name, suffix);
} while (fs::exists(final_path));
try
{
std::ofstream f = open_ofstream(final_path);
f.close();
success = true;
}
catch (...)
{
success = false;
}
if (!success)
{
throw std::runtime_error("Could not create temporary file!");
}
else
{
m_path = final_path;
}
}
TemporaryFile::~TemporaryFile()
{
if (!must_persist_temporary_files())
{
fs::remove(m_path);
}
}
fs::u8path& TemporaryFile::path()
{
return m_path;
}
TemporaryFile::operator fs::u8path()
{
return m_path;
}
std::string read_contents(const fs::u8path& file_path, std::ios::openmode mode)
{
std::ifstream in(file_path.std_path(), std::ios::in | mode);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(static_cast<std::size_t>(in.tellg()));
in.seekg(0, std::ios::beg);
in.read(&contents[0], static_cast<std::streamsize>(contents.size()));
in.close();
return (contents);
}
else
{
throw std::system_error(
errno,
std::system_category(),
"failed to open " + file_path.string()
);
}
}
std::vector<std::string> read_lines(const fs::u8path& file_path)
{
std::fstream file_stream(file_path.std_path(), std::ios_base::in | std::ios_base::binary);
if (file_stream.fail())
{
throw std::system_error(
errno,
std::system_category(),
"failed to open " + file_path.string()
);
}
std::vector<std::string> output;
std::string line;
while (std::getline(file_stream, line))
{
// Remove the trailing \r to accommodate Windows line endings.
if ((!line.empty()) && (line.back() == '\r'))
{
line.pop_back();
}
output.push_back(line);
}
file_stream.close();
return output;
}
void split_package_extension(const std::string& file, std::string& name, std::string& extension)
{
if (util::ends_with(file, ".conda"))
{
name = file.substr(0, file.size() - 6);
extension = ".conda";
}
else if (util::ends_with(file, ".tar.bz2"))
{
name = file.substr(0, file.size() - 8);
extension = ".tar.bz2";
}
else if (util::ends_with(file, ".json"))
{
name = file.substr(0, file.size() - 5);
extension = ".json";
}
else
{
name = file;
extension = "";
}
}
std::string quote_for_shell(const std::vector<std::string>& arguments, const std::string& shell)
{
if ((shell.empty() && util::on_win) || shell == "cmdexe")
{
// ported from CPython's list2cmdline to C++
//
// Translate a sequence of arguments into a command line
// string, using the same rules as the MS C runtime:
// 1) Arguments are delimited by white space, which is either a
// space or a tab.
// 2) A string surrounded by double quotation marks is
// interpreted as a single argument, regardless of white space
// contained within. A quoted string can be embedded in an
// argument.
// 3) A double quotation mark preceded by a backslash is
// interpreted as a literal double quotation mark.
// 4) Backslashes are interpreted literally, unless they
// immediately precede a double quotation mark.
// 5) If backslashes immediately precede a double quotation mark,
// every pair of backslashes is interpreted as a literal
// backslash. If the number of backslashes is odd, the last
// backslash escapes the next double quotation mark as
// described in rule 3.
// See
// http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
// or search http://msdn.microsoft.com for
// "Parsing C++ Command-Line Arguments"
std::string result, bs_buf;
bool need_quote = false;
for (const auto& arg : arguments)
{
bs_buf.clear();
if (!result.empty())
{
// separate arguments
result += " ";
}
need_quote = arg.find_first_of(" \t") != arg.npos || arg.empty();
if (need_quote)
{
result += "\"";
}
for (char c : arg)
{
if (c == '\\')
{
bs_buf += c;
}
else if (c == '"')
{
result += std::string(bs_buf.size() * 2, '\\');
bs_buf.clear();
result += "\\\"";
}
else
{
if (!bs_buf.empty())
{
result += bs_buf;
bs_buf.clear();
}
result += c;
}
}
if (!bs_buf.empty())
{
result += bs_buf;
}
if (need_quote)
{
result += bs_buf;
result += "\"";
}
}
return result;
}
else
{
// Identical to Python's shlex.quote.
auto quote_arg = [](const std::string& s)
{
if (s.size() == 0)
{
return std::string("''");
}
std::regex unsafe("[^\\w@%+=:,./-]");
if (std::regex_search(s, unsafe))
{
std::string s2 = s;
util::replace_all(s2, "'", "'\"'\"'");
return util::concat("'", s2, "'");
}
else
{
return s;
}
};
if (arguments.empty())
{
return "";
}
std::string argstring;
argstring += quote_arg(arguments[0]);
for (std::size_t i = 1; i < arguments.size(); ++i)
{
argstring += " ";
argstring += quote_arg(arguments[i]);
}
return argstring;
}
}
std::size_t clean_trash_files(const fs::u8path& prefix, bool deep_clean)
{
std::size_t deleted_files = 0;
std::size_t remaining_trash = 0;
std::error_code ec;
std::vector<fs::u8path> remaining_files;
auto trash_txt = prefix / "conda-meta" / "mamba_trash.txt";
if (!deep_clean && fs::exists(trash_txt))
{
auto all_files = read_lines(trash_txt);
for (auto& f : all_files)
{
fs::u8path full_path = prefix / f;
LOG_INFO << "Trash: removing " << full_path;
if (!fs::exists(full_path) || fs::remove(full_path, ec))
{
deleted_files += 1;
}
else
{
LOG_INFO << "Trash: could not remove " << full_path;
remaining_trash += 1;
// save relative path
remaining_files.push_back(f);
}
}
}
if (deep_clean)
{
// recursive iterate over all files and delete `.mamba_trash` files
std::vector<fs::u8path> f_to_rm;
for (auto& p : fs::recursive_directory_iterator(prefix))
{
if (p.path().extension() == ".mamba_trash")
{
f_to_rm.push_back(p.path());
}
}
for (auto& p : f_to_rm)
{
LOG_INFO << "Trash: removing " << p;
if (fs::remove(p, ec))
{
deleted_files += 1;
}
else
{
remaining_trash += 1;
// save relative path
remaining_files.push_back(fs::relative(p, prefix));
}
}
}
if (remaining_files.empty())
{
fs::remove(trash_txt, ec);
}
else
{
auto trash_out_file = open_ofstream(
trash_txt,
std::ios::out | std::ios::binary | std::ios::trunc
);
for (auto& rf : remaining_files)
{
trash_out_file << rf.string() << "\n";
}
}
LOG_INFO << "Cleaned " << deleted_files << " .mamba_trash files. " << remaining_trash
<< " remaining.";
return deleted_files;
}
std::size_t remove_or_rename(const Context& context, const fs::u8path& path)
{
std::error_code ec;
std::size_t result = 0;
if (!lexists(path, ec))
{
return 0;
}
if (fs::is_directory(path, ec))
{
result = fs::remove_all(path, ec);
}
else
{
result = fs::remove(path, ec);
}
if (ec)
{
int counter = 0;
// we should only attempt writing to the trash index file from one thread at a time
static std::mutex trash_mutex;
std::lock_guard<std::mutex> guard(trash_mutex);
while (ec)
{
LOG_INFO << "Caught a filesystem error for '" << path.string()
<< "':" << ec.message() << " (File in use?)";
fs::u8path trash_file = path;
std::size_t fcounter = 0;
trash_file.replace_extension(
util::concat(trash_file.extension().string(), ".mamba_trash")
);
while (lexists(trash_file))
{
trash_file = path;
trash_file.replace_extension(util::concat(
trash_file.extension().string(),
std::to_string(fcounter),
".mamba_trash"
));
fcounter += 1;
if (fcounter > 100)
{
throw std::runtime_error("Too many existing trash files. Please force clean");
}
}
fs::rename(path, trash_file, ec);
if (!ec)
{
// The conda-meta directory is locked by transaction execute
auto trash_index = open_ofstream(
context.prefix_params.target_prefix / "conda-meta" / "mamba_trash.txt",
std::ios::app | std::ios::binary
);
// TODO add some unicode tests here?
trash_index << fs::relative(trash_file, context.prefix_params.target_prefix).string()
<< "\n";
return 1;
}
// this is some exponential back off
counter += 1;
LOG_ERROR << "Trying to remove " << path << ": " << ec.message()
<< " (file in use?). Sleeping for " << counter * 2 << "s";
if (counter > 3)
{
throw std::runtime_error(util::concat("Could not delete file ", path.string()));
}
std::this_thread::sleep_for(std::chrono::seconds(counter * 2));
}
}
return result;
}
std::string unindent(const char* p)
{
std::string result;
if (*p == '\n')
{
++p;
}
const char* p_leading = p;
while (std::isspace(*p) && *p != '\n')
{
++p;
}
std::size_t leading_len = static_cast<std::size_t>(p - p_leading);
while (*p)
{
result += *p;
if (*p++ == '\n')
{
for (std::size_t i = 0; i < leading_len; ++i)
{
if (p[i] != p_leading[i])
{
goto dont_skip_leading;
}
}
p += leading_len;
}
dont_skip_leading:;
}
return result;
}
std::string prepend(const char* p, const char* start, const char* newline)
{
std::string result;
result += start;
while (*p)
{
result += *p;
if (*p++ == '\n')
{
result += newline;
}
}
return result;
}
std::string prepend(const std::string& p, const char* start, const char* newline)
{
return prepend(p.c_str(), start, newline);
}
class LockFileOwner
{
public:
explicit LockFileOwner(const fs::u8path& file_path, const std::chrono::seconds timeout);
~LockFileOwner();
LockFileOwner(const LockFileOwner&) = delete;
LockFileOwner& operator=(const LockFileOwner&) = delete;
LockFileOwner(LockFileOwner&&) = delete;
LockFileOwner& operator=(LockFileOwner&&) = delete;
bool set_fd_lock(bool blocking) const;
bool lock_non_blocking();
bool lock_blocking();
bool lock(bool blocking) const;
void remove_lockfile() noexcept;
int close_fd();
bool unlock();
int fd() const
{
return m_fd;
}
fs::u8path path() const
{
return m_path;
}
fs::u8path lockfile_path() const
{
return m_lockfile_path;
}
private:
fs::u8path m_path;
fs::u8path m_lockfile_path;
std::chrono::seconds m_timeout;
int m_fd = -1;
bool m_locked;
bool m_lockfile_existed;
template <typename Func = no_op>
void throw_lock_error(std::string error_message, Func before_throw_task = no_op{}) const
{
auto complete_error_message = fmt::format(
"LockFile acquisition failed, aborting: {}",
std::move(error_message)
);
LOG_ERROR << error_message;
safe_invoke(before_throw_task)
.map_error([](const auto& error)
{ LOG_ERROR << "While handling LockFile failure: " << error.what(); });
throw mamba_error(complete_error_message, mamba_error_code::lockfile_failure);
}
};
LockFileOwner::LockFileOwner(const fs::u8path& path, const std::chrono::seconds timeout)
: m_path(path)
, m_timeout(timeout)
, m_locked(false)
{
std::error_code ec;
if (!fs::exists(path, ec))
{
throw_lock_error(fmt::format("Could not lock non-existing path '{}'", path.string()));
}
if (fs::is_directory(path))
{
LOG_DEBUG << "Locking directory '" << path.string() << "'";
m_lockfile_path = m_path / (m_path.filename().string() + ".lock");
}
else
{
LOG_DEBUG << "Locking file '" << path.string() << "'";
m_lockfile_path = m_path.string() + ".lock";
}
m_lockfile_existed = fs::exists(m_lockfile_path, ec);
#ifdef _WIN32
m_fd = _wopen(m_lockfile_path.wstring().c_str(), O_RDWR | O_CREAT, 0666);
#else
m_fd = open(m_lockfile_path.string().c_str(), O_RDWR | O_CREAT, 0666);
#endif
if (m_fd <= 0)
{
throw_lock_error(
fmt::format("Could not open lockfile '{}'", m_lockfile_path.string()),
[this] { unlock(); }
);
}
else
{
if ((m_locked = lock_non_blocking()) == false)
{
LOG_WARNING << "Cannot lock '" << m_path.string() << "'"
<< "\nWaiting for other mamba process to finish";
m_locked = lock_blocking();
}
if (m_locked)
{
LOG_TRACE << "Lockfile created at '" << m_lockfile_path.string() << "'";
LOG_DEBUG << "Successfully locked";
}
else
{
throw_lock_error(
fmt::format(
"LockFile can't be set at '{}'\n"
"This could be fixed by changing the locks' timeout or "
"cleaning your environment from previous runs",
m_path.string()
),
[this] { unlock(); }
);
}
}
}
LockFileOwner::~LockFileOwner()
{
LOG_DEBUG << "Unlocking '" << m_path.string() << "'";
unlock();
}
void LockFileOwner::remove_lockfile() noexcept
{
close_fd();
if (!m_lockfile_existed)
{
std::error_code ec;
LOG_TRACE << "Removing file '" << m_lockfile_path.string() << "'";
fs::remove(m_lockfile_path, ec);
if (ec)
{
LOG_ERROR << "Removing lock file '" << m_lockfile_path.string() << "' failed\n"
<< "You may need to remove it manually";
}
}
}
int LockFileOwner::close_fd()
{
int ret = 0;
if (m_fd > -1)
{
ret = close(m_fd);
m_fd = -1;
}
return ret;
}
bool LockFileOwner::unlock()
{
int ret = 0;
// POSIX systems automatically remove locks when closing any file
// descriptor related to the file
#ifdef _WIN32
LOG_TRACE << "Removing lock on '" << m_lockfile_path.string() << "'";
_lseek(m_fd, MAMBA_LOCK_POS, SEEK_SET);
ret = _locking(m_fd, LK_UNLCK, 1 /*lock_file_contents_length()*/);
#endif
remove_lockfile();
return ret == 0;
}
#ifndef _WIN32
int timedout_set_fd_lock(int fd, struct flock& lock, const std::chrono::seconds timeout)
{
int ret;
std::mutex m;
std::condition_variable cv;
thread t(
[&cv, &ret, &fd, &lock]()
{
ret = fcntl(fd, F_SETLKW, &lock);
cv.notify_one();
}
);
auto th = t.native_handle();
int err = 0;
set_signal_handler(
[&th, &cv, &ret, &err](sigset_t sigset) -> int
{
int signum = 0;
sigwait(&sigset, &signum);
pthread_cancel(th);
err = EINTR;
ret = -1;
cv.notify_one();
return signum;
}
);
MainExecutor::instance().take_ownership(t.extract());
{
std::unique_lock<std::mutex> l(m);
if (cv.wait_for(l, timeout) == std::cv_status::timeout)
{
pthread_cancel(th);
kill_receiver_thread();
err = EINTR;
ret = -1;
}
}
set_default_signal_handler();
errno = err;
return ret;
}
#endif
bool LockFileOwner::set_fd_lock(bool blocking) const
{
int ret = 0;
#ifdef _WIN32
_lseek(m_fd, MAMBA_LOCK_POS, SEEK_SET);
if (blocking)
{
static constexpr auto default_timeout = std::chrono::seconds(30);
const auto timeout = m_timeout > std::chrono::seconds::zero() ? m_timeout
: default_timeout;
const auto begin_time = std::chrono::system_clock::now();
while ((std::chrono::system_clock::now() - begin_time) < timeout)
{
ret = _locking(m_fd, LK_NBLCK, 1 /*lock_file_contents_length()*/);
if (ret == 0)
{
break;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
if (ret != 0)
{
errno = EINTR;
}
}
else
{
ret = _locking(m_fd, LK_NBLCK, 1 /*lock_file_contents_length()*/);
}
#else
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = MAMBA_LOCK_POS;
lock.l_len = 1;
if (blocking)
{
if (m_timeout.count())
{
ret = timedout_set_fd_lock(m_fd, lock, m_timeout);
}
else
{
ret = fcntl(m_fd, F_SETLKW, &lock);
}
}
else
{
ret = fcntl(m_fd, F_SETLK, &lock);
}
#endif
return ret == 0;
}
bool LockFileOwner::lock(bool blocking) const
{
if (!set_fd_lock(blocking))
{
LOG_ERROR << "Could not set lock (" << strerror(errno) << ")";
return false;
}
return true;
}
bool LockFileOwner::lock_blocking()
{
return lock(true);
}
namespace
{
void log_duplicate_lockfile_in_process(const fs::u8path& path)
{
LOG_DEBUG << "Path already locked by the same process: '" << fs::absolute(path).string()
<< "'";
}
bool is_lockfile_locked(const LockFileOwner& lockfile)
{
#ifdef _WIN32
return LockFile::is_locked(lockfile.lockfile_path());
#else
// Opening a new file descriptor on Unix would clear locks
return LockFile::is_locked(lockfile.fd());
#endif
}
class LockedFilesRegistry
{
public:
LockedFilesRegistry() = default;
LockedFilesRegistry(LockedFilesRegistry&&) = delete;
LockedFilesRegistry(const LockedFilesRegistry&) = delete;
LockedFilesRegistry& operator=(LockedFilesRegistry&&) = delete;
LockedFilesRegistry& operator=(const LockedFilesRegistry&) = delete;
bool is_file_locking_allowed() const
{
return m_is_file_locking_allowed;
}
bool allow_file_locking(bool allow)
{
return m_is_file_locking_allowed.exchange(allow);
}
std::chrono::seconds default_file_locking_timeout() const
{
return m_default_lock_timeout;
}
std::chrono::seconds set_file_locking_timeout(const std::chrono::seconds& new_timeout)