From 932b0cfcab5b9dd4c22c6f76a6119120dce95389 Mon Sep 17 00:00:00 2001 From: Hugo Hurskainen Date: Tue, 9 Jun 2026 16:00:00 +0300 Subject: [PATCH 01/10] Added move funtionality to the ltfs_ordered_copy script --- man/ltfs_ordered_copy.1 | 3 ++ man/sgml/ltfs_ordered_copy.sgml | 6 ++++ src/utils/ltfs_ordered_copy | 54 +++++++++++++++++++++++++++------ 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/man/ltfs_ordered_copy.1 b/man/ltfs_ordered_copy.1 index 0444daee..074cdf16 100644 --- a/man/ltfs_ordered_copy.1 +++ b/man/ltfs_ordered_copy.1 @@ -40,6 +40,9 @@ Configure verbosity of logger. VERBOSE shall be 0-6. (Default: 4) .TP \fB-q, --quiet\fR No message outout +.TP +\fB--move\fR +Move files instead of copying them. Each source file is removed only after it has been successfully copied to the destination, so the LTFS tape read order is preserved and no data is lost if a copy fails. This option implies \fB-p\fR so that file attributes are preserved like a normal move. After a recursive move the emptied source directories are pruned; source directories that still contain files (for example because a copy failed) are left untouched. .SH "COMMAND EXAMPLES" .PP This section shows various command examples. diff --git a/man/sgml/ltfs_ordered_copy.sgml b/man/sgml/ltfs_ordered_copy.sgml index 46f52406..b42cc7f3 100644 --- a/man/sgml/ltfs_ordered_copy.sgml +++ b/man/sgml/ltfs_ordered_copy.sgml @@ -104,6 +104,12 @@ No message outout + + + + Move files instead of copying them. Each source file is removed only after it has been successfully copied to the destination, so the LTFS tape read order is preserved and no data is lost if a copy fails. This option implies so that file attributes are preserved like a normal move. After a recursive move the emptied source directories are pruned; source directories that still contain files (for example because a copy failed) are left untouched. + + diff --git a/src/utils/ltfs_ordered_copy b/src/utils/ltfs_ordered_copy index 5537964e..c0adfabf 100755 --- a/src/utils/ltfs_ordered_copy +++ b/src/utils/ltfs_ordered_copy @@ -46,12 +46,13 @@ from collections import deque class CopyItem: """""" - def __init__(self, src, dst, vea_pre, cp_attr, cp_xattr, logger): #initialization + def __init__(self, src, dst, vea_pre, cp_attr, cp_xattr, logger, move=False): #initialization self.src = src self.dst = dst self.vea_pre = vea_pre self.cp_attr = cp_attr self.cp_xattr = cp_xattr + self.move = move self.vuuid = '' self.part = '' self.start = -1 @@ -78,6 +79,7 @@ class CopyItem: return (self.vuuid, self.part, self.start) def run(self): + action = 'move' if self.move else 'copy' try: if len(self.vuuid): logger.debug('"{0}" ({2}) -> "{1}"'.format(self.src, self.dst, str(self.start))) @@ -98,9 +100,19 @@ class CopyItem: else: #Only copy data shutil.copy(self.src, self.dst) except Exception as e: - self.logger.error('Failed to copy "{0}" to "{1}": {2}'.format(self.src, self.dst, str(str(e)))) + self.logger.error('Failed to {3} "{0}" to "{1}": {2}'.format(self.src, self.dst, str(str(e)), action)) return False + if self.move: + # The data is safely on the destination now; remove the source to + # complete the move. Deletion happens only after a successful copy so + # that nothing is lost if the copy above failed. + try: + os.remove(self.src) + except Exception as e: + self.logger.error('Copied "{0}" to "{1}" but failed to remove source: {2}'.format(self.src, self.dst, str(e))) + return False + return True def __repr__(self): @@ -151,7 +163,7 @@ class CopyQueue: self.items = self.items + 1 - def walk_dir(self, source, dest, cp_attr, cp_xattr=False): + def walk_dir(self, source, dest, cp_attr, cp_xattr=False, move=False): (source_root, t) = os.path.split(source) prefix_len = len(source_root) dst = dest + "/" + t @@ -171,7 +183,7 @@ class CopyQueue: for f in sorted(files) if self.sort_files else files: self.logger.log(NOTSET + 1, 'Creating a copy item for file {}'.format(f)) c = CopyItem(os.path.join(root, f), os.path.join(dst, f), VEA_PREFIX, - cp_attr, cp_xattr, logger) + cp_attr, cp_xattr, logger, move) self.add_copy_item(c) for d in walk_dirs: @@ -280,6 +292,7 @@ parser.add_argument('-v', help='Verbose output. Set VERBOSE level 5', action='st parser.add_argument('--verbose', help='Configure verbosity of logger. VERBOSE shall be 0-6. default is 4', default = str(logger_info)) parser.add_argument('-q','--quiet', help='No message output', action='store_true') parser.add_argument('--sort-files', help='Sort the file list before copying', action='store_true') +parser.add_argument('--move', help='Move files instead of copying. Each source file is removed only after it has been successfully copied to the destination, preserving tape read order. Implies -p so file attributes are preserved like a normal move. Empty source directories are pruned after a recursive move.', action='store_true') args=parser.parse_args() @@ -287,6 +300,10 @@ if args.all: args.p = True args.recursive = True +if args.move: + # A move should preserve file metadata like a regular "mv". + args.p = True + logger = getLogger(__name__) basicConfig(format = '') if args.quiet: @@ -348,7 +365,12 @@ if args.recursive == False and len(args.SOURCE) == 1: (new_d, t) = os.path.split(dst) if not os.path.exists(new_d): os.makedirs(new_d) - shutil.copy(args.SOURCE[0], args.DEST) + if args.p: + shutil.copy2(args.SOURCE[0], args.DEST) + else: + shutil.copy(args.SOURCE[0], args.DEST) + if args.move: + os.remove(args.SOURCE[0]) except Exception as e: logger.error(str(e)) exit(1) @@ -402,7 +424,7 @@ for s in args.SOURCE: (new_d, t) = os.path.split(dst) if not os.path.exists(new_d): os.makedirs(new_d) - c = CopyItem(s, dst, VEA_PREFIX, args.p, args.all, logger) + c = CopyItem(s, dst, VEA_PREFIX, args.p, args.all, logger, args.move) copyq.add_copy_item(c) else: logger.log(NOTSET + 1, 'Creating copy item for directory {}'.format(s)) @@ -414,7 +436,7 @@ for s in args.SOURCE: if not os.path.exists(new_d): os.makedirs(new_d) dst = new_d - copyq.walk_dir(s, dst, args.p, args.all) + copyq.walk_dir(s, dst, args.p, args.all, args.move) else: logger.warning("omitting directory '{0}'".format(s)) @@ -471,10 +493,24 @@ while tape != None: (tape_key, tape) = copyq.pop_tape() prog_tape.finish() +# In move mode the source files have been removed as they were copied. Prune the +# now-empty source directory trees bottom-up. Directories that still hold files +# (e.g. because a copy failed, or a non-recursive directory was skipped) are left +# untouched, so no data is ever discarded. +if args.move: + for s in args.SOURCE: + if os.path.isdir(s): + for dirpath, dirnames, filenames in os.walk(s, topdown=False): + try: + os.rmdir(dirpath) + except OSError: + pass # Not empty or already removed + # Return code +done = 'Moved' if args.move else 'Copied' if fail: - logger.info("Copied {} files, Failed {} files.".format(success, fail)) + logger.info("{} {} files, Failed {} files.".format(done, success, fail)) exit(1) else: - logger.info("Copied {} files.".format(success, fail)) + logger.info("{} {} files.".format(done, success)) exit(0) From 89bf23b9c349d1408234e414c997436b38b93c3e Mon Sep 17 00:00:00 2001 From: Hugo Hurskainen Date: Sat, 4 Jul 2026 00:17:56 +0300 Subject: [PATCH 02/10] Collect the directories actually recursed into (moved_dirs) and prune only those. Directories skipped without -r, plain-file sources, and empty directories outside the moved trees are now left untouched. Recursive moves still replicate the full tree. --- src/utils/ltfs_ordered_copy | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/utils/ltfs_ordered_copy b/src/utils/ltfs_ordered_copy index c0adfabf..4bd8f349 100755 --- a/src/utils/ltfs_ordered_copy +++ b/src/utils/ltfs_ordered_copy @@ -414,6 +414,9 @@ if args.keep_tree is None: # Create the list of copy item copyq = CopyQueue(logger, args.sort_files) +# Track directory sources that were actually recursed into, so a --move run only +# prunes trees it really moved (not plain files, not directories skipped without -r). +moved_dirs = [] for s in args.SOURCE: dst = args.DEST if os.path.isfile(s): @@ -437,6 +440,8 @@ for s in args.SOURCE: os.makedirs(new_d) dst = new_d copyq.walk_dir(s, dst, args.p, args.all, args.move) + if args.move: + moved_dirs.append(s) else: logger.warning("omitting directory '{0}'".format(s)) @@ -494,11 +499,13 @@ while tape != None: prog_tape.finish() # In move mode the source files have been removed as they were copied. Prune the -# now-empty source directory trees bottom-up. Directories that still hold files -# (e.g. because a copy failed, or a non-recursive directory was skipped) are left -# untouched, so no data is ever discarded. +# now-empty source directory trees bottom-up. Only directories that were actually +# recursed into by this move are considered (moved_dirs), so a directory passed +# without -r, or an empty directory outside the moved trees, is never touched. +# Directories that still hold files (e.g. because a copy failed) make rmdir fail +# and are left untouched, so no data is ever discarded. if args.move: - for s in args.SOURCE: + for s in moved_dirs: if os.path.isdir(s): for dirpath, dirnames, filenames in os.walk(s, topdown=False): try: From 48a10d12ad7829c92da80e2a0b0e73c71350c97a Mon Sep 17 00:00:00 2001 From: Hugo Hurskainen Date: Sat, 4 Jul 2026 00:36:22 +0300 Subject: [PATCH 03/10] Recursive walks created destination directories with a bare os.mkdir, so directory mode, timestamps, and xattrs were never carried over. Snapshot each source directory's stat during the walk before any files are moved out, since removing a file bumps its parent's mtime and apply mode + timestamps (with -p) and xattrs (with --all) to the destination in a final pass after all files are written --- src/utils/ltfs_ordered_copy | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/utils/ltfs_ordered_copy b/src/utils/ltfs_ordered_copy index 4bd8f349..ff871128 100755 --- a/src/utils/ltfs_ordered_copy +++ b/src/utils/ltfs_ordered_copy @@ -128,6 +128,7 @@ class CopyQueue: self.items = 0 self.logger = logger self.sort_files = sort_files + self.walked_dirs = [] # (source_dir, dest_dir) pairs for metadata replication def add_copy_item(self, c): (u, p, s) = c.eval() @@ -178,6 +179,12 @@ class CopyQueue: dst = dest + "/" + t dst = os.path.normpath(dst) + # Record every directory (os.walk yields each one once, including + # empty ones) together with a snapshot of its metadata taken now, + # before any files are moved out -- removing a source file bumps its + # directory's mtime, so the snapshot must be captured up front. + self.walked_dirs.append((root, dst, os.stat(root))) + for d in sorted(dirs) if self.sort_files else dirs: walk_dirs.append(os.path.join(dst, d)) for f in sorted(files) if self.sort_files else files: @@ -498,6 +505,23 @@ while tape != None: (tape_key, tape) = copyq.pop_tape() prog_tape.finish() +# Replicate directory metadata (mode and timestamps with -p; xattrs with --all) +# onto each walked destination directory. Mode/timestamps come from the snapshot +# taken during the walk, before the move removed any files (which would bump the +# source directory mtimes). Runs after all files are copied and before move-mode +# pruning, deepest-first so setting a child never re-bumps an already-set parent. +if args.p or args.all: + for (src_dir, dst_dir, src_stat) in reversed(copyq.walked_dirs): + try: + if args.p: + os.chmod(dst_dir, src_stat.st_mode & 0o7777) + os.utime(dst_dir, (src_stat.st_atime, src_stat.st_mtime)) + if args.all: + for key in xattr.list(src_dir): + xattr.set(dst_dir, key, xattr.get(src_dir, key)) + except Exception as e: + logger.error('Failed to copy directory metadata to "{0}": {1}'.format(dst_dir, str(e))) + # In move mode the source files have been removed as they were copied. Prune the # now-empty source directory trees bottom-up. Only directories that were actually # recursed into by this move are considered (moved_dirs), so a directory passed From 31830b4297b854dd4a2ea1b2d414b2b068453fe4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luis=20Gabriel=20Hern=C3=A1ndez=20Hern=C3=A1ndez?= Date: Mon, 27 Jul 2026 13:34:00 -0600 Subject: [PATCH 04/10] Docs: MD updates (#584) --- .github/CONTRIBUTING.md | 77 ++++++++++++++- docs/CODE_OF_CONDUCT.md | 201 ++++++++++++++++------------------------ docs/CODING_STYLEmd | 133 ++++++++++++++++++++++++++ 3 files changed, 287 insertions(+), 124 deletions(-) create mode 100644 docs/CODING_STYLEmd diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 8e7a5a7c..b20fcf24 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -4,7 +4,7 @@ We love pull requests from everyone. When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. -Please note we have a [coding style guide](/docs/CODE_OF_CONDUCT.md), please follow it in all your interactions with the project. +Please note we have a [coding style guide](../docs/CODING_STYLE.md), please follow it in all your interactions with the project. 1. Fork, then clone the repo @@ -25,5 +25,78 @@ Please note we have a [coding style guide](/docs/CODE_OF_CONDUCT.md), please fol __Some things that will increase the chance that your pull request is accepted__ -* Follow our [coding style guide](/docs/CODE_OF_CONDUCT.md). +* Follow our [coding style guide](../docs/CODING_STYLE.md). * Write a good commit message. + +# Branch Naming Conventions +The structure and design conventions are based mainly on the “Conventional Branch” concept and the team’s current work process. + +Note: These conventions are recommendations intended to improve readability and consistency of commits within pull requests and are not strictly enforced. Only the release and main branches are required to fully adhere to this naming convention. + +## Purpose +1. Purpose-driven Branch Names: Each branch name clearly indicates its purpose, making it easy for all developers to understand what the branch is for. +2. Integration with CI/CD: By using consistent branch names, it can help automated systems (like Continuous Integration/Continuous Deployment pipelines) to trigger specific actions based on the branch type. +3. Better type and version control: Branches are related to a specific type of change in the code and the version that is being worked on, allowing for a much better backtracking. + +## Basic Rules +- Naming structure: +`/` +- Naming prefixes (Types): + - feature/: For new features (e.g., feature/add-login-page). + - fix/: For general fixes or code correcting. + - update/: For code upgrade or non-breaking code refactoring. + - chore/: For non-code tasks like dependency, docs updates (e.g., chore/update-dependencies). + - release/: For branches preparing a release (e.g., release/v1.2.0). +- Use Lowercase Alphanumeric and Hyphens: Always use lowercase letters (a-z), numbers (0-9), and hyphens to separate words. Avoid special characters, underscores, or spaces. +- No Consecutive or Trailing Hyphens: Ensure that hyphens are used singly, with no consecutive hyphens (feature/new--login) or at the end (feature/new-login-). +- Keep It Clear and Concise: The branch name should be descriptive yet concise, clearly indicating the purpose of the work. +- Include Ticket Numbers: If applicable, include the ticket number from your project management tool to make tracking easier. For example, for a ticket issue-123, the branch name could be feature/issue-123-new-login. + +## General Project Structure +``` +main +├── release/v1.x.x +│ ├── feature/lorem-ipsum +│ └── fix/ipsum-dolor +├── release/v2.x.x +│ └── chore/dolor-sit +└── release/v3.x.x + ├── update/sit-amet + ├── feature/amet-consectetur + └── chore/consectetur-adipiscing +``` +- main: This branch should only contain working versions completely tested and only receive pull requests from finalized release branches. All new release/ branches must come from this one. +- release: The creation of these branches should be done from the last version of main when created. Only this branches can make pull requests to main. +- Other branches: All working branches should come from a release branch. These are the only ones that should receive direct commits from changes made by development staff. These branches should only do PR to the active release branch. + +# Commits Naming Conventions +The structure and design conventions are based mainly on the “Conventional Branch” concept and the team’s current work process. + +## Purpose +1. Automatically generating CHANGELOGs: When the commits are concise, and precise changelogs can be automated or semi-automated from the commit history. +2. Communicating the nature of changes to everyone: Being able to understand the type of changing by just looking at a name and understanding the basics of a commit just by the title is useful in analysis and backtrack situations. +3. Building code habits and good practices: Maintaining structured commits also leads to more precise coding practices and coherent code changes. + +## Basic Rules +- Naming structure: +``` +: + +[optional body] +``` +- Naming prefixes (Types): + - fix: A commit of the type fix patches a bug in your codebase. + - feat: A commit of the type feat introduces a new feature to the codebase + - !: A commit that appends a ! after the type introduces a breaking change. A breaking change can be part of commits of any type. + - update: A commit of type update changes existing code or refactors functions without changing functionality of adding features in your codebase. + - build: A commit of type build changes build process in your codebase. + - docs: A commit of type docs is for creation or updating documentation in your codebase. + - chore: A commit of type chore is for every other minor task in your codebase. +- Commits must be prefixed with a type, which consists of a noun, feat, fix, etc., followed by the optional !, and required terminal colon and space. +- A description must immediately follow the colon and space after the type prefix. The description is a short summary of the code changes, e.g., fix: array parsing issue when multiple spaces were contained in string. +- A longer commit body may be provided after the short description, providing additional contextual information about the code changes. The body must begin one blank line after the description. +- A commit body is free-form and may consist of any number of newline separated paragraphs. + +# Bibliography +[1] “Conventional Branch,” Conventional Branch, 2025. https://conventional-branch.github.io/ (accessed 2025).
+[2] “Conventional Commits,” Conventional Commits. https://www.conventionalcommits.org/en/v1.0.0/ (accessed 2025). diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md index 408a57dd..db5068df 100644 --- a/docs/CODE_OF_CONDUCT.md +++ b/docs/CODE_OF_CONDUCT.md @@ -1,133 +1,90 @@ -Coding Style guide for LTFS -============= +# Code of Conduct -Naming conventions -------------- +## Our Pledge -- We don't use capital letters, except on defines and enumerators (see below). -- Public APIs are always prefixed by the name of that module: - * ltfs.c: ltfs_statfs(), ltfs_open(), ltfs_close(), ltfs_read() - * fs.c: fs_resolve_dentry(), fs_set_name(), fs_set_creation_time() +We pledge to make our community welcoming, safe, and equitable for all. +We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. -Spaces, tabs and commas -------------- +## Encouraged Behaviors -When indenting the code, always use TABs with 4 spaces. Do not replace TABs by spaces. Remove trailing spaces of a line and empty lines at the end of file. +While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. -When writing arguments to a function or defining enums, also use the following comma conventions: +With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including: +1. Respecting the **purpose of our community**, our activities, and our ways of gathering. +2. Engaging **kindly and honestly** with others. +3. Respecting **different viewpoints** and experiences. +4. **Taking responsibility** for our actions and contributions. +5. Gracefully giving and accepting **constructive feedback**. +6. Committing to **repairing harm** when it occurs. +7. Behaving in other ways that promote and sustain the **well-being of our community**. -``` -call_function(arg1, arg2, arg3); -call_another_function( - very_long_argument1, - very_long_argument2, - very_long_argument3 - ); - -enum very_cool_enumerator { - VERY_COOL_1, - VERY_COOL_2, - VERY_COOL_3, -}; -``` - -Macros and defines -------------- - -When defining wrappers around functions using macros do that using lowercase characters. Defines always go in uppercase. - -``` -#define wrapper_around_some_function(x,y) \ - ... - -#define LTFS_MAX_VALUE 2112 -``` - -Functions -------------- - -Return type, function name and its parameters should go all in a single line, except if the parameters are too long. - - -``` -void ltfs_function(void *params) -{ -} - -void ltfs_function_with_many_parameters(void *params1, - void *params2, void *params3) -{ -} -``` - -Conditional tests -------------- - -``` -if (condition) { - line 1; - line 2; -} else - line 3; - -if (another condition) - do this; -else - do that; - -if (yet another condition) { - /* - * It's ok to open brackets when adding comments, - * just to make it clear where the scope ends. - * That can improve readability when comments - * span across multiple lines. - */ - do something else; -} -``` - -Loops -------------- - -``` -for (x=start; x Date: Wed, 29 Jul 2026 19:35:31 +0200 Subject: [PATCH 05/10] fix: fixes and improvements to the ltfs_ordered_copy tool (#586) --- README.md | 1 + src/utils/ltfs_ordered_copy | 114 +++++++++++++++++++++++++++++------- 2 files changed, 93 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 8d393ba8..fc9ae6d5 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,7 @@ One thing you need to pay attention to here is, that the unmount command continu The [`ltfs_ordered_copy`](https://github.com/LinearTapeFileSystem/ltfs/wiki/ltfs_ordered_copy) is a program to copy files from source to destination with LTFS order optimization. It is written in python and it can work with both python2 and python3 (Python 2.7 or later is strongly recommended). You need to install the `pyxattr` module for both python2 and python3. +For nicer-looking progress bars while copying, it is also recommended you install `tqdm`. # Building the LTFS from this GitHub project diff --git a/src/utils/ltfs_ordered_copy b/src/utils/ltfs_ordered_copy index 5537964e..96f95c6a 100755 --- a/src/utils/ltfs_ordered_copy +++ b/src/utils/ltfs_ordered_copy @@ -44,6 +44,12 @@ import threading from logging import getLogger, basicConfig, NOTSET, CRITICAL, ERROR, WARNING, INFO, DEBUG from collections import deque +try: + from tqdm import tqdm + USE_TQDM = True +except ImportError: + USE_TQDM = False + class CopyItem: """""" def __init__(self, src, dst, vea_pre, cp_attr, cp_xattr, logger): #initialization @@ -77,15 +83,20 @@ class CopyItem: return (self.vuuid, self.part, self.start) - def run(self): + def _run_copy(self, progress): + with open(self.src, 'rb') as srcf, open(self.dst, 'wb') as dstf: + copyfileobj(srcf, dstf, progress.update) + + def run(self, progress): try: if len(self.vuuid): logger.debug('"{0}" ({2}) -> "{1}"'.format(self.src, self.dst, str(self.start))) else: logger.debug('"{0}" -> "{1}"'.format(self.src, self.dst)) - + progress.update_file(self.src) if self.cp_attr: #Copy data and metadata - shutil.copy2(self.src, self.dst) + self._run_copy(progress) + shutil.copystat(self.src, self.dst) if self.cp_xattr: # Capture EAs of the source file src_attributes = {} @@ -96,7 +107,8 @@ class CopyItem: for key in src_attributes: xattr.set(self.dst, key, src_attributes[key]) else: #Only copy data - shutil.copy(self.src, self.dst) + self._run_copy(progress) + shutil.copymode(self.src, self.dst) except Exception as e: self.logger.error('Failed to copy "{0}" to "{1}": {2}'.format(self.src, self.dst, str(str(e)))) return False @@ -116,9 +128,11 @@ class CopyQueue: self.items = 0 self.logger = logger self.sort_files = sort_files + self.total_bytes = 0 def add_copy_item(self, c): (u, p, s) = c.eval() + self.total_bytes += os.path.getsize(c.src) if u == '': # Source is not on LTFS self.direct.append(c) @@ -206,24 +220,83 @@ class CopyQueue: def get_size(self): return self.items +RESULT_LOCK = threading.Lock() + +BUFSIZE = 256 * 1024 * 1024 # 256MiB + +# Based on shutil's code +def copyfileobj(fsrc, fdst, callback, length=BUFSIZE): + try: + # check for optimisation opportunity + if "b" in fsrc.mode and "b" in fdst.mode and fsrc.readinto: + return _copyfileobj_readinto(fsrc, fdst, callback, length) + except AttributeError: + # one or both file objects do not support a .mode or .readinto attribute + pass + + fsrc_read = fsrc.read + fdst_write = fdst.write + + while True: + buf = fsrc_read(length) + if not buf: + break + fdst_write(buf) + callback(len(buf)) + +def _copyfileobj_readinto(fsrc, fdst, callback, length=BUFSIZE): + """readinto()/memoryview() based variant of copyfileobj(). + *fsrc* must support readinto() method and both files must be + open in binary mode. + """ + # Localize variable access to minimize overhead. + fsrc_readinto = fsrc.readinto + fdst_write = fdst.write + with memoryview(bytearray(length)) as mv: + while True: + n = fsrc_readinto(mv) + if not n: + break + elif n < length: + with mv[:n] as smv: + fdst.write(smv) + else: + fdst_write(mv) + callback(n) + class Progress: - def __init__(self, logger, title, num): #initialization + def __init__(self, logger, title, total_files, total_bytes): #initialization self.logger = logger self.title = title - self.num = num - self.cur = 0 + self.total_files = total_files + self.total_bytes = total_bytes + self.current_file = 0 + self.tqdm = None + + def update_file(self, name): + # Delay the initialization of tqdm to prevent console spam + if self.logger.getEffectiveLevel() == INFO and USE_TQDM and self.tqdm is None: + self.tqdm = tqdm(total=self.total_bytes, unit='B', unit_scale=True, unit_divisor=1024) - def update(self, step = 1): + self.current_file += 1 if self.logger.getEffectiveLevel() == INFO: - self.cur = self.cur + 1 - sys.stderr.write('\r{}: {}/{}'.format(self.title, self.cur, self.num)) - sys.stderr.flush() + if self.tqdm is not None: + self.tqdm.set_description(f'{name} [{self.current_file} / {self.total_files}]') + else: + sys.stderr.write('\r{}: {}/{}'.format(self.title, self.current_file, self.total_files)) + sys.stderr.flush() + + def update(self, bytes_add): + if self.tqdm: + self.tqdm.update(bytes_add) def finish(self): - if self.logger.getEffectiveLevel() == INFO: - logger.info("") + if self.tqdm is not None: + self.tqdm.close() + else: + if self.logger.getEffectiveLevel() == INFO: + logger.info("") -RESULT_LOCK = threading.Lock() def writer(logger, prog, q, r): while True: @@ -236,9 +309,7 @@ def writer(logger, prog, q, r): logger.error('writer thread error: ' + str(e)) exit(1) - prog.update() - - result = ci.run() + result = ci.run(prog) with RESULT_LOCK: if result: @@ -363,7 +434,7 @@ direct_write_threads = 8 try: sig = xattr.get(args.DEST, VEA_PREFIX + LTFS_SIG_VEA) - if sig.startswith("LTFS"): + if sig.startswith(b"LTFS"): logger.info("Destination {0} is LTFS".format(args.DEST)) direct_write_threads = 1 else: @@ -425,7 +496,7 @@ success = 0 fail = 0 direct = copyq.pop_direct() -prog_disk = Progress(logger, 'File copy from disk is on going', len(direct)) +prog_disk = Progress(logger, 'File copy from disk is on going', len(direct), copyq.total_bytes) if len(direct): logger.info("Copying on {} disk files with {} threads".format(len(direct), direct_write_threads)) writers = [] @@ -444,7 +515,7 @@ if len(direct): prog_disk.finish() # Copy files on LTFS -prog_tape = Progress(logger, 'File copy from tape is on going', copyq.get_size()) +prog_tape = Progress(logger, 'File copy from tape is on going', copyq.get_size(), copyq.total_bytes) (tape_key, tape) = copyq.pop_tape() while tape != None: logger.log(NOTSET + 1, "Processing {}".format(len(tape))) @@ -461,8 +532,7 @@ while tape != None: for start_block_key in start_block_list: file_ind = partition[start_block_key] for cp in file_ind: - prog_tape.update() - result = cp.run() + result = cp.run(prog_tape) if result: success = success + 1 else: From ba1695effa48af00de4998347f279abfbd237b07 Mon Sep 17 00:00:00 2001 From: Hugo Hurskainen Date: Wed, 29 Jul 2026 20:46:49 +0300 Subject: [PATCH 06/10] fix: resolve ltfs_ordered_copy issue when processing a single file. (#599) --- src/utils/ltfs_ordered_copy | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/utils/ltfs_ordered_copy b/src/utils/ltfs_ordered_copy index 96f95c6a..80560512 100755 --- a/src/utils/ltfs_ordered_copy +++ b/src/utils/ltfs_ordered_copy @@ -407,6 +407,9 @@ if args.DEST == None: logger.error('No destination is specified') exit(2) +if args.keep_tree is None: + args.keep_tree = '' + # Special case: # Copy source is only one file if args.recursive == False and len(args.SOURCE) == 1: @@ -458,9 +461,6 @@ if len(args.SOURCE) == 0: args.SOURCE.append(line.rstrip('\r\n')) logger.log(NOTSET + 1, 'Source: {}'.format(args.SOURCE)) -if args.keep_tree is None: - args.keep_tree = '' - # Create the list of copy item copyq = CopyQueue(logger, args.sort_files) for s in args.SOURCE: From aa0512555f9c30291acc7bd61d5a0db52a076395 Mon Sep 17 00:00:00 2001 From: Masafumi Horimoto Date: Thu, 30 Jul 2026 02:53:23 +0900 Subject: [PATCH 07/10] feat: introduce support for TANDBERG LTO-6 HH drive. (#605) --- src/tape_drivers/hp_tape.c | 1 + src/tape_drivers/hp_tape.h | 1 + 2 files changed, 2 insertions(+) diff --git a/src/tape_drivers/hp_tape.c b/src/tape_drivers/hp_tape.c index f94b4aea..23aa7327 100644 --- a/src/tape_drivers/hp_tape.c +++ b/src/tape_drivers/hp_tape.c @@ -68,6 +68,7 @@ struct supported_device *hp_supported_drives[] = { TAPEDRIVE( HP_VENDOR_ID, "Ultrium 7-SCSI", DRIVE_LTO7, "[Ultrium 7-SCSI]" ), /* HP Ultrium Gen 7 */ TAPEDRIVE( HPE_VENDOR_ID, "Ultrium 8-SCSI", DRIVE_LTO8, "[Ultrium 8-SCSI]" ), /* HPE Ultrium Gen 8 */ TAPEDRIVE( HPE_VENDOR_ID, "Ultrium 9-SCSI", DRIVE_LTO9, "[Ultrium 9-SCSI]" ), /* HPE Ultrium Gen 9 */ + TAPEDRIVE( TANDBERG_VENDOR_ID, "LTO-6 HH ", DRIVE_LTO6_HH, "[LTO-6 HH]" ), /* TANDBERG LTO-6 HH */ /* End of supported_devices */ NULL }; diff --git a/src/tape_drivers/hp_tape.h b/src/tape_drivers/hp_tape.h index 5d60dd9a..cc121bfa 100644 --- a/src/tape_drivers/hp_tape.h +++ b/src/tape_drivers/hp_tape.h @@ -67,6 +67,7 @@ extern "C" { #define HP_VENDOR_ID "HP" #define HPE_VENDOR_ID "HPE" +#define TANDBERG_VENDOR_ID "TANDBERG" extern struct error_table hp_tape_errors[]; From 135edb1961db24e7f41dcf65f373ce9564485e2b Mon Sep 17 00:00:00 2001 From: Matej Kenda Date: Wed, 29 Jul 2026 19:55:51 +0200 Subject: [PATCH 08/10] fix: prevent data loss on writes larger than the tape block size. (#607) --- src/iosched/unified.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/iosched/unified.c b/src/iosched/unified.c index f492e12f..71f9dcc1 100644 --- a/src/iosched/unified.c +++ b/src/iosched/unified.c @@ -1790,7 +1790,11 @@ ssize_t _unified_insert_new_request(const char *buf, off_t offset, size_t count, if (new_req->offset + new_req->count > dpr->file_size) dpr->file_size = new_req->offset + new_req->count; - return (ssize_t)count; + /* Only copy_count bytes were stored (one cache block at most); the + * caller's append loop must advance by that, not the full count, or + * everything past the first block of a larger-than-blocksize write is + * silently dropped. */ + return (ssize_t)copy_count; } /** From f5c51b18ec3ab86dff637c60913ba4680f9c5eab Mon Sep 17 00:00:00 2001 From: Matej Kenda Date: Wed, 29 Jul 2026 21:45:17 +0200 Subject: [PATCH 09/10] fix: resolve build and CLI issues. (#608) --- configure.ac | 2 +- src/libltfs/ltfs_thread.h | 8 ++++---- src/main.c | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/configure.ac b/configure.ac index faf4a937..994f68cb 100644 --- a/configure.ac +++ b/configure.ac @@ -377,7 +377,7 @@ if test "x${snmp}" != "xno" then SNMP_ENABLE="-D ENABLE_SNMP" SNMP_MODULE_CFLAGS="`net-snmp-config --cflags 2> /dev/null`"; - SNMP_MODULE_LIBS_A="`net-snmp-config --agent-libs` 2> /dev/null"; + SNMP_MODULE_LIBS_A="`net-snmp-config --agent-libs 2> /dev/null`"; SNMP_MODULE_LIBS="`net-snmp-config --libs 2> /dev/null`"; if test -z "$SNMP_MODULE_LIBS_A" then diff --git a/src/libltfs/ltfs_thread.h b/src/libltfs/ltfs_thread.h index eb80edad..0e5b7f35 100644 --- a/src/libltfs/ltfs_thread.h +++ b/src/libltfs/ltfs_thread.h @@ -67,6 +67,7 @@ extern "C" { #endif #include +#include #include #include #include @@ -208,11 +209,10 @@ static inline ltfs_thread_t ltfs_thread_self(void) static inline int ltfs_thread_yield(void) { -#if defined (__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) + /* sched_yield() is the POSIX standard and is available on every + * supported platform; pthread_yield() is deprecated since glibc 2.34 + * and absent on some libcs (e.g. musl). */ return sched_yield(); -#else - return pthread_yield(); -#endif } #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) diff --git a/src/main.c b/src/main.c index 533ec70d..05696035 100644 --- a/src/main.c +++ b/src/main.c @@ -704,7 +704,7 @@ int main(int argc, char **argv) if (priv->device_list) { ret = show_device_list(priv); ltfs_finish(); - return (ret != 0) ? 0 : 1; + return ret ? 1 : 0; } /* Validate sync option */ From 56baaf9c71bc74505a572f13427f96dfbe65ce74 Mon Sep 17 00:00:00 2001 From: Alexandra Rangel Date: Wed, 29 Jul 2026 14:41:05 -0600 Subject: [PATCH 10/10] fix: correct inverted status checks in the SCSI tape backend. (#627) Authored-by: Matej Kenda --- src/tape_drivers/linux/sg/sg_tape.c | 9 ++++++--- src/tape_drivers/osx/iokit/iokit_tape.c | 16 ++++++---------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/src/tape_drivers/linux/sg/sg_tape.c b/src/tape_drivers/linux/sg/sg_tape.c index 19f2beb8..47b60132 100644 --- a/src/tape_drivers/linux/sg/sg_tape.c +++ b/src/tape_drivers/linux/sg/sg_tape.c @@ -4630,7 +4630,9 @@ static bool is_ame(void *device) unsigned char buf[TC_MP_READ_WRITE_CTRL_SIZE] = {0}; const int ret = sg_modesense(device, TC_MP_READ_WRITE_CTRL, TC_MP_PC_CURRENT, 0, buf, sizeof(buf)); - if (ret != 0) { + /* sg_modesense returns the transferred byte count (> 0) on success and a + * negative error code on failure. */ + if (ret < 0) { char message[100] = {0}; sprintf(message, "failed to get MP %02Xh (%d)", TC_MP_READ_WRITE_CTRL, ret); ltfsmsg(LTFS_DEBUG, 30392D, __FUNCTION__, message); @@ -4720,7 +4722,7 @@ int sg_set_key(void *device, const unsigned char *keyalias, const unsigned char unsigned char buf[TC_MP_READ_WRITE_CTRL_SIZE] = {0}; ret = sg_modesense(device, TC_MP_READ_WRITE_CTRL, TC_MP_PC_CURRENT, 0, buf, sizeof(buf)); - if (ret != DEVICE_GOOD) + if (ret < 0) /* sg_modesense returns a byte count (> 0) on success */ goto out; ltfs_u16tobe(buffer + 0, sps); @@ -4767,8 +4769,9 @@ int sg_set_key(void *device, const unsigned char *keyalias, const unsigned char memset(buf, 0, sizeof(buf)); ret = sg_modesense(device, TC_MP_READ_WRITE_CTRL, TC_MP_PC_CURRENT, 0, buf, sizeof(buf)); - if (ret != DEVICE_GOOD) + if (ret < 0) /* sg_modesense returns a byte count (> 0) on success */ goto out; + ret = DEVICE_GOOD; /* normalize the byte count to a success code */ free: free(buffer); diff --git a/src/tape_drivers/osx/iokit/iokit_tape.c b/src/tape_drivers/osx/iokit/iokit_tape.c index 76f14628..ea6b86bd 100644 --- a/src/tape_drivers/osx/iokit/iokit_tape.c +++ b/src/tape_drivers/osx/iokit/iokit_tape.c @@ -285,7 +285,7 @@ static int _get_dump(struct iokit_data *priv, char *fname) long long data_length, buf_offset; int dumpfd = -1; int transfer_size, num_transfers, excess_transfer; - int i, bytes; + int bytes; unsigned char cap_buf[DUMP_HEADER_SIZE]; unsigned char *dump_buf; int buf_id; @@ -331,14 +331,11 @@ static int _get_dump(struct iokit_data *priv, char *fname) /* start to transfer data */ buf_offset = 0; - i = 0; ltfsmsg(LTFS_DEBUG, 30859D); while(num_transfers) { int length; - i++; - /* Allocation Length is transfer_size or excess_transfer*/ if(excess_transfer && num_transfers == 1) length = excess_transfer; @@ -3412,7 +3409,9 @@ int iokit_set_xattr(void *device, const char *name, const char *buf, size_t size free(null_terminated); ltfs_profiler_add_entry(priv->profiler, NULL, TAPEBEND_REQ_EXIT(REQ_TC_SETXATTR)); - return -LTFS_NO_XATTR; + /* ret is DEVICE_GOOD when one of the vendor attributes matched above; + * returning the hardcoded failure reported success as an error. */ + return ret; } #define BLOCKLEN_DATA_SIZE 6 @@ -3629,7 +3628,7 @@ static const char *_generate_product_name(const char *product_id) int iokit_get_device_list(struct tc_drive_info *buf, int count) { - int i, ret; + int i; int found = 0; int32_t devs = iokit_get_ssc_device_count(); int drive_type; @@ -3646,10 +3645,7 @@ int iokit_get_device_list(struct tc_drive_info *buf, int count) if( devs > 0 ) { for (i = 0; i < devs; i++) { if(iokit_find_ssc_device(iokit_device, i) != 0) - { - ret = -EDEV_DEVICE_UNOPENABLE; continue; - } drive_type = iokit_get_drive_identifier(iokit_device, &identifier); if (!drive_type) { if (found < count && buf) { @@ -3665,7 +3661,7 @@ int iokit_get_device_list(struct tc_drive_info *buf, int count) } found ++; } - ret = iokit_free_device(iokit_device); + iokit_free_device(iokit_device); } }