File management

These LinuxCNCService RPCs work on files in the NC files directory, by default /home/linuxcnc/linuxcnc/nc_files (set it with --nc-files or LINUXCNC_NC_FILES; see NC files directory).

UploadFile, ListFiles, DeleteFile and ReadFile do not need LinuxCNC and work while the server waits for it. ResolveFile reads LinuxCNC’s status. An upload holds at most 10 MiB of text, and a read returns at most 1 MiB per call.

File names

A name is relative to the NC files directory, such as part1.ngc or subdir/part1.ngc, or an absolute path inside it. A symbolic link is followed only if its target is inside the directory. Every file RPC rejects these names with INVALID_ARGUMENT:

  • an empty name, or one of only whitespace (an empty ListFiles.subdirectory means the directory itself);
  • a name with a null byte;
  • a name that leads outside the directory;
  • a name that runs into a symbolic link loop.

UploadFile

Write a file into the NC files directory.

rpc UploadFile(UploadFileRequest) returns (UploadFileResponse)

Request: UploadFileRequest

FieldTypeDescription
filenamestringThe file name.
contentstringThe G-code text, at most 10,485,760 characters.
fail_if_existsboolIf true, refuse a name that is taken; if false (the default), replace the file.

Response: UploadFileResponse

FieldTypeDescription
pathstringThe absolute path written.
overwrittenboolTrue if a file existed under the name just before the write.

Error codes:

CodeCondition
INVALID_ARGUMENTThe name is rejected, or the content is empty or longer than 10,485,760 characters.
ALREADY_EXISTSfail_if_exists is true and something exists under the name.
INTERNALThe file could not be written, and the message names the error.
RESOURCE_EXHAUSTEDThe request is larger than the server’s 11 MiB (11,534,336-byte) receive limit, and gRPC rejects it before UploadFile runs.

With fail_if_exists, of two uploads of the same new name only one succeeds, and overwritten is always false. Existence is checked first, so an existing directory, the NC files directory itself included, gets ALREADY_EXISTS. Without fail_if_exists, a name that is a directory or the NC files directory itself gets INTERNAL, and so does an upload with fail_if_exists to a file system without hard links.

The 10 MiB limit counts characters, not bytes. Text with non-ASCII characters takes more than one byte per character, so it can stay under the character limit and still exceed the receive limit.

The server writes the content to a temporary file next to the destination and renames it into place once it is complete, so a reader never sees part of an upload and a failed upload leaves the previous file as it was.

  • A replaced file is a new file with the old one’s permission bits. Another hard link to the old file, or a program that has it open, keeps the old content. A file the server may not write is not replaced (INTERNAL).
  • A file another client creates between the check and the write is replaced and reported as overwritten: false.
  • fail_if_exists needs hard links, which some network and FAT mounts lack; there, upload without it.
  • The temporary file, .linuxcnc-grpc-upload-<random>.tmp, is left behind only if the server is killed during the upload, and can then be deleted.

Example (Python):

request = linuxcnc_pb2.UploadFileRequest(
    filename="my_part.ngc",
    content="G0 X10 Y10\nG1 Z-5 F100\nM2\n"
)
response = stub.UploadFile(request)
print(f"Written to: {response.path}")

ListFiles

List one directory of the NC files directory.

rpc ListFiles(ListFilesRequest) returns (ListFilesResponse)

Request: ListFilesRequest

FieldTypeDescription
subdirectorystringThe directory to list, a file name; empty means the top.

Response: ListFilesResponse

FieldTypeDescription
filesFileInfo[]The entries of the directory, without upload temporary files.
directorystringThe absolute path listed.

FileInfo:

FieldTypeDescription
namestringThe entry’s name.
pathstringIts path relative to the NC files directory.
size_bytesint64Its size in bytes.
modified_timestampint64Its modification time in Unix nanoseconds.
is_directoryboolTrue for a directory.

Error codes:

CodeCondition
NOT_FOUNDThe subdirectory does not exist or is not a directory.
INVALID_ARGUMENTThe name is rejected.
INTERNALThe directory could not be listed, or the NC files directory could not be resolved (a symbolic link loop), and the message names the error.

Example (Python):

response = stub.ListFiles(linuxcnc_pb2.ListFilesRequest())
for f in response.files:
    print(f"{f.name}: {f.size_bytes} bytes")

DeleteFile

Delete a file from the NC files directory.

rpc DeleteFile(DeleteFileRequest) returns (DeleteFileResponse)

Request: DeleteFileRequest

FieldTypeDescription
filenamestringThe file name.

Response: DeleteFileResponse

FieldTypeDescription
pathstringThe absolute path deleted.

Error codes:

CodeCondition
NOT_FOUNDThe file does not exist.
INVALID_ARGUMENTThe name is rejected, or it names a directory.
INTERNALThe file could not be deleted (no permission, for example), and the message names the error.

Example (Python):

response = stub.DeleteFile(
    linuxcnc_pb2.DeleteFileRequest(filename="my_part.ngc")
)
print(f"Deleted: {response.path}")

DeleteFile and UploadFile act on the file a name resolves to. If the name is a symbolic link to another file in the directory, the link’s target is deleted or replaced and the link stays. ResolveFile shows what a name resolves to.

ReadFile

Read a file from the NC files directory, whole or in chunks.

rpc ReadFile(ReadFileRequest) returns (ReadFileResponse)

Request: ReadFileRequest

FieldTypeDescription
filenamestringThe file name.
offsetint64The byte offset to start at, 0 by default.
max_bytesint32The most bytes to return; 0 or more than 1 MiB (1,048,576) means 1 MiB.

