### Install: go get bitset Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/bits-and-blooms/bitset/README.md Installation command for the bitset library using go get. ```bash go get github.com/bits-and-blooms/bitset ``` -------------------------------- ### Install Codec Library Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/hashicorp/go-msgpack/codec/README.md Use the go get command to install the library in your Go environment. ```bash go get github.com/ugorji/go/codec ``` -------------------------------- ### Install runc using go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/opencontainers/runc/README.md Installs runc using go get and then builds it from the GOPATH source directory. ```bash go get github.com/opencontainers/runc cd $GOPATH/src/github.com/opencontainers/runc make sudo make install ``` -------------------------------- ### Install utfbom with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/dimchansky/utfbom/README.md Install the utfbom package using the go get command. ```shell go get -u github.com/dimchansky/utfbom ``` -------------------------------- ### Install and run local Go doc site with pkgsite Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.opentelemetry.io/otel/CONTRIBUTING.md Use these commands to install and run a local Go documentation site. Requires Go toolchain. Run `go install golang.org/x/pkgsite/cmd/pkgsite@latest` first, then `pkgsite` to start the server. ```sh go install golang.org/x/pkgsite/cmd/pkgsite@latest pkgsite ``` -------------------------------- ### Signal handler setup example Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/armon/go-metrics/README.md Sets up an in-memory sink and signal handler, then runs some code that records metrics. ```go // Setup the inmem sink and signal handler inm := metrics.NewInmemSink(10*time.Second, time.Minute) sig := metrics.DefaultInmemSignal(inm) metrics.NewGlobal(metrics.DefaultConfig("service-name"), inm) // Run some code inm.SetGauge([]string{"foo"}, 42) inm.EmitKey([]string{"bar"}, 30) inm.IncrCounter([]string{"baz"}, 42) inm.IncrCounter([]string{"baz"}, 1) inm.IncrCounter([]string{"baz"}, 80) inm.AddSample([]string{"method", "wow"}, 42) inm.AddSample([]string{"method", "wow"}, 100) inm.AddSample([]string{"method", "wow"}, 22) ``` -------------------------------- ### Run example SCTP server and client Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/ishidawataru/sctp/README.md Commands to build and run the example SCTP server and client from the example directory. The server is started with the -server flag, and both use the same port and IP addresses. ```shell $ cd example $ go build $ # run example SCTP server $ ./example -server -port 1000 -ip 10.10.0.1,10.20.0.1 $ # run example SCTP client $ ./example -port 1000 -ip 10.10.0.1,10.20.0.1 ``` -------------------------------- ### Install packageurl-go with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/package-url/packageurl-go/README.md Install the packageurl-go library using the standard Go module command. ```bash go get -u github.com/package-url/packageurl-go ``` -------------------------------- ### Install uniseg with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/rivo/uniseg/README.md Installs the uniseg package using the go get command. ```bash go get github.com/rivo/uniseg ``` -------------------------------- ### Using ipvs: create handle and get services Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/moby/ipvs/README.md This example shows how to initialize an ipvs handle and fetch the list of services. It logs a fatal error if either operation fails. ```go import ( "log" "github.com/moby/ipvs" ) func main() { handle, err := ipvs.New("") if err != nil { log.Fatalf("ipvs.New: %s", err) } svcs, err := handle.GetServices() if err != nil { log.Fatalf("handle.GetServices: %s", err) } } ``` -------------------------------- ### Install godbus/dbus with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/godbus/dbus/v5/README.md Install the library using the go get command. Requires Go 1.12 or later. ```bash go get github.com/godbus/dbus/v5 ``` -------------------------------- ### Usage example: Set, Get, and Delete with JSON Pointer Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/xeipuuv/gojsonpointer/README.md Shows how to create a JSON pointer, set a new value, get the value, and delete a key from a JSON document. The example outputs the updated JSON after deletion. ```go jsonText := `{ "name": "Bobby B", "occupation": { "title" : "King", "years" : 15, "heir" : "Joffrey B" } }` var jsonDocument map[string]interface{} json.Unmarshal([]byte(jsonText), &jsonDocument) //create a JSON pointer pointerString := "/occupation/title" pointer, _ := NewJsonPointer(pointerString) //SET a new value for the "title" in the document pointer.Set(jsonDocument, "Supreme Leader of Westeros") //GET the new "title" from the document title, _, _ := pointer.Get(jsonDocument) fmt.Println(title) //outputs "Supreme Leader of Westeros" //DELETE the "heir" from the document deletePointer := NewJsonPointer("/occupation/heir") deletePointer.Delete(jsonDocument) b, _ := json.Marshal(jsonDocument) fmt.Println(string(b)) //outputs `{"name":"Bobby B","occupation":{"title":"Supreme Leader of Westeros","years":15}}` ``` -------------------------------- ### Install levenshtein package Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/agext/levenshtein/README.md Install the package using the go get command. ```bash go get github.com/agext/levenshtein ``` -------------------------------- ### Setup and teardown network with go-cni Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/containerd/go-cni/README.md Complete usage example from the README. Initializes go-cni, loads CNI config, sets up and tears down a network, and prints the IP of the default interface. Requires CNI configuration in "/etc/cni/net.d" and plugins in "/opt/cni/bin". ```Go package main import ( "context" "fmt" "log" gocni "github.com/containerd/go-cni" ) func main() { id := "example" netns := "/var/run/netns/example-ns-1" // CNI allows multiple CNI configurations and the network interface // will be named by eth0, eth1, ..., ethN. ifPrefixName := "eth" defaultIfName := "eth0" // Initializes library l, err := gocni.New( // one for loopback network interface gocni.WithMinNetworkCount(2), gocni.WithPluginConfDir("/etc/cni/net.d"), gocni.WithPluginDir([]string{"/opt/cni/bin"}), // Sets the prefix for network interfaces, eth by default gocni.WithInterfacePrefix(ifPrefixName)) if err != nil { log.Fatalf("failed to initialize cni library: %v", err) } // Load the cni configuration if err := l.Load(gocni.WithLoNetwork, gocni.WithDefaultConf); err != nil { log.Fatalf("failed to load cni configuration: %v", err) } // Setup network for namespace. labels := map[string]string{ "K8S_POD_NAMESPACE": "namespace1", "K8S_POD_NAME": "pod1", "K8S_POD_INFRA_CONTAINER_ID": id, // Plugin tolerates all Args embedded by unknown labels, like // K8S_POD_NAMESPACE/NAME/INFRA_CONTAINER_ID... "IgnoreUnknown": "1", } ctx := context.Background() // Teardown network defer func() { if err := l.Remove(ctx, id, netns, gocni.WithLabels(labels)); err != nil { log.Fatalf("failed to teardown network: %v", err) } }() // Setup network result, err := l.Setup(ctx, id, netns, gocni.WithLabels(labels)) if err != nil { log.Fatalf("failed to setup network for namespace: %v", err) } // Get IP of the default interface IP := result.Interfaces[defaultIfName].IPConfigs[0].IP.String() fmt.Printf("IP of the default interface %s:%s", defaultIfName, IP) } ``` -------------------------------- ### Install OpenCensus Go with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.opencensus.io/README.md Use this command to install the OpenCensus Go library. The API is still evolving, so vendoring or a dependency management tool is recommended. ```bash $ go get -u go.opencensus.io ``` -------------------------------- ### Install sigs.k8s.io/yaml Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/sigs.k8s.io/yaml/README.md Installs the sigs.k8s.io/yaml package using go get. ```shell $ go get sigs.k8s.io/yaml ``` -------------------------------- ### Install sockaddr CLI with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/hashicorp/go-sockaddr/README.md Installs the sockaddr command-line utility from the go-sockaddr repository. Use this to access the CLI for administrative or testing purposes. ```text $ go get -u github.com/hashicorp/go-sockaddr/cmd/sockaddr ``` -------------------------------- ### Install stats package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/montanaflynn/stats/README.md Installs the stats package using the go get command. ```bash go get github.com/montanaflynn/stats ``` -------------------------------- ### Install binary Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/contributing/set-up-dev-env.md Run make install to copy the built binary to the container's /usr/local/bin/ directory. ```none # make install ``` -------------------------------- ### Install Gorilla Mux with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/gorilla/mux/README.md Install the package using the Go toolchain. Requires a correctly configured Go environment. ```sh go get -u github.com/gorilla/mux ``` -------------------------------- ### Install and build github.com/miekg/dns Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/miekg/dns/README.md Install and build the library using Go modules. Run these commands in order to fetch the package and compile it. ```shell go get github.com/miekg/dns ``` ```shell go build github.com/miekg/dns ``` -------------------------------- ### Start query with Query.Run Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/cloud.google.com/go/CHANGES.md Replacement for the removed client.Copy when starting a query job. ```go client.Copy(ctx, table, query) ``` ```go query.Run(ctx) ``` -------------------------------- ### Simple usage example of go-memdb Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/hashicorp/go-memdb/README.md This example shows how to define a schema, create a database, insert records, and perform queries including a range scan. It demonstrates the use of memdb.DBSchema, memdb.NewMemDB, transactions, and the First, Get, and LowerBound methods. The output shows the expected results of the queries. ```go // Create a sample struct type Person struct { Email string Name string Age int } // Create the DB schema schema := &memdb.DBSchema{ Tables: map[string]*memdb.TableSchema{ "person": &memdb.TableSchema{ Name: "person", Indexes: map[string]*memdb.IndexSchema{ "id": &memdb.IndexSchema{ Name: "id", Unique: true, Indexer: &memdb.StringFieldIndex{Field: "Email"}, }, "age": &memdb.IndexSchema{ Name: "age", Unique: false, Indexer: &memdb.IntFieldIndex{Field: "Age"}, }, }, }, }, } // Create a new data base db, err := memdb.NewMemDB(schema) if err != nil { panic(err) } // Create a write transaction txn := db.Txn(true) // Insert some people people := []*Person{ &Person{"joe@aol.com", "Joe", 30}, &Person{"lucy@aol.com", "Lucy", 35}, &Person{"tariq@aol.com", "Tariq", 21}, &Person{"dorothy@aol.com", "Dorothy", 53}, } for _, p := range people { if err := txn.Insert("person", p); err != nil { panic(err) } } // Commit the transaction txn.Commit() // Create read-only transaction txn = db.Txn(false) defer txn.Abort() // Lookup by email raw, err := txn.First("person", "id", "joe@aol.com") if err != nil { panic(err) } // Say hi! fmt.Printf("Hello %s!\n", raw.(*Person).Name) // List all the people it, err := txn.Get("person", "id") if err != nil { panic(err) } fmt.Println("All the people:") for obj := it.Next(); obj != nil; obj = it.Next() { p := obj.(*Person) fmt.Printf(" %s\n", p.Name) } // Range scan over people with ages between 25 and 35 inclusive it, err = txn.LowerBound("person", "age", 25) if err != nil { panic(err) } fmt.Println("People aged 25 - 35:") for obj := it.Next(); obj != nil; obj = it.Next() { p := obj.(*Person) if p.Age > 35 { break } fmt.Printf(" %s is aged %d\n", p.Name, p.Age) } // Output: // Hello Joe! // All the people: // Dorothy // Joe // Lucy // Tariq // People aged 25 - 35: // Joe is aged 30 // Lucy is aged 35 ``` -------------------------------- ### Install gojsonschema with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/xeipuuv/gojsonschema/README.md Install the library using the standard Go package manager. ```bash go get github.com/xeipuuv/gojsonschema ``` -------------------------------- ### Install copystructure with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/mitchellh/copystructure/README.md Standard Go installation command to fetch the copystructure library. Run this in your terminal to add the package to your Go module. ```shell $ go get github.com/mitchellh/copystructure ``` -------------------------------- ### Install Cobra library with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/spf13/cobra/README.md Use this command to install the latest version of the Cobra library. Run it before importing Cobra in your application. ```bash go get -u github.com/spf13/cobra@latest ``` -------------------------------- ### Automated build, install, and run Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/contributing/set-up-dev-env.md Automates the build, install, and run steps. After it completes, hit ctrl-z, then run bg 1 and hit enter to resume the daemon in the background. ```none hack/make.sh binary install-binary run ``` -------------------------------- ### V-style logging examples Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/k8s.io/klog/v2/README.md Examples from the V function documentation showing conditional and direct V-style logging. ```go if glog.V(2) { glog.Info("Starting transaction...") } ``` ```go glog.V(2).Infoln("Processed", nItems, "elements") ``` -------------------------------- ### Install the metadata library Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/cloud.google.com/go/compute/metadata/README.md Use this command to install the cloud.google.com/go/compute/metadata package. Run it in your terminal to add the library as a dependency. ```bash go get cloud.google.com/go/compute/metadata ``` -------------------------------- ### Install blackfriday-tool Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/man/vendor/github.com/russross/blackfriday/v2/README.md Downloads and installs the blackfriday-tool command-line tool. This also installs Blackfriday itself. The tool binary is installed in $GOPATH/bin and is statically linked. ```bash go get github.com/russross/blackfriday-tool ``` -------------------------------- ### Run command with pty.Start (Go) Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/creack/pty/README.md Starts a command with a pty, writes input, and copies output to stdout. The example sends lines to grep and terminates with EOT. Note: demonstration only, not for production. ```go package main import ( "io" "os" "os/exec" "github.com/creack/pty" ) func main() { c := exec.Command("grep", "--color=auto", "bar") f, err := pty.Start(c) if err != nil { panic(err) } go func() { f.Write([]byte("foo\n")) f.Write([]byte("bar\n")) f.Write([]byte("baz\n")) f.Write([]byte{4}) // EOT }() io.Copy(os.Stdout, f) } ``` -------------------------------- ### Install and test netlink library Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/vishvananda/netlink/README.md Commands to fetch the library, install testing dependencies, and run the test suite as root. ```shell go get github.com/vishvananda/netlink ``` ```shell go get github.com/vishvananda/netns ``` ```shell sudo -E go test github.com/vishvananda/netlink ``` -------------------------------- ### Basic glog logging examples Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/k8s.io/klog/v2/README.md Basic examples from the glog package documentation showing Info and Fatalf logging calls. ```go glog.Info("Prepare to repel boarders") ``` ```go glog.Fatalf("Initialization failed: %s", err) ``` -------------------------------- ### Install plugin with settable source Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/cluster_volumes.md Installs the plugin and sets the configfile.source option to /srv/my-csi-plugin/config.yaml. ```bash $ docker plugin install my-csi-plugin configfile.source="/srv/my-csi-plugin/config.yaml" ``` -------------------------------- ### Install registry command with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/docker/distribution/BUILDING.md Installs the registry command from the current latest source into the GOPATH. Requires a Go development environment with GOROOT and GOPATH set. ```shell go get github.com/docker/distribution/cmd/registry ``` -------------------------------- ### Verify examples build outside the repository Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.opentelemetry.io/otel/RELEASING.md Run this script after releasing to ensure examples build with the published release. It copies examples to a different directory, removes any `replace` declarations in `go.mod`, and builds them. ```bash ./verify_examples.sh ``` -------------------------------- ### Create and run a task Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/containerd/containerd/README.md Creates a task from a container, gets its PID, starts it, and waits for exit status. ```go // create a new task task, err := redis.NewTask(context, cio.NewCreator(cio.WithStdio)) defer task.Delete(context) // the task is now running and has a pid that can be used to setup networking // or other runtime settings outside of containerd pid := task.Pid() // start the redis-server process inside the container err := task.Start(context) // wait for the task to exit and get the exit status status, err := task.Wait(context) ``` -------------------------------- ### Install yaml package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/gopkg.in/yaml.v2/README.md Install the yaml package using the Go tool. Run this command in your terminal to fetch the package from its import path. ```shell go get gopkg.in/yaml.v2 ``` -------------------------------- ### Start containerd with ocicrypt stream processors Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/containerd/imgcrypt/README.md Start containerd with a configuration file that enables the ocicrypt stream processors. Uses /tmp for directories to avoid interference with a Docker installation. The command starts containerd with the specified config.toml. ```shell # cat config.toml disable_plugins = ["cri"] root = "/tmp/var/lib/containerd" state = "/tmp/run/containerd" [grpc] address = "/tmp/run/containerd/containerd.sock" uid = 0 gid = 0 [stream_processors] [stream_processors."io.containerd.ocicrypt.decoder.v1.tar.gzip"] accepts = ["application/vnd.oci.image.layer.v1.tar+gzip+encrypted"] returns = "application/vnd.oci.image.layer.v1.tar+gzip" path = "/usr/local/bin/ctd-decoder" [stream_processors."io.containerd.ocicrypt.decoder.v1.tar.zstd"] accepts = ["application/vnd.oci.image.layer.v1.tar+zstd+encrypted"] returns = "application/vnd.oci.image.layer.v1.tar+zstd" path = "/usr/local/bin/ctd-decoder" [stream_processors."io.containerd.ocicrypt.decoder.v1.tar"] accepts = ["application/vnd.oci.image.layer.v1.tar+encrypted"] returns = "application/vnd.oci.image.layer.v1.tar" path = "/usr/local/bin/ctd-decoder" # sudo ~/src/github.com/containerd/containerd/bin/containerd -c config.toml ``` -------------------------------- ### Complete mux server example in Go Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/gorilla/mux/README.md A runnable Go program that creates a new mux router, registers a handler for the root path, and starts an HTTP server on port 8000. The handler writes 'Gorilla!\n' to the response. ```go package main import ( "net/http" "log" "github.com/gorilla/mux" ) func YourHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Gorilla!\n")) } func main() { r := mux.NewRouter() // Routes consist of a path and a handler function. r.HandleFunc("/", YourHandler) // Bind to a port and pass our router in log.Fatal(http.ListenAndServe(":8000", r)) } ``` -------------------------------- ### Build runc from source Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/opencontainers/runc/README.md Clones the runc repository and builds it with make, then installs it with sudo make install. ```bash # create a 'github.com/opencontainers' in your GOPATH/src cd github.com/opencontainers git clone https://github.com/opencontainers/runc cd runc make sudo make install ``` -------------------------------- ### Manage container lifecycle with runc create/start/delete Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/opencontainers/runc/README.md Demonstrates the lifecycle operations: create, list, start, list, and delete. Assumes the config.json has been edited with terminal: false and args: ["sleep", "5"] as shown in the previous example. This allows higher level systems to augment container creation logic, e.g., setting up the network stack after create but before start. ```bash # run as root cd /mycontainer runc create mycontainerid # view the container is created and in the "created" state runc list # start the process inside the container runc start mycontainerid # after 5 seconds view that the container has exited and is now in the stopped state runc list # now delete the container runc delete mycontainerid ``` -------------------------------- ### Basic usage example Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/armon/go-metrics/README.md Shows how to profile a method, configure a statsite sink, and emit a key/value pair. ```go func SlowMethod() { // Profiling the runtime of a method defer metrics.MeasureSince([]string{"SlowMethod"}, time.Now()) } // Configure a statsite sink as the global metrics sink sink, _ := metrics.NewStatsiteSink("statsite:8125") metrics.NewGlobal(metrics.DefaultConfig("service-name"), sink) // Emit a Key/Value pair metrics.EmitKey([]string{"questions", "meaning of life"}, 42) ``` -------------------------------- ### Install rdiff utility Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/balena-os/librsync-go/README.md Use the go install command to install the rdiff utility from the librsync-go repository. ```sh go install github.com/balena-os/librsync-go/cmd/rdiff ``` -------------------------------- ### Defining a WebService and Route Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/emicklei/go-restful/v3/README.md Example showing how to initialize a WebService, define paths, and map a route to a handler function. ```go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` -------------------------------- ### Complete merge example with structs Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/dario.cat/mergo/README.md Complete example showing how to merge two structs. The output is {two 2}. ```go package main import ( "fmt" "dario.cat/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } ``` -------------------------------- ### Install flock with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/gofrs/flock/README.md Install the flock package using the go get command. Requires Go 1.7 or later. ```bash go get -u github.com/gofrs/flock ``` -------------------------------- ### Install uuid package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/google/uuid/README.md Install the github.com/google/uuid package using the go get command. This is the standard way to add the package to a Go module. ```sh go get github.com/google/uuid ``` -------------------------------- ### ZFS filesystem, snapshot, and clone example in Go Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/mistifyio/go-zfs/v3/README.md Go example assuming a zpool named 'test'. Creates a filesystem, takes a snapshot, clones it, and destroys all resources. Error handling is omitted. ```go //assuming a zpool named test //error handling omitted f, err := zfs.CreateFilesystem("test/snapshot-test", nil) ok(t, err) s, err := f.Snapshot("test", nil) ok(t, err) // snapshot is named "test/snapshot-test@test" c, err := s.Clone("test/clone-test", nil) err := c.Destroy() err := s.Destroy() err := f.Destroy() ``` -------------------------------- ### Get a package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/cloud.google.com/go/README.md Command to fetch a specific package, e.g., cloud.google.com/go/firestore. ```bash $ go get cloud.google.com/go/firestore # Replace with the package you want to use. ``` -------------------------------- ### Example output from go run main.go Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/dimchansky/utfbom/README.md Output of the example program, showing BOM skipping and encoding detection results for both BOM and non-BOM inputs. ```text $ go run main.go Input: [239 187 191 104 101 108 108 111] ReadAll with BOM skipping [104 101 108 108 111] Detected encoding: UTF8 ReadAll with BOM detection and skipping [104 101 108 108 111] Input: [104 101 108 108 111] ReadAll with BOM skipping [104 101 108 108 111] Detected encoding: Unknown ReadAll with BOM detection and skipping [104 101 108 108 111] ``` -------------------------------- ### Syntax example for creating sets with generic types Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/deckarep/golang-set/v2/README.md Shows how to instantiate sets with different comparable types using the generic NewSet function. The first line is a syntax example that doesn't compile, followed by valid examples for int, string, struct, and any types. ```go // Syntax example, doesn't compile. mySet := mapset.NewSet[T]() // where T is some concrete comparable type. // Therefore this code creates an int set mySet := mapset.NewSet[int]() // Or perhaps you want a string set mySet := mapset.NewSet[string]() type myStruct { name string age uint8 } // Alternatively a set of structs mySet := mapset.NewSet[myStruct]() // Lastly a set that can hold anything using the any or empty interface keyword: interface{}. This is effectively removes type safety. mySet := mapset.NewSet[any]() ``` -------------------------------- ### Start dev container with DOCKER_CLI_PATH Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/contributing/set-up-dev-env.md Command to start the development container with a custom Docker CLI path, followed by the output showing the CLI location and version inside the container. ```none make DOCKER_CLI_PATH=/home/ubuntu/git/docker-ce/components/packaging/static/build/linux/docker/docker BIND_DIR=. shell ... # which docker /usr/local/cli/docker # docker --version Docker version 17.09.0-dev, build ``` -------------------------------- ### Install json-iterator/go Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/json-iterator/go/README.md Command to install the json-iterator/go package using go get. ```bash go get github.com/json-iterator/go ``` -------------------------------- ### Install golint for Makefile Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/docker/distribution/BUILDING.md Installs the golint tool into GOPATH, required for the Makefile to work. ```shell go get github.com/golang/lint/golint ``` -------------------------------- ### Start containerd daemon Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/containerd/containerd/BUILDING.md Starts the containerd daemon with a configuration file. Required before using the ctr test client. ```sh containerd --config config.toml ``` -------------------------------- ### Install and import mergo Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/dario.cat/mergo/README.md Install the mergo package and import it in your Go code. ```bash go get dario.cat/mergo ``` ```go // use in your .go code import ( "dario.cat/mergo" ) ``` -------------------------------- ### Install release tools Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/montanaflynn/stats/README.md Commands to install the tools used for generating markdown files and releasing. Run these before using the make directives. ```bash go install github.com/davecheney/godoc2md@latest go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest brew tap git-chglog/git-chglog brew install gnu-sed hub git-chglog ``` -------------------------------- ### Rebuild and install binary Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/contributing/set-up-dev-env.md Commands to rebuild the binary and install it to /usr/bin inside the development container. ```bash hack/make.sh binary install-binary ``` -------------------------------- ### Install aec with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/morikuni/aec/README.md Installs the aec package using the Go module system. ```bash go get github.com/morikuni/aec ``` -------------------------------- ### Using Avx512Server and Avx512Digest in Go Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/minio/sha256-simd/README.md Go example showing how to create an AVX512 server, instantiate a digest, and hash a file block. Note that for messages under 1 MB, regular SHA256 is recommended due to scheduling overhead. ```go import "github.com/minio/sha256-simd" func main() { server := sha256.NewAvx512Server() h512 := sha256.NewAvx512(server) h512.Write(fileBlock) digest := h512.Sum([]byte{}) } ``` -------------------------------- ### Install libseccomp-golang with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/seccomp/libseccomp-golang/README.md Command to install the libseccomp-golang package using the Go package manager. ```shell % go get github.com/seccomp/libseccomp-golang ``` -------------------------------- ### Sign and Detach Content with pkcs7 Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.mozilla.org/pkcs7/README.md This example demonstrates how to initialize signed data, add a signer, detach the signature, and verify the resulting PKCS#7 message. ```go package main import ( "bytes" "crypto/rsa" "crypto/x509" "encoding/pem" "fmt" "os" "go.mozilla.org/pkcs7" ) func SignAndDetach(content []byte, cert *x509.Certificate, privkey *rsa.PrivateKey) (signed []byte, err error) { toBeSigned, err := NewSignedData(content) if err != nil { err = fmt.Errorf("Cannot initialize signed data: %s", err) return } if err = toBeSigned.AddSigner(cert, privkey, SignerInfoConfig{}); err != nil { err = fmt.Errorf("Cannot add signer: %s", err) return } // Detach signature, omit if you want an embedded signature toBeSigned.Detach() signed, err = toBeSigned.Finish() if err != nil { err = fmt.Errorf("Cannot finish signing data: %s", err) return } // Verify the signature pem.Encode(os.Stdout, &pem.Block{Type: "PKCS7", Bytes: signed}) p7, err := pkcs7.Parse(signed) if err != nil { err = fmt.Errorf("Cannot parse our signed data: %s", err) return } // since the signature was detached, reattach the content here p7.Content = content if bytes.Compare(content, p7.Content) != 0 { err = fmt.Errorf("Our content was not in the parsed data:\n\tExpected: %s\n\tActual: %s", content, p7.Content) return } if err = p7.Verify(); err != nil { err = fmt.Errorf("Cannot verify our signed data: %s", err) return } return signed, nil } ``` -------------------------------- ### Create root logger with logimpl.New Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/go-logr/logr/README.md Shows how to create the root logger early in an application's life, using a chosen implementation (logimpl) that returns a logr.Logger. This is the setup code before passing the logger to other parts of the app. ```go func main() { // ... other setup code ... // Create the "root" logger. We have chosen the "logimpl" implementation, // which takes some initial parameters and returns a logr.Logger. logger := logimpl.New(param1, param2) // ... other setup code ... ``` -------------------------------- ### System Wide Installation of Dockerfile.nanorc Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/contrib/syntax/nano/README.md Commands to install Dockerfile.nanorc system-wide: create the syntax directory, copy the file, and add an include line to /etc/nanorc. ```bash mkdir /usr/local/share/nano ``` ```bash cp Dockerfile.nanorc /usr/local/share/nano/ ``` ```nanorc ## Dockerfile files include "/usr/local/share/nano/Dockerfile.nanorc" ``` -------------------------------- ### Install and run ltag to add license headers Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/containerd/btrfs/v2/README.md Commands to install the ltag tool and apply license headers to Go files. Requires the license templates in ./license-templates. ```console $ go get github.com/kunalkushwaha/ltag $ ltag -t ./license-templates ``` -------------------------------- ### Create a logging.Client Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/cloud.google.com/go/logging/README.md Creates a logging client for a specified project. This is the first step before using any logging functionality. ```go ctx := context.Background() client, err := logging.NewClient(ctx, "my-project") if err != nil { // TODO: Handle error. } ``` -------------------------------- ### Install netns package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/vishvananda/netns/README.md Use this command to fetch the netns package. Requires Go installed. ```shell go get github.com/vishvananda/netns ``` -------------------------------- ### Install jwt-go with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/golang-jwt/jwt/v4/README.md Adds github.com/golang-jwt/jwt/v4 as a dependency in a Go program. Requires Go to be installed first. ```sh go get -u github.com/golang-jwt/jwt/v4 ``` -------------------------------- ### Create memberlist, join cluster, and list members Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/hashicorp/memberlist/README.md Shows basic usage of the memberlist library: create a memberlist with default configuration, join a cluster with at least one known member (here the IP 1.2.3.4), and list cluster members. Delegates handle membership events in the background. ```go /* Create the initial memberlist from a safe configuration. Please reference the godoc for other default config types. http://godoc.org/github.com/hashicorp/memberlist#Config */ list, err := memberlist.Create(memberlist.DefaultLocalConfig()) if err != nil { panic("Failed to create memberlist: " + err.Error()) } // Join an existing cluster by specifying at least one known member. n, err := list.Join([]string{"1.2.3.4"}) if err != nil { panic("Failed to join cluster: " + err.Error()) } // Ask for members of the cluster for _, member := range list.Members() { fmt.Printf("Member: %s %s\n", member.Name, member.Addr) } // Continue doing whatever you need, memberlist will maintain membership // information in the background. Delegates can be used for receiving // events when members join or leave. ``` -------------------------------- ### Install Blackfriday v2 with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/man/vendor/github.com/russross/blackfriday/v2/README.md Installs the Blackfriday v2 package in module mode. This command resolves and adds the package to the current development module, then builds and installs it. ```bash go get github.com/russross/blackfriday/v2 ``` -------------------------------- ### RPC server and client codec setup Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/hashicorp/go-msgpack/codec/README.md Demonstrates how to use the codec with net/rpc for both server and client sides. The server accepts connections and serves with a codec, while the client dials and creates a client codec. ```go //RPC Server go func() { for { conn, err := listener.Accept() rpcCodec := codec.GoRpc.ServerCodec(conn, h) //OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h) rpc.ServeCodec(rpcCodec) } }() //RPC Communication (client side) conn, err = net.Dial("tcp", "localhost:5555") rpcCodec := codec.GoRpc.ClientCodec(conn, h) //OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h) client := rpc.NewClientWithCodec(rpcCodec) ``` -------------------------------- ### Using sha256-simd as a drop-in replacement Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/minio/sha256-simd/README.md Shows how to import and use github.com/minio/sha256-simd. The package automatically selects the fastest method for the architecture on which it is executed. The example creates a new SHA256 hash writer and copies data from a file to it. ```go import "github.com/minio/sha256-simd" func main() { ... shaWriter := sha256.New() io.Copy(shaWriter, file) ... } ``` -------------------------------- ### Installation: go get github.com/mitchellh/mapstructure Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/mitchellh/mapstructure/README.md Installs the mapstructure library using the Go toolchain. Run this in your terminal to fetch the package into your Go module. ```bash $ go get github.com/mitchellh/mapstructure ``` -------------------------------- ### Install pty package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/creack/pty/README.md Install the pty package using the standard Go module command. Run this in your terminal to add the dependency. ```sh go get github.com/creack/pty ``` -------------------------------- ### I/O timeout error from go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/google.golang.org/grpc/README.md Example error output when the golang.org domain is blocked, such as in some countries. The go get command fails with an i/o timeout. ```console $ go get -u google.golang.org/grpc package google.golang.org/grpc: unrecognized import path "google.golang.org/grpc" (https fetch: Get https://google.golang.org/grpc?go-get=1: dial tcp 216.239.37.1:443: i/o timeout) ``` -------------------------------- ### Install oauth2 package with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/golang.org/x/oauth2/README.md Installs the oauth2 package using the Go module tool. Run this command in your terminal to fetch the package and its dependencies. ```shell go get golang.org/x/oauth2 ``` -------------------------------- ### Run tests with make Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.opencensus.io/CONTRIBUTING.md Installs tools on first run, then runs the test suite. ```bash $ make install-tools # Only first time. $ make ``` -------------------------------- ### Create a client with a JSON key file Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/cloud.google.com/go/README.md Creates a storage client using a JSON key file for authorization. ```go client, err := storage.NewClient(ctx, option.WithCredentialsFile("path/to/keyfile.json")) ``` -------------------------------- ### Install hashstructure v2 with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/mitchellh/hashstructure/v2/README.md Install the hashstructure library using the standard Go toolchain. The v2 release is recommended because it fixes significant hash collision issues from v1. ```shell $ go get github.com/mitchellh/hashstructure/v2 ``` -------------------------------- ### Build and run development container Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/contributing/set-up-dev-env.md Build a development environment image and run it in a container. The first build may take 5-15 minutes and returns informational messages. ```none $ make BIND_DIR=. shell ``` -------------------------------- ### Create a Namespace Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/docker/go-metrics/README.md Initializes a new namespace with a namespace name, subsystem name, and constant labels for versioning and tracking. ```go ns := metrics.NewNamespace("engine", "daemon", metrics.Labels{ "version": dockerversion.Version, "commit": dockerversion.GitCommit, }) ``` -------------------------------- ### Install bbolt with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.etcd.io/bbolt/README.md Retrieves the bbolt library and updates go.mod and go.sum files. ```sh $ go get go.etcd.io/bbolt@latest ``` -------------------------------- ### Start a read-only transaction with DB.View() Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.etcd.io/bbolt/README.md Use DB.View() to start a read-only transaction. Inside the closure, you get a consistent view of the database, but no mutating operations are allowed. You can only retrieve buckets, retrieve values, and copy the database. ```go err := db.View(func(tx *bolt.Tx) error { ... return nil }) ``` -------------------------------- ### Run benchmark with 'go test -bi -bench=. -benchmem' Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/hashicorp/go-msgpack/codec/README.md Command to run the benchmark suite with memory profiling. The output shows a sample run on an Intel Core i7-2630QM CPU. ```shell go test -bi -bench=. -benchmem ``` -------------------------------- ### Create PackageURL from parts Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/package-url/packageurl-go/README.md Shows how to construct a PackageURL using NewPackageURL and print it with ToString. ```go package main import ( "fmt" "github.com/package-url/packageurl-go" ) func main() { instance := packageurl.NewPackageURL("test", "ok", "name", "version", nil, "") fmt.Printf("%s", instance.ToString()) } ``` -------------------------------- ### Start daemon in debug mode Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/docs/contributing/set-up-dev-env.md Start the Engine daemon in the background with debug mode. The -D flag enables debug mode and & runs it in the background. You need to press return to get back to the shell prompt. ```none # dockerd -D & ...output snipped... DEBU[0001] Registering POST, /networks/{id:.*}/connect DEBU[0001] Registering POST, /networks/{id:.*}/disconnect DEBU[0001] Registering DELETE, /networks/{id:.*} INFO[0001] API listen on /var/run/docker.sock DEBU[0003] containerd connection state change: READY ``` -------------------------------- ### Create a client with default credentials Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/cloud.google.com/go/README.md Creates a storage client using Application Default Credentials. ```go client, err := storage.NewClient(ctx) ``` -------------------------------- ### reflect2.TypeByName example Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/modern-go/reflect2/README.md Shows how to use reflect2.TypeByName to get a type by name. The type must have been used in the program, otherwise the compiler may eliminate it. ```go // given package is github.com/your/awesome-package type MyStruct struct { // ... } // will return the type reflect2.TypeByName("awesome-package.MyStruct") // however, if the type has not been used // it will be eliminated by compiler, so we can not get it in runtime ``` -------------------------------- ### Example: using netns to create and switch network namespaces Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/vishvananda/netns/README.md Complete Go program demonstrating netns usage. Locks the OS thread, saves the current namespace, creates a new one, lists interfaces, and switches back. Requires root privileges. ```go package main import ( "fmt" "net" "runtime" "github.com/vishvananda/netns" ) func main() { // Lock the OS Thread so we don't accidentally switch namespaces runtime.LockOSThread() defer runtime.UnlockOSThread() // Save the current network namespace origns, _ := netns.Get() defer origns.Close() // Create a new network namespace newns, _ := netns.New() defer newns.Close() // Do something with the network namespace ifaces, _ := net.Interfaces() fmt.Printf("Interfaces: %v\n", ifaces) // Switch back to the original namespace netns.Set(origns) } ``` -------------------------------- ### ZFS setup commands for Ubuntu 14.04 Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/mistifyio/go-zfs/v3/README.md Commands to install ZFS on Ubuntu 14.04 using apt-get and a PPA. Requires root privileges for ZFS operations. ```bash sudo apt-get install python-software-properties sudo apt-add-repository ppa:zfs-native/stable sudo apt-get update sudo apt-get install ubuntu-zfs libzfs-dev ``` -------------------------------- ### Prefix scan with Seek and bytes.HasPrefix in Go Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/go.etcd.io/bbolt/README.md Combines Cursor.Seek() and bytes.HasPrefix() to iterate over keys with a given prefix. The example scans for keys starting with "1234". ```go db.View(func(tx *bolt.Tx) error { // Assume bucket exists and has keys c := tx.Bucket([]byte("MyBucket")).Cursor() prefix := []byte("1234") for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { fmt.Printf("key=%s, value=%s\n", k, v) } return nil }) ``` -------------------------------- ### Install urfave/cli with go get Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/urfave/cli/README.md Command to fetch the urfave/cli package using Go's module system. Requires a working Go environment with version 1.18+. ```bash $ go get github.com/urfave/cli ``` -------------------------------- ### Run make all Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/grpc-ecosystem/go-grpc-middleware/CONTRIBUTING.md Run the `make all` command to vet, format, regenerate documentation, and run all tests before checking in. ```bash make all ``` -------------------------------- ### Using runewidth.StringWidth to get string width Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/mattn/go-runewidth/README.md Shows how to call runewidth.StringWidth with a string containing wide characters. The example asserts that the width of "つのだ☆HIRO" equals 12. ```go runewidth.StringWidth("つのだ☆HIRO") == 12 ``` -------------------------------- ### Import Blackfriday v2 package Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/man/vendor/github.com/russross/blackfriday/v2/README.md Imports the Blackfriday v2 package in a Go source file. After adding this import, running `go get` without parameters achieves the same installation as the explicit command. ```go import "github.com/russross/blackfriday/v2" ``` -------------------------------- ### Run registry binary with version flag Source: https://github.com/balena-os/balena-engine/blob/release/v25.0/vendor/github.com/docker/distribution/BUILDING.md Runs the registry binary with --version to verify installation. The output shows the version string. ```shell $ $GOPATH/bin/registry --version $GOPATH/bin/registry github.com/docker/distribution v2.0.0-alpha.1+unknown ```