Files
tailscale/tstest/tailmac/Swift/TailMac/TailMac.swift
T
Will Norris 3ec5be3f51 all: remove AUTHORS file and references to it
This file was never truly necessary and has never actually been used in
the history of Tailscale's open source releases.

A Brief History of AUTHORS files
---

The AUTHORS file was a pattern developed at Google, originally for
Chromium, then adopted by Go and a bunch of other projects. The problem
was that Chromium originally had a copyright line only recognizing
Google as the copyright holder. Because Google (and most open source
projects) do not require copyright assignemnt for contributions, each
contributor maintains their copyright. Some large corporate contributors
then tried to add their own name to the copyright line in the LICENSE
file or in file headers. This quickly becomes unwieldy, and puts a
tremendous burden on anyone building on top of Chromium, since the
license requires that they keep all copyright lines intact.

The compromise was to create an AUTHORS file that would list all of the
copyright holders. The LICENSE file and source file headers would then
include that list by reference, listing the copyright holder as "The
Chromium Authors".

This also become cumbersome to simply keep the file up to date with a
high rate of new contributors. Plus it's not always obvious who the
copyright holder is. Sometimes it is the individual making the
contribution, but many times it may be their employer. There is no way
for the proejct maintainer to know.

Eventually, Google changed their policy to no longer recommend trying to
keep the AUTHORS file up to date proactively, and instead to only add to
it when requested: https://opensource.google/docs/releasing/authors.
They are also clear that:

> Adding contributors to the AUTHORS file is entirely within the
> project's discretion and has no implications for copyright ownership.

It was primarily added to appease a small number of large contributors
that insisted that they be recognized as copyright holders (which was
entirely their right to do). But it's not truly necessary, and not even
the most accurate way of identifying contributors and/or copyright
holders.

In practice, we've never added anyone to our AUTHORS file. It only lists
Tailscale, so it's not really serving any purpose. It also causes
confusion because Tailscalars put the "Tailscale Inc & AUTHORS" header
in other open source repos which don't actually have an AUTHORS file, so
it's ambiguous what that means.

Instead, we just acknowledge that the contributors to Tailscale (whoever
they are) are copyright holders for their individual contributions. We
also have the benefit of using the DCO (developercertificate.org) which
provides some additional certification of their right to make the
contribution.

The source file changes were purely mechanical with:

    git ls-files | xargs sed -i -e 's/\(Tailscale Inc &\) AUTHORS/\1 contributors/g'

Updates #cleanup

Change-Id: Ia101a4a3005adb9118051b3416f5a64a4a45987d
Signed-off-by: Will Norris <will@tailscale.com>
2026-01-23 15:49:45 -08:00