Response: ReadFileResponse

FieldTypeDescription
pathstringThe absolute, canonical path read.
contentbytesThe file’s bytes from offset.
offsetint64The offset content starts at.
total_size_bytesint64The size of the whole file when it was read.
end_of_fileboolTrue if content reaches the end of the file.
modified_timestampint64The modification time in Unix nanoseconds.

One response carries at most 1 MiB, which fits a gRPC client’s default 4 MB receive limit. For a larger file of any size, call again with offset advanced by the length of content until end_of_file is true.

  • content is raw bytes, and a chunk can end inside a multi-byte UTF-8 character, so join the chunks before decoding.
  • If modified_timestamp or total_size_bytes changes between chunks, the file was rewritten: start again from offset 0, and check at the end that you received total_size_bytes bytes. A rewrite with the same size and time cannot be seen, so don’t read a file you know is being written.
  • If the file changes while the server reads one chunk, the call fails with ABORTED: start again from offset 0.
  • An offset at or past the end is not an error: content is empty and end_of_file is true.
  • In Node.js, modified_timestamp arrives in milliseconds, so comparing it between chunks can miss a same-size rewrite within one millisecond; see 64-bit integers in Node.js/TypeScript.

Error codes:

CodeCondition
NOT_FOUNDThe file does not exist.
INVALID_ARGUMENTThe name is rejected, the name is not a regular file (a directory, FIFO or device is refused unread), or offset or max_bytes is negative.
ABORTEDThe file’s size or modification time changed during the read, so start again from offset 0.
INTERNALThe file could not be read (no permission, for example), and the message names the error.

Example (Python):

def read_nc_file(stub, filename):
    content = b""
    first_version = None
    while True:
        chunk = stub.ReadFile(
            linuxcnc_pb2.ReadFileRequest(filename=filename, offset=len(content)),
            timeout=30,
        )
        version = (chunk.modified_timestamp, chunk.total_size_bytes)
        if first_version not in (None, version):
            raise RuntimeError(f"{filename} changed while it was being read")
        first_version = version
        content += chunk.content
        if chunk.end_of_file:
            if len(content) != chunk.total_size_bytes:
                raise RuntimeError(f"{filename} changed while it was being read")
            return content.decode()

print(read_nc_file(stub, "my_part.ngc"))

The Go client wrapper in the root package (github.com/dougcalobrisi/linuxcnc-grpc, created with linuxcnc.NewClient) has a ReadFile(ctx, filename) helper that runs the same loop. The generated client in packages/go has only the plain RPC.

ResolveFile

Resolve a name to its canonical path and say whether it is the program LinuxCNC has loaded. Call it before replacing or deleting a file.

rpc ResolveFile(ResolveFileRequest) returns (ResolveFileResponse)

Request: ResolveFileRequest

FieldTypeDescription
filenamestringThe file name, which need not exist.

Response: ResolveFileResponse

FieldTypeDescription
pathstringThe canonical path with symbolic links resolved, which is the file the other file RPCs act on for this name.
existsboolTrue if something exists at that path.
is_directoryboolTrue if it is a directory.
is_symlinkboolTrue if resolving the name goes through a symbolic link at any component.
is_loaded_programboolTrue if this is the file LinuxCNC has loaded (task.file).
loaded_programstringThe canonical path of the loaded program, or the path as LinuxCNC gave it if it cannot be resolved, empty if none.
interp_stateInterpStateThe interpreter state when checked.

is_loaded_program compares canonical paths and files on disk (hard links) as they are now, and is false if the loaded program’s path cannot be resolved. If the loaded program’s name was given a new file after LinuxCNC opened it (by an upload, or an editor that saves by renaming), another name for the old file LinuxCNC still reads reports false. LinuxCNC keeps reporting the last program it opened, so a loaded program is in use only while interp_state is not INTERP_IDLE. A safe rule:

  • is_loaded_program false: replacing the file with UploadFile or deleting it is safe, since both leave the old content alone. A tool that writes into the file in place should first rule out the case above.
  • is_loaded_program true and INTERP_IDLE: replacing it is safe, but LinuxCNC keeps the version it read until the program is opened again.
  • is_loaded_program true and any other state: leave the file alone.

The answer is a snapshot: a program can be loaded right after you ask, and UploadFile and DeleteFile do not check again.

Error codes:

CodeCondition
INVALID_ARGUMENTThe name is rejected, which is checked before LinuxCNC is needed.
UNAVAILABLEThe server is not connected, its LinuxCNC is gone, or the status cannot be read, so the loaded program is unknown; see Errors and reasons.
INTERNALThe NC files directory could not be resolved (a symbolic link loop), or the status read failed unexpectedly, and the message names the error.

Example (Python):

resolved = stub.ResolveFile(
    linuxcnc_pb2.ResolveFileRequest(filename="my_part.ngc")
)
if resolved.is_loaded_program and resolved.interp_state != linuxcnc_pb2.INTERP_IDLE:
    print(f"{resolved.path} is running; not touching it")
else:
    stub.DeleteFile(linuxcnc_pb2.DeleteFileRequest(filename="my_part.ngc"))

Changes to the directory during a call

The file RPCs check a name, then act on it. If a local program replaces the last component of the name with a symbolic link in between, ReadFile fails, UploadFile replaces the link itself (or gets ALREADY_EXISTS with fail_if_exists), DeleteFile removes the link itself, and ListFiles lists the directory the link points to. The server does not defend against a hostile local user rearranging directories higher up the path.