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.subdirectorymeans 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
| Field | Type | Description |
|---|---|---|
filename | string | The file name. |
content | string | The G-code text, at most 10,485,760 characters. |
fail_if_exists | bool | If true, refuse a name that is taken; if false (the default), replace the file. |
Response: UploadFileResponse
| Field | Type | Description |
|---|---|---|
path | string | The absolute path written. |
overwritten | bool | True if a file existed under the name just before the write. |
Error codes:
| Code | Condition |
|---|---|
INVALID_ARGUMENT | The name is rejected, or the content is empty or longer than 10,485,760 characters. |
ALREADY_EXISTS | fail_if_exists is true and something exists under the name. |
INTERNAL | The file could not be written, and the message names the error. |
RESOURCE_EXHAUSTED | The 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_existsneeds 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
| Field | Type | Description |
|---|---|---|
subdirectory | string | The directory to list, a file name; empty means the top. |
Response: ListFilesResponse
| Field | Type | Description |
|---|---|---|
files | FileInfo[] | The entries of the directory, without upload temporary files. |
directory | string | The absolute path listed. |
FileInfo:
| Field | Type | Description |
|---|---|---|
name | string | The entry’s name. |
path | string | Its path relative to the NC files directory. |
size_bytes | int64 | Its size in bytes. |
modified_timestamp | int64 | Its modification time in Unix nanoseconds. |
is_directory | bool | True for a directory. |
Error codes:
| Code | Condition |
|---|---|
NOT_FOUND | The subdirectory does not exist or is not a directory. |
INVALID_ARGUMENT | The name is rejected. |
INTERNAL | The 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
| Field | Type | Description |
|---|---|---|
filename | string | The file name. |
Response: DeleteFileResponse
| Field | Type | Description |
|---|---|---|
path | string | The absolute path deleted. |
Error codes:
| Code | Condition |
|---|---|
NOT_FOUND | The file does not exist. |
INVALID_ARGUMENT | The name is rejected, or it names a directory. |
INTERNAL | The 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
| Field | Type | Description |
|---|---|---|
filename | string | The file name. |
offset | int64 | The byte offset to start at, 0 by default. |
max_bytes | int32 | The most bytes to return; 0 or more than 1 MiB (1,048,576) means 1 MiB. |
Response: ReadFileResponse
| Field | Type | Description |
|---|---|---|
path | string | The absolute, canonical path read. |
content | bytes | The file’s bytes from offset. |
offset | int64 | The offset content starts at. |
total_size_bytes | int64 | The size of the whole file when it was read. |
end_of_file | bool | True if content reaches the end of the file. |
modified_timestamp | int64 | The 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.
contentis raw bytes, and a chunk can end inside a multi-byte UTF-8 character, so join the chunks before decoding.- If
modified_timestamportotal_size_byteschanges between chunks, the file was rewritten: start again from offset 0, and check at the end that you receivedtotal_size_bytesbytes. 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
offsetat or past the end is not an error:contentis empty andend_of_fileis true. - In Node.js,
modified_timestamparrives 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:
| Code | Condition |
|---|---|
NOT_FOUND | The file does not exist. |
INVALID_ARGUMENT | The 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. |
ABORTED | The file’s size or modification time changed during the read, so start again from offset 0. |
INTERNAL | The 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
| Field | Type | Description |
|---|---|---|
filename | string | The file name, which need not exist. |
Response: ResolveFileResponse
| Field | Type | Description |
|---|---|---|
path | string | The canonical path with symbolic links resolved, which is the file the other file RPCs act on for this name. |
exists | bool | True if something exists at that path. |
is_directory | bool | True if it is a directory. |
is_symlink | bool | True if resolving the name goes through a symbolic link at any component. |
is_loaded_program | bool | True if this is the file LinuxCNC has loaded (task.file). |
loaded_program | string | The canonical path of the loaded program, or the path as LinuxCNC gave it if it cannot be resolved, empty if none. |
interp_state | InterpState | The 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_programfalse: replacing the file withUploadFileor 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_programtrue andINTERP_IDLE: replacing it is safe, but LinuxCNC keeps the version it read until the program is opened again.is_loaded_programtrue 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:
| Code | Condition |
|---|---|
INVALID_ARGUMENT | The name is rejected, which is checked before LinuxCNC is needed. |
UNAVAILABLE | The server is not connected, its LinuxCNC is gone, or the status cannot be read, so the loaded program is unknown; see Errors and reasons. |
INTERNAL | The 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.