336 lines
11 KiB
Swift

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
import Foundation
import Virtualization
import ArgumentParser
var usage =
"""
Installs and configures VMs suitable for use with natlab
To create a new VM (this will grab a restore image if needed)
tailmac create --id <vm_id>
To refresh an existing restore image:
tailmac refresh
To clone a vm (this will clone the mac and port as well)
tailmac clone --identfier <old_vm_id> --target-id <new_vm_id>
To reconfigure a vm:
tailmac configure --id <vm_id> --mac 11:22:33:44:55:66 --port 12345 --mem 8000000000000 -sock "/tmp/mySock.sock"
To run a vm:
tailmac run --id <vm_id>
To stop a vm: (this may take a minute - the vm needs to persist it's state)
tailmac stop --id <vm_id>
To halt a vm without persisting its state
tailmac halt --id <vm_id>
To delete a vm:
tailmac delete --id <vm_id>
To list the available VM images:
tailmac ls
"""
@main
struct Tailmac: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "A utility for setting up VM images",
usage: usage,
subcommands: [Create.self, Clone.self, Delete.self, Configure.self, Stop.self, Run.self, Ls.self, Halt.self],
defaultSubcommand: Ls.self)
}
extension Tailmac {
struct Ls: ParsableCommand {
mutating func run() {
do {
let dirs = try FileManager.default.contentsOfDirectory(atPath: vmBundleURL.path())
var images = [String]()
// This assumes we don't put anything else interesting in our VM.bundle dir
// You may need to add some other exclusions or checks here if that's the case.
for dir in dirs {
if !dir.contains("ipsw") {
images.append(URL(fileURLWithPath: dir).lastPathComponent)
}
}
print("Available images:\n\(images)")
} catch {
fatalError("Failed to query available images \(error)")
}
}
}
}
extension Tailmac {
struct Stop: ParsableCommand {
@Option(help: "The vm identifier") var id: String
mutating func run() {
print("Stopping vm with id \(id). This may take some time!")
let nc = DistributedNotificationCenter()
nc.post(name: Notifications.stop, object: nil, userInfo: ["id": id])
}
}
}
extension Tailmac {
struct Halt: ParsableCommand {
@Option(help: "The vm identifier") var id: String
mutating func run() {
print("Halting vm with id \(id)")
let nc = DistributedNotificationCenter()
nc.post(name: Notifications.halt, object: nil, userInfo: ["id": id])
}
}
}
extension Tailmac {
struct Run: ParsableCommand {
@Option(help: "The vm identifier") var id: String
@Option(help: "Optional share directory") var share: String?
@Flag(help: "Tail the TailMac log output instead of returning immediatly") var tail
mutating func run() {
let process = Process()
let stdOutPipe = Pipe()
let executablePath = CommandLine.arguments[0]
let executableDirectory = (executablePath as NSString).deletingLastPathComponent
let appPath = executableDirectory + "/Host.app/Contents/MacOS/Host"
process.executableURL = URL(
fileURLWithPath: appPath,
isDirectory: false,
relativeTo: NSRunningApplication.current.bundleURL
)
if !FileManager.default.fileExists(atPath: appPath) {
fatalError("Could not find Host.app at \(appPath). This must be co-located with the tailmac utility")
}
var args = ["run", "--id", id]
if let share {
args.append("--share")
args.append(share)
}
process.arguments = args
do {
process.standardOutput = stdOutPipe
try process.run()
} catch {
fatalError("Unable to launch the vm process")
}
if tail != 0 {
// (jonathan)TODO: How do we get the process output in real time?
// The child process only seems to flush to stdout on completion
let outHandle = stdOutPipe.fileHandleForReading
outHandle.readabilityHandler = { handle in
let data = handle.availableData
if data.count > 0 {
if let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
}
}
process.waitUntilExit()
}
}
}
}
extension Tailmac {
struct Configure: ParsableCommand {
@Option(help: "The vm identifier") var id: String
@Option(help: "The mac address of the socket network interface") var mac: String?
@Option(help: "The port for the virtio socket device") var port: String?
@Option(help: "The named socket for the socket network interface") var sock: String?
@Option(help: "The desired RAM in bytes") var mem: String?
@Option(help: "The ethernet address for a standard NAT adapter") var ethermac: String?
mutating func run() {
let config = Config(id)
let vmExists = FileManager.default.fileExists(atPath: config.vmDataURL.path())
if !vmExists {
print("VM with id \(id) doesn't exist. Cannot configure.")
return
}
if let mac {
config.mac = mac
}
if let port, let portInt = UInt32(port) {
config.port = portInt
}
if let ethermac {
config.ethermac = ethermac
}
if let mem, let membytes = UInt64(mem) {
config.memorySize = membytes
}
if let sock {
config.serverSocket = sock
}
config.persist()
let str = String(data:try! JSONEncoder().encode(config), encoding: .utf8)!
print("New Config: \(str)")
}
}
}
extension Tailmac {
struct Delete: ParsableCommand {
@Option(help: "The vm identifer") var id: String?
mutating func run() {
guard let id else {
print("Usage: Installer delete --id=<id>")
return
}
let config = Config(id)
let vmExists = FileManager.default.fileExists(atPath: config.vmDataURL.path())
if !vmExists {
print("VM with id \(id) doesn't exist. Cannot delete.")
return
}
do {
try FileManager.default.removeItem(at: config.vmDataURL)
} catch {
print("Whoops... Deletion failed \(error)")
}
}
}
}
extension Tailmac {
struct Clone: ParsableCommand {
@Option(help: "The vm identifier") var id: String
@Option(help: "The vm identifier for the cloned vm") var targetId: String
mutating func run() {
let config = Config(id)
let targetConfig = Config(targetId)
if id == targetId {
fatalError("The ids match. Clone failed.")
}
let vmExists = FileManager.default.fileExists(atPath: config.vmDataURL.path())
if !vmExists {
print("VM with id \(id) doesn't exist. Cannot clone.")
return
}
print("Cloning \(config.vmDataURL) to \(targetConfig.vmDataURL)")
do {
try FileManager.default.copyItem(at: config.vmDataURL, to: targetConfig.vmDataURL)
} catch {
print("Whoops... Cloning failed \(error)")
}
}
}
}
extension Tailmac {
struct RefreshImage: ParsableCommand {
mutating func run() {
let config = Config()
let exists = FileManager.default.fileExists(atPath: config.restoreImageURL.path())
if exists {
try? FileManager.default.removeItem(at: config.restoreImageURL)
}
let restoreImage = RestoreImage(config.restoreImageURL)
restoreImage.download {
print("Restore image refreshed")
}
}
}
}
extension Tailmac {
struct Create: ParsableCommand {
@Option(help: "The vm identifier. Each VM instance needs a unique ID.") var id: String
@Option(help: "The mac address of the socket network interface") var mac: String?
@Option(help: "The port for the virtio socket device") var port: String?
@Option(help: "The named socket for the socket network interface") var sock: String?
@Option(help: "The desired RAM in bytes") var mem: String?
@Option(help: "The ethernet address for a standard NAT adapter") var ethermac: String?
@Option(help: "The image name to build from. If omitted we will use RestoreImage.ipsw in ~/VM.bundle and download it if needed") var image: String?
mutating func run() {
buildVM(id)
}
func buildVM(_ id: String) {
print("Configuring vm with id \(id)")
let config = Config(id)
let installer = VMInstaller(config)
let vmExists = FileManager.default.fileExists(atPath: config.vmDataURL.path())
if vmExists {
print("VM with id \(id) already exists. No action taken.")
return
}
createDir(config.vmDataURL.path())
if let mac {
config.mac = mac
}
if let port, let portInt = UInt32(port) {
config.port = portInt
}
if let ethermac {
config.ethermac = ethermac
}
if let mem, let membytes = UInt64(mem) {
config.memorySize = membytes
}
if let sock {
config.serverSocket = sock
}
config.persist()
let restoreImagePath = image ?? config.restoreImageURL.path()
let exists = FileManager.default.fileExists(atPath: restoreImagePath)
if exists {
print("Using existing restore image at \(restoreImagePath)")
installer.installMacOS(ipswURL: URL(fileURLWithPath: restoreImagePath))
} else {
if image != nil {
fatalError("Unable to find custom restore image")
}
print("Downloading default restore image to \(config.restoreImageURL)")
let restoreImage = RestoreImage(URL(fileURLWithPath: restoreImagePath))
restoreImage.download {
// Install from the restore image that you downloaded.
installer.installMacOS(ipswURL: URL(fileURLWithPath: restoreImagePath))
}
}
dispatchMain()
}
}
}