A native Go client and command-line tool for HDFS — no JVM and no Hadoop installation required.
Note
This project was originally created by Colin Marc and is now maintained by
@wgzhao. The canonical repository is
wgzhao/hdfs; the former colinmarc/hdfs
location redirects here.
HDFS for Go speaks the Hadoop protobuf RPC protocol directly to the namenode and the data-transfer protocol directly to datanodes. There is no JVM, no Hadoop install, and no cgo — just a small, fast Go library and a single static binary.
The library deliberately mirrors the standard library's os package, where
possible, and implements its interfaces, including os.FileInfo and
os.PathError. If you know your way around a local filesystem, you already
know your way around HDFS.
Here's what it looks like in action:
client, _ := hdfs.New("namenode:8020")
file, _ := client.Open("/mobydick.txt")
buf := make([]byte, 59)
file.ReadAt(buf, 48847)
fmt.Println(string(buf))
// => Abominable are the tumblers into which he pours his poison.For complete documentation, check out the Go reference.
- No JVM, no Hadoop install. The library and CLI are pure Go and cross-compile to a single dependency-free binary. Nothing needs to be installed on the machine that talks to HDFS.
- Fast. Starting
hdfscosts milliseconds instead of the seconds the JVM needs, which makes it a practical drop-in for shell scripts and CI jobs. - Idiomatic Go.
Open,Create,Stat,ReadDir,Mkdir,Remove,Walk,Chmod,Chown— anos-style API that returns*os.PathErrorand works withos.IsNotExistand friends. - Production security. Kerberos (SASL DIGEST-MD5), delegation tokens with automatic renewal, SASL integrity/privacy, AES-CTR data-transfer encryption, KMS-backed encryption zones (transparent data encryption), and block-token access to datanodes.
- Broad HDFS coverage. Buffered reads and writes with
hflush/hsyncsemantics, append, snapshots, POSIX ACLs, extended attributes, truncate, replication control, checksums, content summaries and filesystem stats. - Portable. Linux, macOS and Windows on amd64 and arm64, with release archives for every target — including native Apple Silicon.
- Battle-tested. The end-to-end test suite runs against a real Hadoop 3.x cluster in CI, including Kerberos, RPC protection, data-transfer protection and AES variants.
Grab the archive for your platform from the
releases page (.tar.gz for Linux
and macOS, .zip for Windows), or install with Go:
go install github.com/colinmarc/hdfs/v2/cmd/hdfs@latestNote
The Go module path is still github.com/colinmarc/hdfs/v2, even though the
canonical repository is now wgzhao/hdfs. Keep using that path in
go install, go get and import statements — it redirects to this
repository, so existing users can upgrade without changing their imports.
Then use it like you would hadoop fs:
hdfs ls /
hdfs mkdir -p /tmp/demo
hdfs put ./data.csv /tmp/demo/data.csv
hdfs cat /tmp/demo/data.csv | head
hdfs df -hIt picks up your Hadoop configuration automatically — see Installing the command-line client for the search order, tab completion and user configuration.
go get github.com/colinmarc/hdfs/v2package main
import (
"errors"
"fmt"
"io"
"log"
"os"
hdfs "github.com/colinmarc/hdfs/v2"
)
func main() {
client, err := hdfs.New("namenode:8020")
if err != nil {
log.Fatal(err)
}
defer client.Close()
f, err := client.Open("/data/events.json")
if err != nil {
if errors.Is(err, os.ErrNotExist) {
log.Println("file does not exist")
return
}
log.Fatal(err)
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(data))
}FileReader implements io.Reader, io.ReaderAt, io.Seeker and
io.Closer; FileWriter is buffered, and calling Close is mandatory.
| Capability | Library | hdfs CLI |
|---|---|---|
| Read, write, append | Yes | get, put, appendToFile |
Buffered writes with hflush/hsync |
Yes | — |
| Kerberos (DIGEST-MD5) | Yes | Yes |
| Delegation tokens with auto-renewal | Yes | Yes |
| SASL integrity / AES-CTR privacy | Yes | Yes |
| Encryption zones (KMS-backed TDE) | Yes | transparent |
| Snapshots | Yes | Yes |
| POSIX ACLs | Yes | getfacl, setfacl |
| Extended attributes (xattrs) | Yes | getfattr, setfattr |
Checksums, truncate, setrep, statfs |
Yes | Yes |
| Glob expansion, bash completion | — | Yes |
FileWriter is buffered; call Close once, after all data has been written.
Two methods provide the Java client's hflush and hsync semantics:
FileWriter.Sync()ishflush: it sends any buffered data to the datanodes with the sync flag set and waits for the whole pipeline to acknowledge it, so the data becomes visible to new readers. The file length recorded on the namenode (whatStatreturns) does not change.FileWriter.Hsync()ishsync: likeSync, and in addition calls the namenode'sfsyncRPC, so the current file length is persisted on the namenode and immediately visible toStat.
Both may block on the network, and can return a timeout error if a deadline
has been set. Neither replaces Close, which must still be called once all
data has been written. FileWriter.Flush() only drains buffered data to the
datanodes; unlike Sync, it does not make that data visible to readers.
w, _ := client.Create("/tmp/job-output")
w.Write([]byte("checkpoint 1\n"))
w.Sync() // new readers can see the checkpoint, even before CloseBy default, a datanode failure mid-write is fail-fast: the writer stops
accepting data, and Close returns ErrWritePipelineFailed instead of
completing a truncated file. Use IsErrWritePipelineFailed to test for it,
and Abandon to drop the partially written block before retrying or removing
the file. Set ClientOptions.DatanodeRecovery to opt into best-effort
recovery instead: the failed datanode is removed from the pipeline, the client
reconnects to the remaining replicas with the recovery handshake, replays any
unacknowledged packets, and continues writing — a subset of what the Java
client does.
Files inside an HDFS encryption zone are encrypted and decrypted transparently.
When the namenode reports an encrypted file, the client fetches the encrypted
data encryption key from the KMS named by the cluster's
dfs.encryption.key.provider.uri, unwraps it, and applies AES-CTR
(AES/CTR/NoPadding) to reads, writes and appends. This also covers the
command-line client, so hdfs cat, put and get work on encrypted files
unchanged.
No extra client options are needed on a simple-auth cluster. On a Kerberized
cluster, KMS requests authenticate with the configured KerberosClient using
SPNEGO. Only the AES-CTR cipher suite is supported.
Since it doesn't have to wait for the JVM to start up, the CLI is a lot faster
than hadoop fs:
$ time hadoop fs -ls / > /dev/null
real 0m2.218s
user 0m2.500s
sys 0m0.376s
$ time hdfs ls / > /dev/null
real 0m0.015s
user 0m0.004s
sys 0m0.004s
Best of all, it comes with bash tab completion for paths on Unix-like systems.
Along with the library, this repo contains a command-line client for HDFS. Like the library, its primary aim is to be idiomatic, by enabling your favorite unix verbs:
$ hdfs --help
Usage: hdfs COMMAND
The flags available are a subset of the POSIX ones, but should behave similarly.
Valid commands:
ls [-lahRtuU] [FILE]...
rm [-rf] FILE...
mv [-nT] SOURCE... DEST
mkdir [-p] FILE...
touch [-c] FILE...
touchz FILE...
chmod [-R] OCTAL-MODE FILE...
chown [-R] OWNER[:GROUP] FILE...
chgrp [-R] GROUP FILE...
cat SOURCE...
head [-n LINES | -c BYTES] SOURCE...
tail [-n LINES | -c BYTES] SOURCE...
test [-defsz] FILE...
du [-sh] FILE...
df [-h]
count [-qhvue] FILE...
stat [FORMAT] FILE...
find [FILE...] [-name PATTERN] [-iname PATTERN] [-print | -print0]
checksum FILE...
text [-ignoreCrc] SOURCE...
get SOURCE... DEST
getmerge [-n] SOURCE DEST
copyToLocal SOURCE... DEST
put [-f] SOURCE... DEST
copyFromLocal [-f] SOURCE... DEST
moveFromLocal [-f] SOURCE... DEST
moveToLocal SOURCE DEST
appendToFile SOURCE... DEST
cp [-fpd] SOURCE... DEST
rmdir [--ignore-fail-on-non-empty] DIR...
truncate SIZE FILE
setrep [-Rw] REPLICATION FILE...
createSnapshot DIR [NAME]
deleteSnapshot DIR NAME
renameSnapshot DIR OLD NEW
getfacl [-R] PATH...
setfacl [-R] {-b|-k} [-m|-x ACL] PATH...
setfacl [-R] --set ACL PATH...
getfattr [-R] {-n NAME | -d} [-e ENC] PATH...
setfattr {-n NAME [-v VALUE] | -x NAME} PATH...
usage [COMMAND...]
Like unix ls, entries are sorted by name by default. The sorting flags
mirror the unix ones:
-t: sort by modification time, newest first-c: sort by inode change time (ctime)-u: sort by last access time-U: do not sort; list entries in directory order
However, the HDFS protocol only exposes the modification time and the access time of a file; there is no ctime. As a result:
-cfalls back to sorting by modification time (behaves like-t).-usorts by access time, but if access time tracking is disabled on the namenode (dfs.namenode.accesstime.precision = 0, the default), all access times are zero and it falls back to sorting by modification time as well. Note that enabling access time tracking adds a namenode write on every file read, so it is often disabled in production.
When multiple time flags are combined, -U wins (no sorting), followed by
-c, -u, and -t. Ties are broken by name, ascending.
Grab the archive for your platform from the
releases page (.tar.gz for
Linux and macOS, .zip for Windows) and unzip it wherever you like.
To configure the client, it looks for your Hadoop configuration
(core-site.xml, hdfs-site.xml, and mapred-site.xml) in these locations,
in order:
HADOOP_CONF_DIR$HADOOP_HOME/etc/hadoop$HADOOP_HOME/conf/etc/hadoop/conf(on Linux and other non-Windows systems)
You only need to set an environment variable if your configuration lives somewhere else:
$ export HADOOP_CONF_DIR="/path/to/hadoop/conf"
On Windows, use set (or the system environment variable editor) instead:
> set HADOOP_CONF_DIR=C:\hadoop\conf
To install tab completion globally on linux, copy or link the bash_completion
file which comes with the tarball into the right place:
$ ln -sT bash_completion /etc/bash_completion.d/gohdfs
By default on non-kerberized clusters, the HDFS user is set to the currently-logged-in user. You can override this with another environment variable:
$ export HADOOP_USER_NAME=username
This applies both to the commandline client and to the library's hdfs.New,
mirroring the behavior of the official Java client under simple
authentication.
The library and command-line client are pure Go and require no cgo. Supported targets:
| Operating system | Architectures |
|---|---|
| Linux | amd64, arm64 |
| macOS | amd64, arm64 |
| Windows | amd64, arm64 |
Release archives are published for all of these targets (.tar.gz for Linux
and macOS, .zip for Windows), including native Apple Silicon builds.
Go 1.25 or newer is required (go.mod); see the Go installation guide.
$ git clone https://github.com/wgzhao/hdfs.git
$ cd hdfs
$ go build -o hdfs ./cmd/hdfs
To produce a binary for another platform, set GOOS and GOARCH. For
example, to build a native Apple Silicon binary:
$ GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 \
go build -trimpath \
-ldflags "-X main.version=$(git describe --tags --always)" \
-o hdfs-darwin-arm64 ./cmd/hdfs
And for 64-bit Windows:
$ GOOS=windows GOARCH=amd64 CGO_ENABLED=0 \
go build -o hdfs.exe ./cmd/hdfs
The Makefile and shell scripts are Unix-oriented; on Windows, invoke
go build and go test directly.
Like hadoop fs, the commandline client expects a ccache file in the default
location: /tmp/krb5cc_<uid>. That means it should 'just work' to use kinit:
$ kinit bob@EXAMPLE.com
$ hdfs ls /
If that doesn't work, try setting the KRB5CCNAME environment variable to
wherever you have the ccache saved.
On Windows, the client looks for krb5.ini under
%ProgramData%\MIT\Kerberos5 or %SystemRoot%, and only FILE: ccaches
are supported. Set KRB5_CONFIG and KRB5CCNAME explicitly if your
Kerberos installation uses different locations, for example:
> set KRB5_CONFIG=C:\ProgramData\MIT\Kerberos5\krb5.ini
> set KRB5CCNAME=FILE:C:\Users\me\krb5cc
> hdfs ls /
macOS may keep Kerberos credentials in an in-memory API: cache by default;
point KRB5CCNAME at a FILE: ccache in that case.
On kerberized clusters where repeated kinit round-trips are impractical
(for example, inside long-running jobs or CI), you can authenticate with an
HDFS delegation token instead. Obtain one from the cluster (for example with
hdfs fetchdt), then point HADOOP_TOKEN_FILE_LOCATION at the token file:
$ hdfs fetchdt /tmp/dt.token
$ export HADOOP_TOKEN_FILE_LOCATION=/tmp/dt.token
$ hdfs ls /
The token is used for both namenode authentication (SASL DIGEST-MD5) and
datanode block access. The client renews the token automatically in the
background (at half its remaining lifetime), so a token fetched once stays
valid across the lifetime of a long-running process, up to the cluster's
dfs.namenode.delegation.token.max-lifetime.
Tokens are also available to library users: pass ClientOptions.Token
directly, or create/renew/cancel tokens programmatically with
Client.GetDelegationToken, Client.RenewDelegationToken and
Client.CancelDelegationToken. To reuse a token file, load it with
LoadDelegationTokenFile:
token, err := hdfs.LoadDelegationTokenFile("/tmp/dt.token")
if err != nil {
log.Fatal(err)
}
client, err := hdfs.NewClient(hdfs.ClientOptions{
Addresses: []string{"namenode:9000"},
Token: token,
})
$ make # build the ./hdfs binary
$ make test # build, run the Go tests, then the bats CLI tests
The Go tests in the repository root are end-to-end tests: they require a
reachable HDFS cluster configured via HADOOP_CONF_DIR (or HADOOP_HOME),
plus the fixtures created by .github/scripts/fixtures.sh. The CI workflow in
.github/workflows/tests.yml downloads and starts a local Hadoop cluster
before running them. Tests for hadoopconf and the internal/ packages run
without a cluster:
$ go test ./hadoopconf ./internal/...
See CONTRIBUTING.md for the full development workflow.
This library uses "Version 9" of the HDFS protocol, which means it should work with hadoop distributions based on 2.2.x and above, as well as 3.x.
Bug reports, feature requests and pull requests are welcome. If you are reporting a bug, please include your Hadoop version, how the client was configured (simple auth, Kerberos, or delegation token), and the error message. See CONTRIBUTING.md for build and test instructions.
This library is heavily indebted to snakebite.
