misc/genreadme,tempfork/pkgdoc,tsnet: generate README.md files from godoc
Adds a CI check to keep opted-in directories' README.md files in sync
with their package godoc. For now tsnet (and its sub-packages under
tsnet/example) is the only opted-in tree. The list of directories
lives in misc/genreadme/genreadme.go as defaultRoots, so CI and humans
both just run `./tool/go run ./misc/genreadme` with no arguments.
The check piggybacks on the existing go_generate job in test.yml and
fails if any README.md is out of date, pointing the user at the same
command.
Along the way:
- tempfork/pkgdoc now emits Markdown instead of plain text: headings
become level-2 with no {#hdr-...} anchors, and [Symbol] doc links
resolve to pkg.go.dev URLs, including for symbols in the current
package (which the default Printer would otherwise emit as bare
#Name fragments with no backing anchor in a README). Parsing no
longer uses parser.ImportsOnly, so doc.Package knows the package's
symbols and can resolve [Symbol] links at all.
- genreadme also emits a pkg.go.dev Go Reference badge at the top of
a library package's README; suppressed for package main.
- tsnet/tsnet.go's package godoc is expanded in idiomatic godoc
syntax — [Type], [Type.Method], reference-style [link]: URL
definitions — rather than Markdown-flavored [text](url) or
backtick-quoted identifiers, so that both pkg.go.dev and the
generated README.md render cleanly from a single source.
Fixes #19431
Fixes #19483
Fixes #19470
Change-Id: I8ca37e9e7b3bd446b8bfa7a91ac548f142688cb1
Co-authored-by: Brad Fitzpatrick <bradfitz@tailscale.com>
Signed-off-by: Walter Poupore <walterp@tailscale.com>
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
committed by
Brad Fitzpatrick
parent
311dd3839d
commit
a7d8aeb8ae
@@ -787,6 +787,14 @@ jobs:
|
|||||||
echo
|
echo
|
||||||
echo
|
echo
|
||||||
git diff --name-only --exit-code || (echo "The files above need updating. Please run 'go generate'."; exit 1)
|
git diff --name-only --exit-code || (echo "The files above need updating. Please run 'go generate'."; exit 1)
|
||||||
|
- name: check that 'genreadme' is clean
|
||||||
|
working-directory: src
|
||||||
|
run: |
|
||||||
|
./tool/go run ./misc/genreadme
|
||||||
|
git add -N . # ensure untracked files are noticed
|
||||||
|
echo
|
||||||
|
echo
|
||||||
|
git diff --name-only --exit-code || (echo "The files above need updating. Please run './tool/go run ./misc/genreadme'."; exit 1)
|
||||||
|
|
||||||
make_tidy:
|
make_tidy:
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
"io/fs"
|
"io/fs"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -28,6 +29,9 @@ import (
|
|||||||
"tailscale.com/tempfork/pkgdoc"
|
"tailscale.com/tempfork/pkgdoc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// modulePath is the current module's import path, read from go.mod at startup.
|
||||||
|
var modulePath string
|
||||||
|
|
||||||
var skip = map[string]bool{
|
var skip = map[string]bool{
|
||||||
"out": true,
|
"out": true,
|
||||||
}
|
}
|
||||||
@@ -36,15 +40,25 @@ var skip = map[string]bool{
|
|||||||
// Buildkite because a deploy workflow is not set up for them.
|
// Buildkite because a deploy workflow is not set up for them.
|
||||||
var bkSkip = map[string]bool{}
|
var bkSkip = map[string]bool{}
|
||||||
|
|
||||||
|
// defaultRoots are the directory trees walked when genreadme is run with
|
||||||
|
// no arguments. Add a directory here to opt its package (and any
|
||||||
|
// sub-packages) into README.md generation from godoc.
|
||||||
|
var defaultRoots = []string{
|
||||||
|
"tsnet",
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
root := "."
|
modulePath = readModulePath("go.mod")
|
||||||
|
var roots []string
|
||||||
switch flag.NArg() {
|
switch flag.NArg() {
|
||||||
case 0:
|
case 0:
|
||||||
|
roots = defaultRoots
|
||||||
case 1:
|
case 1:
|
||||||
root = flag.Arg(0)
|
root := flag.Arg(0)
|
||||||
root = strings.TrimPrefix(root, "./")
|
root = strings.TrimPrefix(root, "./")
|
||||||
root = strings.TrimSuffix(root, "/")
|
root = strings.TrimSuffix(root, "/")
|
||||||
|
roots = []string{root}
|
||||||
default:
|
default:
|
||||||
log.Fatalf("Usage: genreadme [dir]")
|
log.Fatalf("Usage: genreadme [dir]")
|
||||||
}
|
}
|
||||||
@@ -54,6 +68,7 @@ func main() {
|
|||||||
updateErrs = append(updateErrs, err)
|
updateErrs = append(updateErrs, err)
|
||||||
}).Limit(runtime.NumCPU() * 2) // usually I/O bound
|
}).Limit(runtime.NumCPU() * 2) // usually I/O bound
|
||||||
|
|
||||||
|
for _, root := range roots {
|
||||||
g.Go(func() error {
|
g.Go(func() error {
|
||||||
return fs.WalkDir(os.DirFS("."), root, func(path string, d fs.DirEntry, err error) error {
|
return fs.WalkDir(os.DirFS("."), root, func(path string, d fs.DirEntry, err error) error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -75,6 +90,7 @@ func main() {
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
}
|
||||||
g.Wait()
|
g.Wait()
|
||||||
if err := errors.Join(updateErrs...); err != nil {
|
if err := errors.Join(updateErrs...); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
@@ -126,7 +142,7 @@ func getNewContent(dir string) (newContent []byte, err error) {
|
|||||||
quickTest func(dir string, dents []fs.DirEntry) bool
|
quickTest func(dir string, dents []fs.DirEntry) bool
|
||||||
generate func(dir string) ([]byte, error)
|
generate func(dir string) ([]byte, error)
|
||||||
}{
|
}{
|
||||||
{"go", hasPkgMainGoFiles, genGoDoc},
|
{"go", hasGoFiles, genGoDoc},
|
||||||
}
|
}
|
||||||
for _, gen := range generators {
|
for _, gen := range generators {
|
||||||
if !gen.quickTest(dir, dents) {
|
if !gen.quickTest(dir, dents) {
|
||||||
@@ -147,7 +163,11 @@ func genGoDoc(dir string) ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to get absolute path for %q: %w", dir, err)
|
return nil, fmt.Errorf("failed to get absolute path for %q: %w", dir, err)
|
||||||
}
|
}
|
||||||
godoc, err := pkgdoc.PackageDoc(abs)
|
var importPath string
|
||||||
|
if modulePath != "" {
|
||||||
|
importPath = path.Join(modulePath, filepath.ToSlash(dir))
|
||||||
|
}
|
||||||
|
godoc, err := pkgdoc.PackageDoc(abs, importPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to get package doc for %q: %w", dir, err)
|
return nil, fmt.Errorf("failed to get package doc for %q: %w", dir, err)
|
||||||
}
|
}
|
||||||
@@ -155,13 +175,22 @@ func genGoDoc(dir string) ([]byte, error) {
|
|||||||
// No godoc; skipping.
|
// No godoc; skipping.
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
if bytes.HasPrefix(godoc, []byte("package ")) {
|
isLibrary := bytes.HasPrefix(godoc, []byte("package "))
|
||||||
// Not a package main; skipping.
|
if isLibrary {
|
||||||
|
// Strip the "package X // import Y\n\n" clause emitted for library packages.
|
||||||
|
if i := bytes.Index(godoc, []byte("\n\n")); i != -1 {
|
||||||
|
godoc = godoc[i+2:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(bytes.TrimSpace(godoc)) == 0 {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
io.WriteString(&buf, genHeader)
|
io.WriteString(&buf, genHeader)
|
||||||
fmt.Fprintf(&buf, "\n# %s\n\n", filepath.Base(dir))
|
fmt.Fprintf(&buf, "\n# %s\n\n", filepath.Base(dir))
|
||||||
|
if isLibrary && importPath != "" {
|
||||||
|
fmt.Fprintf(&buf, "[](https://pkg.go.dev/%s)\n\n", importPath, importPath)
|
||||||
|
}
|
||||||
buf.Write(godoc)
|
buf.Write(godoc)
|
||||||
|
|
||||||
if !bytes.Contains(godoc, []byte("## Deploying")) {
|
if !bytes.Contains(godoc, []byte("## Deploying")) {
|
||||||
@@ -184,6 +213,21 @@ const genHeader = "<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT.
|
|||||||
|
|
||||||
func isGenerated(b []byte) bool { return bytes.HasPrefix(b, []byte(genHeader)) }
|
func isGenerated(b []byte) bool { return bytes.HasPrefix(b, []byte(genHeader)) }
|
||||||
|
|
||||||
|
// readModulePath returns the module path declared in the given go.mod file,
|
||||||
|
// or "" if it can't be read or parsed.
|
||||||
|
func readModulePath(file string) string {
|
||||||
|
b, err := os.ReadFile(file)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
for line := range strings.Lines(string(b)) {
|
||||||
|
if rest, ok := strings.CutPrefix(strings.TrimSpace(line), "module "); ok {
|
||||||
|
return strings.Trim(strings.TrimSpace(rest), `"`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
func hasBuildkite(dir string) bool {
|
func hasBuildkite(dir string) bool {
|
||||||
if bkSkip[dir] {
|
if bkSkip[dir] {
|
||||||
return false
|
return false
|
||||||
@@ -192,7 +236,7 @@ func hasBuildkite(dir string) bool {
|
|||||||
return flyErr != nil
|
return flyErr != nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func hasPkgMainGoFiles(dir string, dents []fs.DirEntry) bool {
|
func hasGoFiles(dir string, dents []fs.DirEntry) bool {
|
||||||
var fset *token.FileSet
|
var fset *token.FileSet
|
||||||
|
|
||||||
for _, de := range dents {
|
for _, de := range dents {
|
||||||
@@ -217,7 +261,7 @@ func hasPkgMainGoFiles(dir string, dents []fs.DirEntry) bool {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
return pkgFile.Name.Name == "main"
|
return pkgFile.Name.Name != ""
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"go/ast"
|
"go/ast"
|
||||||
"go/build"
|
"go/build"
|
||||||
"go/doc"
|
"go/doc"
|
||||||
|
"go/doc/comment"
|
||||||
"go/parser"
|
"go/parser"
|
||||||
"go/token"
|
"go/token"
|
||||||
"io"
|
"io"
|
||||||
@@ -46,6 +47,31 @@ func (pkg *Package) ToText(w io.Writer, text, prefix, codePrefix string) {
|
|||||||
w.Write(pr.Text(d))
|
w.Write(pr.Text(d))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ToMarkdown parses the godoc comment text and writes a Markdown rendering to w
|
||||||
|
// suitable for a repository README.md: top-level sections become ## headings
|
||||||
|
// without per-heading anchor IDs, and [Symbol] doc links resolve to pkg.go.dev,
|
||||||
|
// including for symbols in the current package (which the default printer would
|
||||||
|
// otherwise emit as bare #Name fragments with no backing anchor).
|
||||||
|
func (pkg *Package) ToMarkdown(w io.Writer, text string) {
|
||||||
|
d := pkg.doc.Parser().Parse(text)
|
||||||
|
pr := pkg.doc.Printer()
|
||||||
|
pr.HeadingLevel = 2
|
||||||
|
pr.HeadingID = func(*comment.Heading) string { return "" }
|
||||||
|
pr.DocLinkBaseURL = "https://pkg.go.dev"
|
||||||
|
pr.DocLinkURL = func(link *comment.DocLink) string {
|
||||||
|
importPath := link.ImportPath
|
||||||
|
if importPath == "" {
|
||||||
|
importPath = pkg.doc.ImportPath
|
||||||
|
}
|
||||||
|
name := link.Name
|
||||||
|
if link.Recv != "" {
|
||||||
|
name = link.Recv + "." + name
|
||||||
|
}
|
||||||
|
return "https://pkg.go.dev/" + importPath + "#" + name
|
||||||
|
}
|
||||||
|
w.Write(pr.Markdown(d))
|
||||||
|
}
|
||||||
|
|
||||||
// pkgBuffer is a wrapper for bytes.Buffer that prints a package clause the
|
// pkgBuffer is a wrapper for bytes.Buffer that prints a package clause the
|
||||||
// first time Write is called.
|
// first time Write is called.
|
||||||
type pkgBuffer struct {
|
type pkgBuffer struct {
|
||||||
@@ -85,7 +111,10 @@ func parsePackage(writer io.Writer, pkg *build.Package, userPath string) *Packag
|
|||||||
return slices.Contains(pkg.GoFiles, info.Name()) || slices.Contains(pkg.CgoFiles, info.Name())
|
return slices.Contains(pkg.GoFiles, info.Name()) || slices.Contains(pkg.CgoFiles, info.Name())
|
||||||
}
|
}
|
||||||
fset := token.NewFileSet()
|
fset := token.NewFileSet()
|
||||||
pkgs, err := parser.ParseDir(fset, pkg.Dir, include, parser.ParseComments|parser.ImportsOnly)
|
// Parse declarations (not just imports) so that doc.Package knows the
|
||||||
|
// package's symbols; the Markdown printer needs this to resolve
|
||||||
|
// [Symbol] doc links in package comments.
|
||||||
|
pkgs, err := parser.ParseDir(fset, pkg.Dir, include, parser.ParseComments)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -144,10 +173,10 @@ func (pkg *Package) newlines(n int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// packageDoc prints the docs for the package.
|
// packageDoc prints the docs for the package as Markdown.
|
||||||
func (pkg *Package) packageDoc() {
|
func (pkg *Package) packageDoc() {
|
||||||
pkg.Printf("") // Trigger the package clause; we know the package exists.
|
pkg.Printf("") // Trigger the package clause; we know the package exists.
|
||||||
pkg.ToText(&pkg.buf, pkg.doc.Doc, "", indent)
|
pkg.ToMarkdown(&pkg.buf, pkg.doc.Doc)
|
||||||
pkg.newlines(1)
|
pkg.newlines(1)
|
||||||
|
|
||||||
pkg.bugs()
|
pkg.bugs()
|
||||||
@@ -175,8 +204,12 @@ func (pkg *Package) bugs() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// PackageDoc generates documentation for a package in the given directory.
|
// PackageDoc generates Markdown documentation for the package in the given
|
||||||
func PackageDoc(dir string) ([]byte, error) {
|
// directory. importPath is the full Go import path of that package (e.g.
|
||||||
|
// "tailscale.com/tsnet"); it's used to render [Symbol] doc links to the
|
||||||
|
// right pkg.go.dev URL. If importPath is empty, build.ImportDir's guess
|
||||||
|
// is used (typically "." for module-based repos).
|
||||||
|
func PackageDoc(dir, importPath string) ([]byte, error) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
var writer io.Writer = &buf
|
var writer io.Writer = &buf
|
||||||
|
|
||||||
@@ -188,6 +221,9 @@ func PackageDoc(dir string) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if importPath != "" {
|
||||||
|
buildPackage.ImportPath = importPath
|
||||||
|
}
|
||||||
userPath := dir
|
userPath := dir
|
||||||
|
|
||||||
pkg := parsePackage(writer, buildPackage, userPath)
|
pkg := parsePackage(writer, buildPackage, userPath)
|
||||||
|
|||||||
+100
@@ -0,0 +1,100 @@
|
|||||||
|
<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT. (or remove this line) -->
|
||||||
|
|
||||||
|
# tsnet
|
||||||
|
|
||||||
|
[](https://pkg.go.dev/tailscale.com/tsnet)
|
||||||
|
|
||||||
|
Package tsnet embeds a Tailscale node directly into a Go program, allowing it to join a tailnet and accept or dial connections without running a separate tailscaled daemon or requiring any system-level configuration.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Normally, Tailscale runs as a background system service (tailscaled) that manages a virtual network interface for the whole machine. tsnet takes a different approach: it runs a fully self-contained Tailscale node inside your process using a userspace TCP/IP stack (gVisor). This means:
|
||||||
|
|
||||||
|
- No root privileges required.
|
||||||
|
- No system daemons to install or manage.
|
||||||
|
- Multiple independent Tailscale nodes can run within a single binary.
|
||||||
|
- The node's [Tailscale identity](https://tailscale.com/docs/concepts/tailscale-identity) and state are stored in a directory you control.
|
||||||
|
|
||||||
|
The core type is [Server](https://pkg.go.dev/tailscale.com/tsnet#Server), which represents one embedded Tailscale node. Calling [Server.Listen](https://pkg.go.dev/tailscale.com/tsnet#Server.Listen) or [Server.Dial](https://pkg.go.dev/tailscale.com/tsnet#Server.Dial) routes traffic exclusively over the tailnet. The standard library's [net.Listener](https://pkg.go.dev/net#Listener) and [net.Conn](https://pkg.go.dev/net#Conn) interfaces are returned, so any existing Go HTTP server, gRPC server, or other net-based code works without modification.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
import "tailscale.com/tsnet"
|
||||||
|
|
||||||
|
s := &tsnet.Server{
|
||||||
|
Hostname: "my-service",
|
||||||
|
AuthKey: os.Getenv("TS_AUTHKEY"),
|
||||||
|
}
|
||||||
|
defer s.Close()
|
||||||
|
|
||||||
|
ln, err := s.Listen("tcp", ":80")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
log.Fatal(http.Serve(ln, myHandler))
|
||||||
|
|
||||||
|
On first run, if no [Server.AuthKey](https://pkg.go.dev/tailscale.com/tsnet#Server.AuthKey) is provided and the node is not already enrolled, the server logs an authentication URL. Open it in a browser to add the node to your tailnet.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
A [Server](https://pkg.go.dev/tailscale.com/tsnet#Server) authenticates using, in order of precedence:
|
||||||
|
|
||||||
|
1. [Server.AuthKey](https://pkg.go.dev/tailscale.com/tsnet#Server.AuthKey).
|
||||||
|
2. The TS\_AUTHKEY environment variable.
|
||||||
|
3. The TS\_AUTH\_KEY environment variable.
|
||||||
|
4. An OAuth client secret ([Server.ClientSecret](https://pkg.go.dev/tailscale.com/tsnet#Server.ClientSecret) or TS\_CLIENT\_SECRET), used to mint an auth key.
|
||||||
|
5. Workload identity federation ([Server.ClientID](https://pkg.go.dev/tailscale.com/tsnet#Server.ClientID) plus [Server.IDToken](https://pkg.go.dev/tailscale.com/tsnet#Server.IDToken) or [Server.Audience](https://pkg.go.dev/tailscale.com/tsnet#Server.Audience)).
|
||||||
|
6. An interactive login URL printed to [Server.UserLogf](https://pkg.go.dev/tailscale.com/tsnet#Server.UserLogf).
|
||||||
|
|
||||||
|
If the node is already enrolled (state found in [Server.Store](https://pkg.go.dev/tailscale.com/tsnet#Server.Store)), the auth key is ignored unless TSNET\_FORCE\_LOGIN=1 is set.
|
||||||
|
|
||||||
|
## Identifying callers
|
||||||
|
|
||||||
|
Use the WhoIs method on the client returned by [Server.LocalClient](https://pkg.go.dev/tailscale.com/tsnet#Server.LocalClient) to identify who is making a request:
|
||||||
|
|
||||||
|
lc, _ := srv.LocalClient()
|
||||||
|
http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), 500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, "Hello, %s!", who.UserProfile.LoginName)
|
||||||
|
}))
|
||||||
|
|
||||||
|
## Tailscale Funnel
|
||||||
|
|
||||||
|
[Server.ListenFunnel](https://pkg.go.dev/tailscale.com/tsnet#Server.ListenFunnel) exposes your service on the public internet. [Tailscale Funnel](https://tailscale.com/docs/features/tailscale-funnel) currently supports TCP on ports 443, 8443, and 10000. HTTPS must be enabled in the Tailscale admin console.
|
||||||
|
|
||||||
|
ln, err := srv.ListenFunnel("tcp", ":443")
|
||||||
|
// ln is a TLS listener; connections can come from anywhere on the
|
||||||
|
// internet as well as from your tailnet.
|
||||||
|
|
||||||
|
// To restrict to public traffic only:
|
||||||
|
ln, err = srv.ListenFunnel("tcp", ":443", tsnet.FunnelOnly())
|
||||||
|
|
||||||
|
## Tailscale Services
|
||||||
|
|
||||||
|
[Server.ListenService](https://pkg.go.dev/tailscale.com/tsnet#Server.ListenService) advertises the node as a host for a named [Tailscale Service](https://tailscale.com/docs/features/tailscale-services). The node must use a tag-based identity. To advertise multiple ports, call ListenService once per port.
|
||||||
|
|
||||||
|
srv.AdvertiseTags = []string{"tag:myservice"}
|
||||||
|
|
||||||
|
ln, err := srv.ListenService("svc:my-service", tsnet.ServiceModeHTTP{
|
||||||
|
HTTPS: true,
|
||||||
|
Port: 443,
|
||||||
|
})
|
||||||
|
log.Printf("Listening on https://%s", ln.FQDN)
|
||||||
|
|
||||||
|
## Running multiple nodes in one process
|
||||||
|
|
||||||
|
Each [Server](https://pkg.go.dev/tailscale.com/tsnet#Server) instance is an independent node. Give each a unique [Server.Dir](https://pkg.go.dev/tailscale.com/tsnet#Server.Dir) and [Server.Hostname](https://pkg.go.dev/tailscale.com/tsnet#Server.Hostname):
|
||||||
|
|
||||||
|
for _, name := range []string{"frontend", "backend"} {
|
||||||
|
srv := &tsnet.Server{
|
||||||
|
Hostname: name,
|
||||||
|
Dir: filepath.Join(baseDir, name),
|
||||||
|
AuthKey: os.Getenv("TS_AUTHKEY"),
|
||||||
|
Ephemeral: true,
|
||||||
|
}
|
||||||
|
srv.Start()
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT. (or remove this line) -->
|
||||||
|
|
||||||
|
# tshello
|
||||||
|
|
||||||
|
The tshello server demonstrates how to use Tailscale as a library.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT. (or remove this line) -->
|
||||||
|
|
||||||
|
# tsnet-funnel
|
||||||
|
|
||||||
|
The tsnet-funnel server demonstrates how to use tsnet with Funnel.
|
||||||
|
|
||||||
|
To use it, generate an auth key from the Tailscale admin panel and run the demo with the key:
|
||||||
|
|
||||||
|
TS_AUTHKEY=<yourkey> go run tsnet-funnel.go
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT. (or remove this line) -->
|
||||||
|
|
||||||
|
# tsnet-http-client
|
||||||
|
|
||||||
|
The tshello server demonstrates how to use Tailscale as a library.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT. (or remove this line) -->
|
||||||
|
|
||||||
|
# tsnet-services
|
||||||
|
|
||||||
|
The tsnet-services example demonstrates how to use tsnet with Services.
|
||||||
|
|
||||||
|
To run this example yourself:
|
||||||
|
|
||||||
|
1. Add access controls which (i) define a new ACL tag, (ii) allow the demo node to host the Service, and (iii) allow peers on the tailnet to reach the Service. A sample ACL policy is provided below.
|
||||||
|
2. [Generate an auth key](https://tailscale.com/kb/1085/auth-keys#generate-an-auth-key) using the Tailscale admin panel. When doing so, add your new tag to your key (Service hosts must be tagged nodes).
|
||||||
|
3. [Define a Service](https://tailscale.com/kb/1552/tailscale-services#step-1-define-a-tailscale-service). For the purposes of this demo, it must be defined to listen on TCP port 443. Note that you only need to follow Step 1 in the linked document.
|
||||||
|
4. Run the demo on the command line (step 4 command shown below).
|
||||||
|
|
||||||
|
Command for step 4:
|
||||||
|
|
||||||
|
TS_AUTHKEY=<yourkey> go run tsnet-services.go -service <service-name>
|
||||||
|
|
||||||
|
The following is a sample ACL policy for step 1:
|
||||||
|
|
||||||
|
"tagOwners": {
|
||||||
|
"tag:tsnet-demo-host": ["autogroup:member"],
|
||||||
|
},
|
||||||
|
"autoApprovers": {
|
||||||
|
"services": {
|
||||||
|
"svc:tsnet-demo": ["tag:tsnet-demo-host"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"grants": [
|
||||||
|
"src": ["*"],
|
||||||
|
"dst": ["svc:tsnet-demo"],
|
||||||
|
"ip": ["*"],
|
||||||
|
],
|
||||||
@@ -8,15 +8,14 @@
|
|||||||
// 1. Add access controls which (i) define a new ACL tag, (ii) allow the demo
|
// 1. Add access controls which (i) define a new ACL tag, (ii) allow the demo
|
||||||
// node to host the Service, and (iii) allow peers on the tailnet to reach
|
// node to host the Service, and (iii) allow peers on the tailnet to reach
|
||||||
// the Service. A sample ACL policy is provided below.
|
// the Service. A sample ACL policy is provided below.
|
||||||
//
|
|
||||||
// 2. [Generate an auth key] using the Tailscale admin panel. When doing so, add
|
// 2. [Generate an auth key] using the Tailscale admin panel. When doing so, add
|
||||||
// your new tag to your key (Service hosts must be tagged nodes).
|
// your new tag to your key (Service hosts must be tagged nodes).
|
||||||
//
|
|
||||||
// 3. [Define a Service]. For the purposes of this demo, it must be defined to
|
// 3. [Define a Service]. For the purposes of this demo, it must be defined to
|
||||||
// listen on TCP port 443. Note that you only need to follow Step 1 in the
|
// listen on TCP port 443. Note that you only need to follow Step 1 in the
|
||||||
// linked document.
|
// linked document.
|
||||||
|
// 4. Run the demo on the command line (step 4 command shown below).
|
||||||
//
|
//
|
||||||
// 4. Run the demo on the command line:
|
// Command for step 4:
|
||||||
//
|
//
|
||||||
// TS_AUTHKEY=<yourkey> go run tsnet-services.go -service <service-name>
|
// TS_AUTHKEY=<yourkey> go run tsnet-services.go -service <service-name>
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<!-- README.md auto-generated by misc/genreadme; DO NOT EDIT. (or remove this line) -->
|
||||||
|
|
||||||
|
# web-client
|
||||||
|
|
||||||
|
The web-client command demonstrates serving the Tailscale web client over tsnet.
|
||||||
+121
-1
@@ -1,7 +1,127 @@
|
|||||||
// Copyright (c) Tailscale Inc & contributors
|
// Copyright (c) Tailscale Inc & contributors
|
||||||
// SPDX-License-Identifier: BSD-3-Clause
|
// SPDX-License-Identifier: BSD-3-Clause
|
||||||
|
|
||||||
// Package tsnet provides Tailscale as a library.
|
// Package tsnet embeds a Tailscale node directly into a Go program,
|
||||||
|
// allowing it to join a tailnet and accept or dial connections without
|
||||||
|
// running a separate tailscaled daemon or requiring any system-level
|
||||||
|
// configuration.
|
||||||
|
//
|
||||||
|
// # Overview
|
||||||
|
//
|
||||||
|
// Normally, Tailscale runs as a background system service (tailscaled)
|
||||||
|
// that manages a virtual network interface for the whole machine. tsnet
|
||||||
|
// takes a different approach: it runs a fully self-contained Tailscale
|
||||||
|
// node inside your process using a userspace TCP/IP stack (gVisor).
|
||||||
|
// This means:
|
||||||
|
//
|
||||||
|
// - No root privileges required.
|
||||||
|
// - No system daemons to install or manage.
|
||||||
|
// - Multiple independent Tailscale nodes can run within a single binary.
|
||||||
|
// - The node's [Tailscale identity] and state are stored in a directory you control.
|
||||||
|
//
|
||||||
|
// The core type is [Server], which represents one embedded Tailscale
|
||||||
|
// node. Calling [Server.Listen] or [Server.Dial] routes traffic
|
||||||
|
// exclusively over the tailnet. The standard library's [net.Listener]
|
||||||
|
// and [net.Conn] interfaces are returned, so any existing Go HTTP
|
||||||
|
// server, gRPC server, or other net-based code works without
|
||||||
|
// modification.
|
||||||
|
//
|
||||||
|
// # Usage
|
||||||
|
//
|
||||||
|
// import "tailscale.com/tsnet"
|
||||||
|
//
|
||||||
|
// s := &tsnet.Server{
|
||||||
|
// Hostname: "my-service",
|
||||||
|
// AuthKey: os.Getenv("TS_AUTHKEY"),
|
||||||
|
// }
|
||||||
|
// defer s.Close()
|
||||||
|
//
|
||||||
|
// ln, err := s.Listen("tcp", ":80")
|
||||||
|
// if err != nil {
|
||||||
|
// log.Fatal(err)
|
||||||
|
// }
|
||||||
|
// log.Fatal(http.Serve(ln, myHandler))
|
||||||
|
//
|
||||||
|
// On first run, if no [Server.AuthKey] is provided and the node is not
|
||||||
|
// already enrolled, the server logs an authentication URL. Open it in a
|
||||||
|
// browser to add the node to your tailnet.
|
||||||
|
//
|
||||||
|
// # Authentication
|
||||||
|
//
|
||||||
|
// A [Server] authenticates using, in order of precedence:
|
||||||
|
//
|
||||||
|
// 1. [Server.AuthKey].
|
||||||
|
// 2. The TS_AUTHKEY environment variable.
|
||||||
|
// 3. The TS_AUTH_KEY environment variable.
|
||||||
|
// 4. An OAuth client secret ([Server.ClientSecret] or TS_CLIENT_SECRET),
|
||||||
|
// used to mint an auth key.
|
||||||
|
// 5. Workload identity federation ([Server.ClientID] plus
|
||||||
|
// [Server.IDToken] or [Server.Audience]).
|
||||||
|
// 6. An interactive login URL printed to [Server.UserLogf].
|
||||||
|
//
|
||||||
|
// If the node is already enrolled (state found in [Server.Store]), the
|
||||||
|
// auth key is ignored unless TSNET_FORCE_LOGIN=1 is set.
|
||||||
|
//
|
||||||
|
// # Identifying callers
|
||||||
|
//
|
||||||
|
// Use the WhoIs method on the client returned by [Server.LocalClient]
|
||||||
|
// to identify who is making a request:
|
||||||
|
//
|
||||||
|
// lc, _ := srv.LocalClient()
|
||||||
|
// http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// who, err := lc.WhoIs(r.Context(), r.RemoteAddr)
|
||||||
|
// if err != nil {
|
||||||
|
// http.Error(w, err.Error(), 500)
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
// fmt.Fprintf(w, "Hello, %s!", who.UserProfile.LoginName)
|
||||||
|
// }))
|
||||||
|
//
|
||||||
|
// # Tailscale Funnel
|
||||||
|
//
|
||||||
|
// [Server.ListenFunnel] exposes your service on the public internet.
|
||||||
|
// [Tailscale Funnel] currently supports TCP on ports 443, 8443, and
|
||||||
|
// 10000. HTTPS must be enabled in the Tailscale admin console.
|
||||||
|
//
|
||||||
|
// ln, err := srv.ListenFunnel("tcp", ":443")
|
||||||
|
// // ln is a TLS listener; connections can come from anywhere on the
|
||||||
|
// // internet as well as from your tailnet.
|
||||||
|
//
|
||||||
|
// // To restrict to public traffic only:
|
||||||
|
// ln, err = srv.ListenFunnel("tcp", ":443", tsnet.FunnelOnly())
|
||||||
|
//
|
||||||
|
// # Tailscale Services
|
||||||
|
//
|
||||||
|
// [Server.ListenService] advertises the node as a host for a named
|
||||||
|
// [Tailscale Service]. The node must use a tag-based identity. To
|
||||||
|
// advertise multiple ports, call ListenService once per port.
|
||||||
|
//
|
||||||
|
// srv.AdvertiseTags = []string{"tag:myservice"}
|
||||||
|
//
|
||||||
|
// ln, err := srv.ListenService("svc:my-service", tsnet.ServiceModeHTTP{
|
||||||
|
// HTTPS: true,
|
||||||
|
// Port: 443,
|
||||||
|
// })
|
||||||
|
// log.Printf("Listening on https://%s", ln.FQDN)
|
||||||
|
//
|
||||||
|
// # Running multiple nodes in one process
|
||||||
|
//
|
||||||
|
// Each [Server] instance is an independent node. Give each a unique
|
||||||
|
// [Server.Dir] and [Server.Hostname]:
|
||||||
|
//
|
||||||
|
// for _, name := range []string{"frontend", "backend"} {
|
||||||
|
// srv := &tsnet.Server{
|
||||||
|
// Hostname: name,
|
||||||
|
// Dir: filepath.Join(baseDir, name),
|
||||||
|
// AuthKey: os.Getenv("TS_AUTHKEY"),
|
||||||
|
// Ephemeral: true,
|
||||||
|
// }
|
||||||
|
// srv.Start()
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// [Tailscale identity]: https://tailscale.com/docs/concepts/tailscale-identity
|
||||||
|
// [Tailscale Funnel]: https://tailscale.com/docs/features/tailscale-funnel
|
||||||
|
// [Tailscale Service]: https://tailscale.com/docs/features/tailscale-services
|
||||||
package tsnet
|
package tsnet
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
Reference in New Issue
Block a user