diff options
Diffstat (limited to 'ops')
186 files changed, 11268 insertions, 0 deletions
diff --git a/ops/besadii/default.nix b/ops/besadii/default.nix new file mode 100644 index 000000000000..1199c56cfb94 --- /dev/null +++ b/ops/besadii/default.nix @@ -0,0 +1,8 @@ +# This program is used as a Gerrit hook to trigger builds on +# Buildkite, Sourcegraph reindexing and other maintenance tasks. +{ depot, ... }: + +depot.nix.buildGo.program { + name = "besadii"; + srcs = [ ./main.go ]; +} diff --git a/ops/besadii/main.go b/ops/besadii/main.go new file mode 100644 index 000000000000..412ae3a73bea --- /dev/null +++ b/ops/besadii/main.go @@ -0,0 +1,558 @@ +// Copyright 2019-2020 Google LLC. +// SPDX-License-Identifier: Apache-2.0 +// +// besadii is a small CLI tool that is invoked as a hook by various +// programs to cause CI-related actions. +// +// It supports the following modes & operations: +// +// Gerrit (ref-updated) hook: +// - Trigger Buildkite CI builds +// - Trigger SourceGraph repository index updates +// +// Buildkite (post-command) hook: +// - Submit CL verification status back to Gerrit +package main + +import ( + "bytes" + "encoding/json" + "flag" + "fmt" + "io/ioutil" + "log/syslog" + "net/http" + "net/mail" + "os" + "os/user" + "path" + "regexp" + "strconv" + "strings" +) + +// Regular expression to extract change ID out of a URL +var changeIdRegexp = regexp.MustCompile(`^.*/(\d+)$`) + +// Regular expression to check if gerritChangeName valid. The +// limitation could be what is allowed for a git branch name. For now +// we want to have a stricter limitation for readability and ease of +// use. +var gerritChangeNameRegexp = `^[a-z0-9]+$` +var gerritChangeNameCheck = regexp.MustCompile(gerritChangeNameRegexp) + +// besadii configuration file structure +type config struct { + // Required configuration for Buildkite<>Gerrit monorepo + // integration. + Repository string `json:"repository"` + Branch string `json:"branch"` + GerritUrl string `json:"gerritUrl"` + GerritUser string `json:"gerritUser"` + GerritPassword string `json:"gerritPassword"` + GerritLabel string `json:"gerritLabel"` + BuildkiteOrg string `json:"buildkiteOrg"` + BuildkiteProject string `json:"buildkiteProject"` + BuildkiteToken string `json:"buildkiteToken"` + GerritChangeName string `json:"gerritChangeName"` + + // Optional configuration for Sourcegraph trigger updates. + SourcegraphUrl string `json:"sourcegraphUrl"` + SourcegraphToken string `json:"sourcegraphToken"` +} + +// buildTrigger represents the information passed to besadii when it +// is invoked as a Gerrit hook. +// +// https://gerrit.googlesource.com/plugins/hooks/+/HEAD/src/main/resources/Documentation/hooks.md +type buildTrigger struct { + project string + ref string + commit string + author string + email string + + changeId string + patchset string +} + +type Author struct { + Name string `json:"name"` + Email string `json:"email"` +} + +// Build is the representation of a Buildkite build as described on +// https://buildkite.com/docs/apis/rest-api/builds#create-a-build +type Build struct { + Commit string `json:"commit"` + Branch string `json:"branch"` + Author Author `json:"author"` + Env map[string]string `json:"env"` +} + +// BuildResponse is the representation of Buildkite's success response +// after triggering a build. This has many fields, but we only need +// one of them. +type buildResponse struct { + WebUrl string `json:"web_url"` +} + +// reviewInput is a struct representing the data submitted to Gerrit +// to post a review on a CL. +// +// https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#review-input +type reviewInput struct { + Message string `json:"message"` + Labels map[string]int `json:"labels,omitempty"` + OmitDuplicateComments bool `json:"omit_duplicate_comments"` + IgnoreDefaultAttentionSetRules bool `json:"ignore_default_attention_set_rules"` + Tag string `json:"tag"` + Notify string `json:"notify,omitempty"` +} + +func defaultConfigLocation() (string, error) { + usr, err := user.Current() + if err != nil { + return "", fmt.Errorf("failed to get current user: %w", err) + } + + return path.Join(usr.HomeDir, "besadii.json"), nil +} + +func loadConfig() (*config, error) { + configPath := os.Getenv("BESADII_CONFIG") + + if configPath == "" { + var err error + configPath, err = defaultConfigLocation() + if err != nil { + return nil, fmt.Errorf("failed to get config location: %w", err) + } + } + + configJson, err := ioutil.ReadFile(configPath) + if err != nil { + return nil, fmt.Errorf("failed to load besadii config: %w", err) + } + + var cfg config + err = json.Unmarshal(configJson, &cfg) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal besadii config: %w", err) + } + + // The default Gerrit label to set is 'Verified', unless specified otherwise. + if cfg.GerritLabel == "" { + cfg.GerritLabel = "Verified" + } + + // The default text referring to a Gerrit Change in BuildKite. + if cfg.GerritChangeName == "" { + cfg.GerritChangeName = "cl" + } + if !gerritChangeNameCheck.MatchString(cfg.GerritChangeName) { + return nil, fmt.Errorf("invalid 'gerritChangeName': %s", cfg.GerritChangeName) + } + + // Rudimentary config validation logic + if cfg.SourcegraphUrl != "" && cfg.SourcegraphToken == "" { + return nil, fmt.Errorf("'SourcegraphToken' must be set if 'SourcegraphUrl' is set") + } + + if cfg.Repository == "" || cfg.Branch == "" { + return nil, fmt.Errorf("missing repository configuration (required: repository, branch)") + } + + if cfg.GerritUrl == "" || cfg.GerritUser == "" || cfg.GerritPassword == "" { + return nil, fmt.Errorf("missing Gerrit configuration (required: gerritUrl, gerritUser, gerritPassword)") + } + + if cfg.BuildkiteOrg == "" || cfg.BuildkiteProject == "" || cfg.BuildkiteToken == "" { + return nil, fmt.Errorf("mising Buildkite configuration (required: buildkiteOrg, buildkiteProject, buildkiteToken)") + } + + return &cfg, nil +} + +// linkToChange creates the full link to a change's patchset in Gerrit +func linkToChange(cfg *config, changeId, patchset string) string { + return fmt.Sprintf("%s/c/%s/+/%s/%s", cfg.GerritUrl, cfg.Repository, changeId, patchset) +} + +// updateGerrit posts a comment on a Gerrit CL to indicate the current build status. +func updateGerrit(cfg *config, review reviewInput, changeId, patchset string) { + body, _ := json.Marshal(review) + reader := ioutil.NopCloser(bytes.NewReader(body)) + + url := fmt.Sprintf("%s/a/changes/%s/revisions/%s/review", cfg.GerritUrl, changeId, patchset) + req, err := http.NewRequest("POST", url, reader) + if err != nil { + fmt.Fprintf(os.Stderr, "failed to create an HTTP request: %w", err) + os.Exit(1) + } + + req.SetBasicAuth(cfg.GerritUser, cfg.GerritPassword) + req.Header.Add("Content-Type", "application/json") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + fmt.Errorf("failed to update %s on %s: %w", cfg.GerritChangeName, cfg.GerritUrl, err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + respBody, _ := ioutil.ReadAll(resp.Body) + fmt.Fprintf(os.Stderr, "received non-success response from Gerrit: %s (%v)", respBody, resp.Status) + } else { + fmt.Printf("Added CI status comment on %s", linkToChange(cfg, changeId, patchset)) + } +} + +// Trigger a build of a given branch & commit on Buildkite +func triggerBuild(cfg *config, log *syslog.Writer, trigger *buildTrigger) error { + env := make(map[string]string) + branch := trigger.ref + + // Pass information about the originating Gerrit change to the + // build, if it is for a patchset. + // + // This information is later used by besadii when invoked by Gerrit + // to communicate the build status back to Gerrit. + headBuild := true + if trigger.changeId != "" && trigger.patchset != "" { + env["GERRIT_CHANGE_URL"] = linkToChange(cfg, trigger.changeId, trigger.patchset) + env["GERRIT_CHANGE_ID"] = trigger.changeId + env["GERRIT_PATCHSET"] = trigger.patchset + headBuild = false + + // The branch doesn't have to be a real ref (it's just used to + // group builds), so make it the identifier for the CL. + branch = fmt.Sprintf("%s/%v", cfg.GerritChangeName, strings.Split(trigger.ref, "/")[3]) + } + + build := Build{ + Commit: trigger.commit, + Branch: branch, + Env: env, + Author: Author{ + Name: trigger.author, + Email: trigger.email, + }, + } + + body, _ := json.Marshal(build) + reader := ioutil.NopCloser(bytes.NewReader(body)) + + bkUrl := fmt.Sprintf("https://api.buildkite.com/v2/organizations/%s/pipelines/%s/builds", cfg.BuildkiteOrg, cfg.BuildkiteProject) + req, err := http.NewRequest("POST", bkUrl, reader) + if err != nil { + return fmt.Errorf("failed to create an HTTP request: %w", err) + } + + req.Header.Add("Authorization", "Bearer "+cfg.BuildkiteToken) + req.Header.Add("Content-Type", "application/json") + + resp, err := http.DefaultClient.Do(req) + if err != nil { + // This might indicate a temporary error on the Buildkite side. + return fmt.Errorf("failed to send Buildkite request: %w", err) + } + defer resp.Body.Close() + + respBody, err := ioutil.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read Buildkite response body: %w", err) + } + + if resp.StatusCode != http.StatusCreated { + return fmt.Errorf("received non-success response from Buildkite: %s (%v)", respBody, resp.Status) + } + + var buildResp buildResponse + err = json.Unmarshal(respBody, &buildResp) + if err != nil { + return fmt.Errorf("failed to unmarshal build response: %w", err) + } + + fmt.Fprintf(log, "triggered build for ref %q at commit %q: %s", trigger.ref, trigger.commit, buildResp.WebUrl) + + // For builds of the HEAD branch there is nothing else to do + if headBuild { + return nil + } + + // Report the status back to the Gerrit CL so that users can click + // through to the running build. + msg := fmt.Sprintf("Started build for patchset #%s on: %s", trigger.patchset, buildResp.WebUrl) + review := reviewInput{ + Message: msg, + OmitDuplicateComments: true, + Tag: "autogenerated:buildkite~trigger", + + // Do not update the attention set for this comment. + IgnoreDefaultAttentionSetRules: true, + + Notify: "NONE", + } + updateGerrit(cfg, review, trigger.changeId, trigger.patchset) + + return nil +} + +// Trigger a Sourcegraph repository index update. +// +// https://docs.sourcegraph.com/admin/repo/webhooks +func triggerIndexUpdate(cfg *config, log *syslog.Writer) error { + req, err := http.NewRequest("POST", cfg.SourcegraphUrl, nil) + if err != nil { + return err + } + + req.Header.Add("Authorization", "token "+cfg.SourcegraphToken) + + _, err = http.DefaultClient.Do(req) + if err != nil { + return fmt.Errorf("failed to trigger Sourcegraph index update: %w", err) + } + + log.Info("triggered sourcegraph index update") + return nil +} + +// Gerrit passes more flags than we want, but Rob Pike decided[0] in +// 2013 that the Go art project will not allow users to ignore flags +// because he "doesn't like it". This function allows users to ignore +// flags. +// +// [0]: https://github.com/golang/go/issues/6112#issuecomment-66083768 +func ignoreFlags(ignore []string) { + for _, f := range ignore { + flag.String(f, "", "flag to ignore") + } +} + +// Extract the username & email from Gerrit's uploader flag and set it +// on the trigger struct, for display in Buildkite. +func extractChangeUploader(uploader string, trigger *buildTrigger) error { + // Gerrit passes the uploader in another extra layer of quotes. + uploader, err := strconv.Unquote(uploader) + if err != nil { + return fmt.Errorf("failed to unquote email - forgot quotes on manual invocation?: %w", err) + } + + // Extract the uploader username & email from the input passed by + // Gerrit (in RFC 5322 format). + addr, err := mail.ParseAddress(uploader) + if err != nil { + return fmt.Errorf("invalid change uploader (%s): %w", uploader, err) + } + + trigger.author = addr.Name + trigger.email = addr.Address + + return nil +} + +// Extract the buildtrigger struct out of the flags passed to besadii +// when invoked as Gerrit's 'patchset-created' hook. This hook is used +// for triggering CI on in-progress CLs. +func buildTriggerFromPatchsetCreated(cfg *config) (*buildTrigger, error) { + // Information that needs to be returned + var trigger buildTrigger + + // Information that is only needed for parsing + var targetBranch, changeUrl, uploader, kind string + + flag.StringVar(&trigger.project, "project", "", "Gerrit project") + flag.StringVar(&trigger.commit, "commit", "", "commit hash") + flag.StringVar(&trigger.patchset, "patchset", "", "patchset ID") + + flag.StringVar(&targetBranch, "branch", "", "CL target branch") + flag.StringVar(&changeUrl, "change-url", "", "HTTPS URL of change") + flag.StringVar(&uploader, "uploader", "", "Change uploader name & email") + flag.StringVar(&kind, "kind", "", "Kind of patchset") + + // patchset-created also passes various flags which we don't need. + ignoreFlags([]string{"topic", "change", "uploader-username", "change-owner", "change-owner-username"}) + + flag.Parse() + + // Ignore patchsets which do not contain code changes + if kind == "NO_CODE_CHANGE" || kind == "NO_CHANGE" { + return nil, nil + } + + // Parse username & email + err := extractChangeUploader(uploader, &trigger) + if err != nil { + return nil, err + } + + // If the patchset is not for the HEAD branch of the monorepo, then + // we can ignore it. It might be some other kind of change + // (refs/meta/config or Gerrit-internal), but it is not an error. + if trigger.project != cfg.Repository || targetBranch != cfg.Branch { + return nil, nil + } + + // Change ID is not directly passed in the numeric format, so we + // need to extract it out of the URL + matches := changeIdRegexp.FindStringSubmatch(changeUrl) + trigger.changeId = matches[1] + + // Construct the CL ref from which the build should happen. + changeId, _ := strconv.Atoi(trigger.changeId) + trigger.ref = fmt.Sprintf( + "refs/changes/%02d/%s/%s", + changeId%100, trigger.changeId, trigger.patchset, + ) + + return &trigger, nil +} + +// Extract the buildtrigger struct out of the flags passed to besadii +// when invoked as Gerrit's 'change-merged' hook. This hook is used +// for triggering HEAD builds after change submission. +func buildTriggerFromChangeMerged(cfg *config) (*buildTrigger, error) { + // Information that needs to be returned + var trigger buildTrigger + + // Information that is only needed for parsing + var targetBranch, submitter string + + flag.StringVar(&trigger.project, "project", "", "Gerrit project") + flag.StringVar(&trigger.commit, "commit", "", "Commit hash") + flag.StringVar(&submitter, "submitter", "", "Submitter email & username") + flag.StringVar(&targetBranch, "branch", "", "CL target branch") + + // Ignore extra flags passed by change-merged + ignoreFlags([]string{"change", "topic", "change-url", "submitter-username", "newrev", "change-owner", "change-owner-username"}) + + flag.Parse() + + // Parse username & email + err := extractChangeUploader(submitter, &trigger) + if err != nil { + return nil, err + } + + // If the patchset is not for the HEAD branch of the monorepo, then + // we can ignore it. + if trigger.project != cfg.Repository || targetBranch != cfg.Branch { + return nil, nil + } + + trigger.ref = "refs/heads/" + targetBranch + + return &trigger, nil +} + +func gerritHookMain(cfg *config, log *syslog.Writer, trigger *buildTrigger) { + if trigger == nil { + // The hook was not for something we care about. + os.Exit(0) + } + + err := triggerBuild(cfg, log, trigger) + + if err != nil { + log.Err(fmt.Sprintf("failed to trigger Buildkite build: %s", err)) + } + + if cfg.SourcegraphUrl != "" && trigger.ref == "refs/heads/canon" { + err = triggerIndexUpdate(cfg, log) + if err != nil { + log.Err(fmt.Sprintf("failed to trigger sourcegraph index update: %s", err)) + } + } +} + +func postCommandMain(cfg *config) { + changeId := os.Getenv("GERRIT_CHANGE_ID") + patchset := os.Getenv("GERRIT_PATCHSET") + + if changeId == "" || patchset == "" { + // If these variables are unset, but the hook was invoked, the + // build was most likely for a branch and not for a CL - no status + // needs to be reported back to Gerrit! + fmt.Printf("This isn't a %s build, nothing to do. Have a nice day!\n", cfg.GerritChangeName) + return + } + + if os.Getenv("BUILDKITE_LABEL") != ":duck:" { + // this is not the build stage, don't do anything. + return + } + + var vote int + var verb string + var notify string + + if os.Getenv("BUILDKITE_COMMAND_EXIT_STATUS") == "0" { + vote = 1 // automation passed: +1 in Gerrit + verb = "passed" + notify = "NONE" + } else { + vote = -1 + verb = "failed" + notify = "OWNER" + } + + msg := fmt.Sprintf("Build of patchset %s %s: %s", patchset, verb, os.Getenv("BUILDKITE_BUILD_URL")) + review := reviewInput{ + Message: msg, + OmitDuplicateComments: true, + Labels: map[string]int{ + cfg.GerritLabel: vote, + }, + + // Update the attention set if we are failing this patchset. + IgnoreDefaultAttentionSetRules: vote == 1, + + Tag: "autogenerated:buildkite~result", + + Notify: notify, + } + updateGerrit(cfg, review, changeId, patchset) +} + +func main() { + // Logging happens in syslog because it's almost impossible to get + // output out of Gerrit hooks otherwise. + log, err := syslog.New(syslog.LOG_INFO|syslog.LOG_USER, "besadii") + if err != nil { + fmt.Fprintf(os.Stderr, "failed to open syslog: %s\n", err) + os.Exit(1) + } + + log.Info(fmt.Sprintf("besadii called with arguments: %v", os.Args)) + + bin := path.Base(os.Args[0]) + cfg, err := loadConfig() + + if err != nil { + log.Crit(fmt.Sprintf("besadii configuration error: %v", err)) + os.Exit(4) + } + + if bin == "patchset-created" { + trigger, err := buildTriggerFromPatchsetCreated(cfg) + if err != nil { + log.Crit(fmt.Sprintf("failed to parse 'patchset-created' invocation from args: %v", err)) + os.Exit(1) + } + gerritHookMain(cfg, log, trigger) + } else if bin == "change-merged" { + trigger, err := buildTriggerFromChangeMerged(cfg) + if err != nil { + log.Crit(fmt.Sprintf("failed to parse 'change-merged' invocation from args: %v", err)) + os.Exit(1) + } + gerritHookMain(cfg, log, trigger) + } else if bin == "post-command" { + postCommandMain(cfg) + } else { + fmt.Fprintf(os.Stderr, "besadii does not know how to be invoked as %q, sorry!", bin) + os.Exit(1) + } +} diff --git a/ops/deploy-whitby/default.nix b/ops/deploy-whitby/default.nix new file mode 100644 index 000000000000..aafe798cbfa7 --- /dev/null +++ b/ops/deploy-whitby/default.nix @@ -0,0 +1,31 @@ +{ pkgs, ... }: + +pkgs.stdenv.mkDerivation { + name = "deploy-whitby"; + + phases = [ "installPhase" "installCheckPhase" ]; + + nativeBuildInputs = with pkgs; [ + makeWrapper + ]; + + installPhase = '' + mkdir -p $out/bin + makeWrapper ${./deploy-whitby.sh} $out/bin/deploy-whitby.sh \ + --prefix PATH : ${with pkgs; lib.makeBinPath [ + ansi2html + git + jq + nvd + ]} + ''; + + installCheckInputs = with pkgs; [ + shellcheck + ]; + + doInstallCheck = true; + installCheckPhase = '' + shellcheck $out/bin/deploy-whitby.sh + ''; +} diff --git a/ops/deploy-whitby/deploy-whitby.sh b/ops/deploy-whitby/deploy-whitby.sh new file mode 100755 index 000000000000..756aa7ae0801 --- /dev/null +++ b/ops/deploy-whitby/deploy-whitby.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -Ceuo pipefail + +HTML_ROOT="${HTML_ROOT:-/var/html/deploys.tvl.fyi}" +URL_BASE="${URL_BASE:-https://deploys.tvl.fyi/diff}" +IRCCAT_PORT="${IRCCAT_PORT:-4722}" + +drv_hash() { + basename "$1" | sed 's/-.*//' +} + +new_rev="$1" + +if [ -z "$new_rev" ]; then + >&2 echo "Usage: $0 <new_rev>" + exit 1 +fi + +if [ -d "/tmp/deploy.worktree" ]; then + >&2 echo "/tmp/deploy.worktree exists - exiting in case another deploy is currently running" + exit 1 +fi + +worktree_dir=/tmp/worktree_dir + +cleanup() { + rm -rf "$worktree_dir" +} +trap cleanup EXIT + +git clone https://cl.tvl.fyi/depot "$worktree_dir" --reference /depot +git -C "$worktree_dir" checkout "$new_rev" + +current=$(nix show-derivation /run/current-system | jq -r 'keys | .[0]') +new=$(nix-instantiate -A ops.nixos.whitbySystem "$worktree_dir") + +diff_filename="$(drv_hash "$current")..$(drv_hash "$new").html" +nvd --color always diff "$current" "$new" \ + | ansi2html \ + >| "$HTML_ROOT/diff/$diff_filename" +chmod a+r "$HTML_ROOT/diff/$diff_filename" + +echo "#tvl whitby is being deployed! system diff: $URL_BASE/$diff_filename" \ + | nc -w 5 -N localhost "$IRCCAT_PORT" + +# TODO(grfn): Actually do the deploy diff --git a/ops/dns/README.md b/ops/dns/README.md new file mode 100644 index 000000000000..2290299fe46c --- /dev/null +++ b/ops/dns/README.md @@ -0,0 +1,11 @@ +DNS configuration +================= + +This folder contains configuration for our DNS zones. The zones are hosted with +Google Cloud DNS, which supports zone-file based import/export. + +Currently there is no automation to deploy these zones, but CI will check their +integrity. + +*Note: While each zone file specifies an SOA record, it only exists to satisfy +`named-checkzone`. Cloud DNS manages this record for us.* diff --git a/ops/dns/default.nix b/ops/dns/default.nix new file mode 100644 index 000000000000..ad6e136f2756 --- /dev/null +++ b/ops/dns/default.nix @@ -0,0 +1,14 @@ +# Performs simple (local-only) validity checks on DNS zones. +{ depot, pkgs, ... }: + +let + checkZone = zone: file: pkgs.runCommandNoCC "${zone}-check" { } '' + ${pkgs.bind}/bin/named-checkzone -i local ${zone} ${file} | tee $out + ''; + +in +depot.nix.readTree.drvTargets { + nixery-dev = checkZone "nixery.dev" ./nixery.dev.zone; + tvl-fyi = checkZone "tvl.fyi" ./tvl.fyi.zone; + tvl-su = checkZone "tvl.su" ./tvl.su.zone; +} diff --git a/ops/dns/nixery.dev.zone b/ops/dns/nixery.dev.zone new file mode 100644 index 000000000000..44cabab29bd8 --- /dev/null +++ b/ops/dns/nixery.dev.zone @@ -0,0 +1,10 @@ +;; Google Cloud DNS zone for nixery.dev +nixery.dev. 21600 IN SOA ns-cloud-b1.googledomains.com. cloud-dns-hostmaster.google.com. 5 21600 3600 259200 300 +nixery.dev. 21600 IN NS ns-cloud-b1.googledomains.com. +nixery.dev. 21600 IN NS ns-cloud-b2.googledomains.com. +nixery.dev. 21600 IN NS ns-cloud-b3.googledomains.com. +nixery.dev. 21600 IN NS ns-cloud-b4.googledomains.com. + +;; Records for pointing nixery.dev to whitby +nixery.dev. 300 IN A 49.12.129.211 +nixery.dev. 300 IN AAAA 2a01:4f8:242:5b21:0:feed:edef:beef diff --git a/ops/dns/tvl.fyi.zone b/ops/dns/tvl.fyi.zone new file mode 100644 index 000000000000..d1961c6a7a82 --- /dev/null +++ b/ops/dns/tvl.fyi.zone @@ -0,0 +1,39 @@ +;; Google Cloud DNS zone for tvl.fyi. +;; +;; This zone is hosted in the project 'tvl-fyi', and registered via +;; Google Domains. +tvl.fyi. 21600 IN SOA ns-cloud-b1.googledomains.com. cloud-dns-hostmaster.google.com. 20 21600 3600 259200 300 +tvl.fyi. 21600 IN NS ns-cloud-b1.googledomains.com. +tvl.fyi. 21600 IN NS ns-cloud-b2.googledomains.com. +tvl.fyi. 21600 IN NS ns-cloud-b3.googledomains.com. +tvl.fyi. 21600 IN NS ns-cloud-b4.googledomains.com. + +;; Mail forwarding (via domains.google) +tvl.fyi. 3600 IN MX 5 gmr-smtp-in.l.google.com. +tvl.fyi. 3600 IN MX 10 alt1.gmr-smtp-in.l.google.com. +tvl.fyi. 3600 IN MX 20 alt2.gmr-smtp-in.l.google.com. +tvl.fyi. 3600 IN MX 30 alt3.gmr-smtp-in.l.google.com. +tvl.fyi. 3600 IN MX 40 alt4.gmr-smtp-in.l.google.com. + +;; Landing website is hosted on whitby on the apex. +tvl.fyi. 21600 IN A 49.12.129.211 +tvl.fyi. 21600 IN AAAA 2a01:4f8:242:5b21:0:feed:edef:beef + +;; TVL infrastructure +whitby.tvl.fyi. 21600 IN A 49.12.129.211 +whitby.tvl.fyi. 21600 IN AAAA 2a01:4f8:242:5b21:0:feed:edef:beef + +;; TVL services +at.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +atward.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +b.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +cache.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +cl.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +code.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +cs.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +deploys.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +images.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +login.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +static.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +status.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. +todo.tvl.fyi. 21600 IN CNAME whitby.tvl.fyi. diff --git a/ops/dns/tvl.su.zone b/ops/dns/tvl.su.zone new file mode 100644 index 000000000000..da46752f13ba --- /dev/null +++ b/ops/dns/tvl.su.zone @@ -0,0 +1,51 @@ +;; Google Cloud DNS for tvl.su. +;; +;; This zone is hosted in the project 'tvl-fyi', and registered via +;; NIC.RU. +;; +;; This zone is mostly identical to tvl.fyi and will eventually become +;; the primary zone. +tvl.su. 21600 IN SOA ns-cloud-b1.googledomains.com. cloud-dns-hostmaster.google.com. 33 21600 3600 259200 300 +tvl.su. 21600 IN NS ns-cloud-b1.googledomains.com. +tvl.su. 21600 IN NS ns-cloud-b2.googledomains.com. +tvl.su. 21600 IN NS ns-cloud-b3.googledomains.com. +tvl.su. 21600 IN NS ns-cloud-b4.googledomains.com. + +;; Landing website is hosted on whitby on the apex. +tvl.su. 21600 IN A 49.12.129.211 +tvl.su. 21600 IN AAAA 2a01:4f8:242:5b21:0:feed:edef:beef + +;; TVL infrastructure +whitby.tvl.su. 21600 IN A 49.12.129.211 +whitby.tvl.su. 21600 IN AAAA 2a01:4f8:242:5b21:0:feed:edef:beef + +;; TVL services +at.tvl.su. 21600 IN CNAME whitby.tvl.su. +atward.tvl.su. 21600 IN CNAME whitby.tvl.su. +b.tvl.su. 21600 IN CNAME whitby.tvl.su. +cache.tvl.su. 21600 IN CNAME whitby.tvl.su. +cl.tvl.su. 21600 IN CNAME whitby.tvl.su. +code.tvl.su. 21600 IN CNAME whitby.tvl.su. +cs.tvl.su. 21600 IN CNAME whitby.tvl.su. +images.tvl.su. 21600 IN CNAME whitby.tvl.su. +login.tvl.su. 21600 IN CNAME whitby.tvl.su. +static.tvl.su. 21600 IN CNAME whitby.tvl.su. +status.tvl.su. 21600 IN CNAME whitby.tvl.su. +todo.tvl.su. 21600 IN CNAME whitby.tvl.su. + +;; Google Workspaces domain verification +tvl.su. 21600 IN TXT "google-site-verification=3ksTBzFK3lZlzD3ddBfpaHs9qasfAiYBmvbW2T_ejH4" + +;; Google Workspaces email configuration +tvl.su. 21600 IN MX 1 aspmx.l.google.com. +tvl.su. 21600 IN MX 5 alt1.aspmx.l.google.com. +tvl.su. 21600 IN MX 5 alt2.aspmx.l.google.com. +tvl.su. 21600 IN MX 10 alt3.aspmx.l.google.com. +tvl.su. 21600 IN MX 10 alt4.aspmx.l.google.com. +tvl.su. 21600 IN TXT "v=spf1 include:_spf.google.com ~all" +google._domainkey.tvl.su. 21600 IN TXT ("v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlqCbnGa8oPwrudJK60l6MJj3NBnwj8wAPXNGtYy2SXrOBi7FT+ySwW7ATpfv6Xq9zGDUWJsENPUlFmvDiUs7Qi4scnNvSO1L+sDseB9/q1m3gMFVnTuieDO/" "T+KKkg0+uYgMM7YX5PahsAAJJ+EMb/r4afl3tcBMPR64VveKQ0hiSHA4zIYPsB9FB+b8S5C46uyY0r6WR7IzGjq2Gzb1do0kxvaKItTITWLSImcUu5ZZuXOUKJb441frVBWur5lXaYuedkxb1IRTTK0V/mBODE1D7k73MxGrqlzaMPdCqz+c3hRE18WVUkBTYjANVXDrs3yzBBVxaIAeu++vkO6BvQIDAQAB") + +;; Google Workspaces site aliases +docs.tvl.su. 21600 IN CNAME ghs.googlehosted.com. +groups.tvl.su. 21600 IN CNAME ghs.googlehosted.com. +mail.tvl.su. 21600 IN CNAME ghs.googlehosted.com. diff --git a/ops/gerrit-tvl/HttpModule.java b/ops/gerrit-tvl/HttpModule.java new file mode 100644 index 000000000000..6d785c0817fc --- /dev/null +++ b/ops/gerrit-tvl/HttpModule.java @@ -0,0 +1,14 @@ +package su.tvl.gerrit; + +import com.google.gerrit.extensions.registration.DynamicSet; +import com.google.gerrit.extensions.webui.JavaScriptPlugin; +import com.google.gerrit.extensions.webui.WebUiPlugin; +import com.google.inject.servlet.ServletModule; + +public final class HttpModule extends ServletModule { + + @Override + protected void configureServlets() { + DynamicSet.bind(binder(), WebUiPlugin.class).toInstance(new JavaScriptPlugin("tvl.js")); + } +} diff --git a/ops/gerrit-tvl/MANIFEST.MF b/ops/gerrit-tvl/MANIFEST.MF new file mode 100644 index 000000000000..bfe4eedeb6ac --- /dev/null +++ b/ops/gerrit-tvl/MANIFEST.MF @@ -0,0 +1,2 @@ +Gerrit-HttpModule: su.tvl.gerrit.HttpModule +Gerrit-PluginName: tvl diff --git a/ops/gerrit-tvl/README.md b/ops/gerrit-tvl/README.md new file mode 100644 index 000000000000..1b88600f197f --- /dev/null +++ b/ops/gerrit-tvl/README.md @@ -0,0 +1,6 @@ +# gerrit-tvl + +A Gerrit plugin that does TVL-specific things. + +You probably want to take inspiration from this rather than using it directly, +as it has a variety of TVL-ish assumptions baked into it. diff --git a/ops/gerrit-tvl/default.nix b/ops/gerrit-tvl/default.nix new file mode 100644 index 000000000000..f3bec7a3a242 --- /dev/null +++ b/ops/gerrit-tvl/default.nix @@ -0,0 +1,33 @@ +{ depot, pkgs, lib, ... }: + +let + classPath = lib.concatStringsSep ":" [ + "${depot.third_party.gerrit}/share/api/extension-api_deploy.jar" + ]; +in +pkgs.stdenvNoCC.mkDerivation rec { + name = "${pname}-${version}.jar"; + pname = "gerrit-tvl"; + version = "0.0.1"; + + src = ./.; + + nativeBuildInputs = with pkgs; [ + jdk + ]; + + buildPhase = '' + mkdir $NIX_BUILD_TOP/build + + # Build Java components. + export JAVAC="javac -cp ${classPath} -d $NIX_BUILD_TOP/build --release 11" + $JAVAC ./HttpModule.java + + # Install static files. + cp -R static $NIX_BUILD_TOP/build/static + ''; + + installPhase = '' + jar --create --file $out --manifest $src/MANIFEST.MF -C $NIX_BUILD_TOP/build . + ''; +} diff --git a/ops/gerrit-tvl/static/tvl.js b/ops/gerrit-tvl/static/tvl.js new file mode 100644 index 000000000000..2c4d7ee4739c --- /dev/null +++ b/ops/gerrit-tvl/static/tvl.js @@ -0,0 +1,191 @@ +// vim: set noai ts=2 sw=2 et: */ + +// This is a read-only Buildkite token: it was generated by lukegb@, and has +// read_builds, read_build_logs, and read_pipelines permissions. +const BUILDKITE_TOKEN = 'a150658fb61062e432f13a032962d70fa9352088'; + +function encodeParams(p) { + const pieces = []; + for (let k of Object.getOwnPropertyNames(p)) { + pieces.push(`${encodeURIComponent(k)}=${encodeURIComponent(p[k])}`); + } + return pieces.join('&'); +} + +function formatDuration(from, to) { + const millisecondsTook = Math.floor(to.valueOf() - from.valueOf()); + if (millisecondsTook < 2000) return `${millisecondsTook} ms`; + const secondsTook = Math.floor(millisecondsTook / 1000); + if (secondsTook < 100) return `${secondsTook} seconds`; + const minutesTook = Math.floor(secondsTook / 60); + if (minutesTook < 60) return `${minutesTook} minutes`; + const hoursTook = Math.floor(minutesTook / 60); + const minutesRemainder = minutesTook - (hoursTook * 60); + return `${hoursTook}hr ${minutesRemainder}min`; +} + +// Maps the status of a Buildkite *job* to the statuses available for +// a Gerrit check. +// +// Note that jobs can have statuses that, according to the Buildkite +// documentation, are only available for builds, and maybe vice-versa. +// To deal with this we simply cover all statuses for all types here. +// +// Buildkite job statuses: https://buildkite.com/docs/pipelines/notifications#job-states +// +// Gerrit check statuses: https://gerrit.googlesource.com/gerrit/+/v3.4.0/polygerrit-ui/app/api/checks.ts#167 +// +// TODO(tazjin): Use SCHEDULED status once we have upgraded Gerrit +// past 3.4 +function jobStateToCheckRunStatus(state) { + const status = { + // Statuses documented for both types + 'blocked': 'RUNNABLE', + 'canceled': 'COMPLETED', + 'canceling': 'RUNNING', + 'running': 'RUNNING', + 'scheduled': 'RUNNABLE', + 'skipped': 'COMPLETED', + + // Statuses only documented for builds + 'creating': 'RUNNABLE', + 'failed': 'COMPLETED', + 'not_run': 'COMPLETED', + 'passed': 'COMPLETED', + + // Statuses only documented for jobs + 'accepted': 'RUNNABLE', + 'assigned': 'RUNNABLE', + 'blocked_failed': 'COMPLETED', + 'broken': 'COMPLETED', + 'finished': 'COMPLETED', + 'limited': 'RUNNABLE', + 'limiting': 'RUNNABLE', + 'pending': 'RUNNABLE', + 'timed_out': 'COMPLETED', + 'timing_out': 'RUNNING', + 'unblocked': 'RUNNABLE', + 'unblocked_failed': 'COMPLETED', + 'waiting': 'RUNNABLE', + 'waiting_failed': 'COMPLETED', + }[state]; + + if (!status) { + console.log(`unknown Buildkite job state: ${state}`); + } + + return status; +} + +const tvlChecksProvider = { + async fetch(change) { + let {changeNumber, patchsetNumber, repo} = change; + + const experiments = window.ENABLED_EXPERIMENTS || []; + if (experiments.includes("UiFeature__tvl_check_debug")) { + changeNumber = 2872; + patchsetNumber = 4; + repo = 'depot'; + } + + if (repo !== 'depot') { + // We only handle TVL's depot at the moment. + return {responseCode: 'OK'}; + } + + const params = { + // besadii groups different patchsets of the same CL under this fake ref + branch: `cl/${changeNumber.toString()}`, + }; + const url = `https://api.buildkite.com/v2/organizations/tvl/pipelines/depot/builds?${encodeParams(params)}`; + const resp = await fetch(url, { + headers: { + Authorization: `Bearer ${BUILDKITE_TOKEN}`, + }, + }); + const respJSON = await resp.json(); + + const runs = []; + for (let i = 0; i < respJSON.length; i++) { + const attempt = respJSON.length - i; + const build = respJSON[i]; + + for (let job of build.jobs) { + // Skip non-command jobs (e.g. waiting/grouping jobs) + if (job.type !== 'script') { + continue; + } + + // Skip jobs marked as 'broken' (this means they were skipped + // intentionally) + if (job.state === 'broken') { + continue; + } + + // TODO(lukegb): add the ability to retry these + const checkRun = { + patchset: parseInt(build.env.GERRIT_PATCHSET, 10), + attempt: attempt, + externalId: job.id, + checkName: job.name, + checkDescription: job.command, + checkLink: job.web_url, + status: jobStateToCheckRunStatus(job.state), + labelName: 'Verified', + }; + + if (job.scheduled_at) { + checkRun.scheduledTimestamp = new Date(job.scheduled_at); + } + + if (job.started_at) { + checkRun.startedTimestamp = new Date(job.started_at); + } + + if (job.finished_at) { + checkRun.finishedTimestamp = new Date(job.finished_at); + } + + let statusDescription = job.state; + if (checkRun.startedTimestamp && checkRun.finishedTimestamp) { + statusDescription = `${statusDescription} in ${formatDuration(checkRun.startedTimestamp, checkRun.finishedTimestamp)}`; + } else if (checkRun.startedTimestamp) { + statusDescription = `${statusDescription} for ${formatDuration(checkRun.startedTimestamp, new Date())}`; + } else if (checkRun.scheduledTimestamp) { + statusDescription = `${statusDescription} for ${formatDuration(checkRun.scheduledTimestamp, new Date())}`; + } + checkRun.statusDescription = statusDescription; + + if (['failed', 'timed_out'].includes(job.state)) { + const result = { + // TODO(lukegb): get the log as the message here (the Gerrit + // implementation doesn't yet seem to support newlines in message + // strings...) + links: [{ + url: job.web_url, + tooltip: "Buildkite", + primary: true, + icon: 'EXTERNAL', + }], + category: 'ERROR', + summary: `${job.command} failed`, + }; + checkRun.results = [result]; + } + + runs.push(checkRun); + } + } + + return { + responseCode: 'OK', + runs: runs, + }; + }, +}; + +Gerrit.install(plugin => { + console.log('TVL plugin initialising'); + + plugin.checks().register(tvlChecksProvider); +}); diff --git a/ops/glesys/.gitignore b/ops/glesys/.gitignore new file mode 100644 index 000000000000..de8e8f12ee98 --- /dev/null +++ b/ops/glesys/.gitignore @@ -0,0 +1,3 @@ +.terraform* +terraform.tfstate* +.envrc diff --git a/ops/glesys/README.md b/ops/glesys/README.md new file mode 100644 index 000000000000..00f61a93604b --- /dev/null +++ b/ops/glesys/README.md @@ -0,0 +1,20 @@ +Terraform for GleSYS +====================== + +This contains the Terraform configuration for deploying TVL's +infrastructure at [GleSYS](https://glesys.com). This includes object +storage (e.g. for backups and Terraform state) and DNS. + +Secrets are needed for applying this. The encrypted file +`//ops/secrets/tf-glesys.age` contains `export` calls which should be +sourced, for example via `direnv`, by users with the appropriate +credentials. + +An example `direnv` configuration used by tazjin is this: + +``` +# //ops/secrets/.envrc +source_up +eval $(age --decrypt -i ~/.ssh/id_ed25519 $(git rev-parse --show-toplevel)/ops/secrets/tf-glesys.age) +watch_file $(git rev-parse --show-toplevel)/secrets/tf-glesys.age +``` diff --git a/ops/glesys/default.nix b/ops/glesys/default.nix new file mode 100644 index 000000000000..2dfb505fb423 --- /dev/null +++ b/ops/glesys/default.nix @@ -0,0 +1,8 @@ +{ depot, pkgs, ... }: + +depot.nix.readTree.drvTargets { + # Provide a Terraform wrapper with the right provider installed. + terraform = pkgs.terraform.withPlugins (_: [ + depot.third_party.terraform-provider-glesys + ]); +} diff --git a/ops/glesys/dns-nixery-dev.tf b/ops/glesys/dns-nixery-dev.tf new file mode 100644 index 000000000000..53a421d20e34 --- /dev/null +++ b/ops/glesys/dns-nixery-dev.tf @@ -0,0 +1,44 @@ +# DNS configuration for nixery.dev +# +# TODO(tazjin): Figure out what to do with //ops/dns for this. I'd +# like to keep zonefiles in case we move providers again, but maybe +# generate something from them. Not sure yet. + +resource "glesys_dnsdomain" "nixery_dev" { + name = "nixery.dev" +} + +resource "glesys_dnsdomain_record" "nixery_dev_apex_A" { + domain = glesys_dnsdomain.nixery_dev.id + host = "@" + type = "A" + data = var.whitby_ipv4 +} + +resource "glesys_dnsdomain_record" "nixery_dev_apex_AAAA" { + domain = glesys_dnsdomain.nixery_dev.id + host = "@" + type = "AAAA" + data = var.whitby_ipv6 +} + +resource "glesys_dnsdomain_record" "nixery_dev_NS1" { + domain = glesys_dnsdomain.nixery_dev.id + host = "@" + type = "NS" + data = "ns1.namesystem.se." +} + +resource "glesys_dnsdomain_record" "nixery_dev_NS2" { + domain = glesys_dnsdomain.nixery_dev.id + host = "@" + type = "NS" + data = "ns2.namesystem.se." +} + +resource "glesys_dnsdomain_record" "nixery_dev_NS3" { + domain = glesys_dnsdomain.nixery_dev.id + host = "@" + type = "NS" + data = "ns3.namesystem.se." +} diff --git a/ops/glesys/dns-tvl-fyi.tf b/ops/glesys/dns-tvl-fyi.tf new file mode 100644 index 000000000000..803bfeae08ba --- /dev/null +++ b/ops/glesys/dns-tvl-fyi.tf @@ -0,0 +1,99 @@ +# DNS configuration for tvl.fyi + +resource "glesys_dnsdomain" "tvl_fyi" { + name = "tvl.fyi" +} + +resource "glesys_dnsdomain_record" "tvl_fyi_NS1" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "NS" + data = "ns1.namesystem.se." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_NS2" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "NS" + data = "ns2.namesystem.se." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_NS3" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "NS" + data = "ns3.namesystem.se." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_apex_A" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "A" + data = var.whitby_ipv4 +} + +resource "glesys_dnsdomain_record" "tvl_fyi_apex_AAAA" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "AAAA" + data = var.whitby_ipv6 +} + +resource "glesys_dnsdomain_record" "tvl_fyi_whitby_A" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "whitby" + type = "A" + data = var.whitby_ipv4 +} + +resource "glesys_dnsdomain_record" "tvl_fyi_whitby_AAAA" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "whitby" + type = "AAAA" + data = var.whitby_ipv6 +} + +# This record is responsible for hosting ~all TVL services. Be +# mindful! +resource "glesys_dnsdomain_record" "tvl_fyi_wildcard" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "*" + type = "CNAME" + data = "whitby.tvl.fyi." +} + +# Google Domains mail forwarding configuration (no sending) +resource "glesys_dnsdomain_record" "tvl_fyi_MX_5" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "MX" + data = "5 gmr-smtp-in.l.google.com." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_MX_10" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "MX" + data = "10 alt1.gmr-smtp-in.l.google.com." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_MX_20" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "MX" + data = "20 alt2.gmr-smtp-in.l.google.com." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_MX_30" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "MX" + data = "30 alt3.aspmx.l.google.com." +} + +resource "glesys_dnsdomain_record" "tvl_fyi_MX_40" { + domain = glesys_dnsdomain.tvl_fyi.id + host = "@" + type = "MX" + data = "40 alt4.gmr-smtp-in.l.google.com." +} diff --git a/ops/glesys/dns-tvl-su.tf b/ops/glesys/dns-tvl-su.tf new file mode 100644 index 000000000000..39fd054e01dd --- /dev/null +++ b/ops/glesys/dns-tvl-su.tf @@ -0,0 +1,122 @@ +# DNS configuration for tvl.su + +resource "glesys_dnsdomain" "tvl_su" { + name = "tvl.su" +} + +resource "glesys_dnsdomain_record" "tvl_su_NS1" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "NS" + data = "ns1.namesystem.se." +} + +resource "glesys_dnsdomain_record" "tvl_su_NS2" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "NS" + data = "ns2.namesystem.se." +} + +resource "glesys_dnsdomain_record" "tvl_su_NS3" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "NS" + data = "ns3.namesystem.se." +} + +resource "glesys_dnsdomain_record" "tvl_su_apex_A" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "A" + data = var.whitby_ipv4 +} + +resource "glesys_dnsdomain_record" "tvl_su_apex_AAAA" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "AAAA" + data = var.whitby_ipv6 +} + +resource "glesys_dnsdomain_record" "tvl_su_whitby_A" { + domain = glesys_dnsdomain.tvl_su.id + host = "whitby" + type = "A" + data = var.whitby_ipv4 +} + +resource "glesys_dnsdomain_record" "tvl_su_whitby_AAAA" { + domain = glesys_dnsdomain.tvl_su.id + host = "whitby" + type = "AAAA" + data = var.whitby_ipv6 +} + +resource "glesys_dnsdomain_record" "tvl_su_sanduny_A" { + domain = glesys_dnsdomain.tvl_su.id + host = "sanduny" + type = "A" + data = var.sanduny_ipv4 +} + +resource "glesys_dnsdomain_record" "tvl_su_sanduny_AAAA" { + domain = glesys_dnsdomain.tvl_su.id + host = "sanduny" + type = "AAAA" + data = var.sanduny_ipv6 +} + +# This record is responsible for hosting ~all TVL services. Be +# mindful! +resource "glesys_dnsdomain_record" "tvl_su_wildcard" { + domain = glesys_dnsdomain.tvl_su.id + host = "*" + type = "CNAME" + data = "whitby.tvl.su." +} + +resource "glesys_dnsdomain_record" "tvl_su_TXT_google_site" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "TXT" + data = "google-site-verification=3ksTBzFK3lZlzD3ddBfpaHs9qasfAiYBmvbW2T_ejH4" +} + +# Yandex 360 setup + +resource "glesys_dnsdomain_record" "tvl_su_TXT_yandex" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "TXT" + data = "yandex-verification: b99c43b7838949dc" +} + +resource "glesys_dnsdomain_record" "tvl_su_MX_yandex" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "MX" + data = "10 mx.yandex.net." +} + +resource "glesys_dnsdomain_record" "tvl_su_TXT_yandex_spf" { + domain = glesys_dnsdomain.tvl_su.id + host = "@" + type = "TXT" + data = "v=spf1 redirect=_spf.yandex.net" + +} + +resource "glesys_dnsdomain_record" "tvl_su_TXT_yandex_dkim" { + domain = glesys_dnsdomain.tvl_su.id + host = "mail._domainkey" + type = "TXT" + data = "v=DKIM1; k=rsa; t=s; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDaRdWF8BtCHlTTQN8O+E5Qn27FVIpUEAdk1uq2vdIKh1Un/3NfdWtxStcS1Mf0iEprt1Fb4zgWOkDlPi+hH/UZqiC9QNeNqEBGMB9kgJyfsUt6cDCIVGvn8PT9JcZW1jxSziOj8nUWB4noqbaVcQNqNbwtaHPm3aifwKwScxVO7wIDAQAB" +} + +resource "glesys_dnsdomain_record" "tvl_su_CNAME_yandex_mail" { + domain = glesys_dnsdomain.tvl_su.id + host = "mail" + type = "CNAME" + data = "domain.mail.yandex.net." +} diff --git a/ops/glesys/main.tf b/ops/glesys/main.tf new file mode 100644 index 000000000000..9032d501a518 --- /dev/null +++ b/ops/glesys/main.tf @@ -0,0 +1,72 @@ +# Configure TVL resources hosted with GleSYS. +# +# Most importantly: +# - all of our DNS +# - object storage (e.g. backups) + +terraform { + required_providers { + glesys = { + source = "depot/glesys" + } + } + + backend "s3" { + endpoint = "https://objects.dc-sto1.glesys.net" + bucket = "tvl-state" + key = "terraform/tvl-glesys" + region = "glesys" + + skip_credentials_validation = true + skip_region_validation = true + skip_metadata_api_check = true + } +} + +provider "glesys" { + userid = "cl26117" # generated by GleSYS +} + +resource "glesys_objectstorage_instance" "tvl-backups" { + description = "tvl-backups" + datacenter = "dc-sto1" +} + +resource "glesys_objectstorage_instance" "tvl-state" { + description = "tvl-state" + datacenter = "dc-sto1" + + lifecycle { + ignore_changes = [accesskey] + } +} + +resource "glesys_objectstorage_credential" "terraform-state" { + instanceid = glesys_objectstorage_instance.tvl-state.id + description = "key for terraform state" +} + +resource "glesys_objectstorage_credential" "litestream" { + instanceid = glesys_objectstorage_instance.tvl-state.id + description = "key for litestream" +} + +variable "whitby_ipv4" { + type = string + default = "49.12.129.211" +} + +variable "whitby_ipv6" { + type = string + default = "2a01:4f8:242:5b21:0:feed:edef:beef" +} + +variable "sanduny_ipv4" { + type = string + default = "85.119.82.231" +} + +variable "sanduny_ipv6" { + type = string + default = "2001:ba8:1f1:f109::feed:edef:beef" +} diff --git a/ops/journaldriver/.gitignore b/ops/journaldriver/.gitignore new file mode 100644 index 000000000000..29e65519ba35 --- /dev/null +++ b/ops/journaldriver/.gitignore @@ -0,0 +1,3 @@ +result +/target +**/*.rs.bk diff --git a/ops/journaldriver/Cargo.lock b/ops/journaldriver/Cargo.lock new file mode 100644 index 000000000000..0b7afd993291 --- /dev/null +++ b/ops/journaldriver/Cargo.lock @@ -0,0 +1,511 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr 2.4.1", +] + +[[package]] +name = "anyhow" +version = "1.0.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4361135be9122e0870de935d7c439aef945b9f9ddd4199a553b5270b49c82a27" + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "crimp" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe8f9a320ad9c1a2e3bacedaa281587bd297fb10a10179fd39f777049d04794" +dependencies = [ + "curl", + "serde", + "serde_json", +] + +[[package]] +name = "cstr-argument" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514570a4b719329df37f93448a70df2baac553020d0eb43a8dfa9c1f5ba7b658" +dependencies = [ + "cfg-if 0.1.10", + "memchr 1.0.2", +] + +[[package]] +name = "curl" +version = "0.4.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37d855aeef205b43f65a5001e0997d81f8efca7badad4fad7d897aa7f0d0651f" +dependencies = [ + "curl-sys", + "libc", + "openssl-probe", + "openssl-sys", + "schannel", + "socket2", + "winapi", +] + +[[package]] +name = "curl-sys" +version = "0.4.53+curl-7.82.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8092905a5a9502c312f223b2775f57ec5c5b715f9a15ee9d2a8591d1364a0352" +dependencies = [ + "cc", + "libc", + "libz-sys", + "openssl-sys", + "pkg-config", + "vcpkg", + "winapi", +] + +[[package]] +name = "env_logger" +version = "0.5.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38" +dependencies = [ + "atty", + "humantime", + "log", + "regex", + "termcolor", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "humantime" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" +dependencies = [ + "quick-error", +] + +[[package]] +name = "itoa" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" + +[[package]] +name = "journaldriver" +version = "1.1.0" +dependencies = [ + "anyhow", + "crimp", + "env_logger", + "lazy_static", + "log", + "medallion", + "pkg-config", + "serde", + "serde_derive", + "serde_json", + "systemd", + "time", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.123" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb691a747a7ab48abc15c5b42066eaafde10dc427e3b6ee2a1cf43db04c763bd" + +[[package]] +name = "libsystemd-sys" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7b98458cd04a5c3aacba6f1a3a3c4b9abcb0ae4d66a055eee502e0d52dc226b" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "libz-sys" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f35facd4a5673cb5a48822be2be1d4236c1c99cb4113cab7061ac720d5bf859" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "log" +version = "0.4.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" +dependencies = [ + "cfg-if 1.0.0", +] + +[[package]] +name = "medallion" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35b83c0c3277d722b53a6eb24e3c1321172f85b715cc7405add8ffd1f2f06288" +dependencies = [ + "anyhow", + "base64", + "openssl", + "serde", + "serde_json", + "time", +] + +[[package]] +name = "memchr" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "148fab2e51b4f1cfc66da2a7c32981d1d3c083a803978268bb11fe4b86925e7a" +dependencies = [ + "libc", +] + +[[package]] +name = "memchr" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" + +[[package]] +name = "num_threads" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aba1801fb138d8e85e11d0fc70baf4fe1cdfffda7c6cd34a854905df588e5ed0" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" + +[[package]] +name = "openssl" +version = "0.10.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c7ae222234c30df141154f159066c5093ff73b63204dcda7121eb082fc56a95" +dependencies = [ + "bitflags", + "cfg-if 1.0.0", + "foreign-types", + "libc", + "once_cell", + "openssl-sys", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e46109c383602735fa0a2e48dd2b7c892b048e1bf69e5c3b1d804b7d9c203cb" +dependencies = [ + "autocfg", + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "pkg-config" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" + +[[package]] +name = "proc-macro2" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" +dependencies = [ + "unicode-xid", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quote" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" +dependencies = [ + "aho-corasick", + "memchr 2.4.1", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" + +[[package]] +name = "ryu" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" + +[[package]] +name = "schannel" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f05ba609c234e60bee0d547fe94a4c7e9da733d1c962cf6e59efa4cd9c8bc75" +dependencies = [ + "lazy_static", + "winapi", +] + +[[package]] +name = "serde" +version = "1.0.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "socket2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "syn" +version = "1.0.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "systemd" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b62a732355787f960c25536210ae0a981aca2e5dae9dab8491bdae39613ce48" +dependencies = [ + "cstr-argument", + "libc", + "libsystemd-sys", + "log", + "utf8-cstr", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "time" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd" +dependencies = [ + "itoa", + "libc", + "num_threads", + "serde", + "time-macros", +] + +[[package]] +name = "time-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42657b1a6f4d817cda8e7a0ace261fe0cc946cf3a80314390b22cc61ae080792" + +[[package]] +name = "unicode-xid" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" + +[[package]] +name = "utf8-cstr" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55bcbb425141152b10d5693095950b51c3745d019363fc2929ffd8f61449b628" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/ops/journaldriver/Cargo.toml b/ops/journaldriver/Cargo.toml new file mode 100644 index 000000000000..4c32b893f77d --- /dev/null +++ b/ops/journaldriver/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "journaldriver" +version = "1.1.0" +authors = ["Vincent Ambo <mail@tazj.in>"] +license = "GPL-3.0-or-later" +edition = "2021" + +[dependencies] +anyhow = "1.0" +crimp = "0.2" +env_logger = "0.5" +lazy_static = "1.0" +log = "0.4" +medallion = "2.5" +serde = "1.0" +serde_derive = "1.0" +serde_json = "1.0" +systemd = "0.3" +time = { version = "0.3", features = [ "serde-well-known", "macros" ]} + +[build-dependencies] +pkg-config = "0.3" diff --git a/ops/journaldriver/README.md b/ops/journaldriver/README.md new file mode 100644 index 000000000000..4dc9de0f617b --- /dev/null +++ b/ops/journaldriver/README.md @@ -0,0 +1,152 @@ +journaldriver +============= + +This is a small daemon used to forward logs from `journald` (systemd's +logging service) to [Stackdriver Logging][]. + +Many existing log services are written in inefficient dynamic +languages with error-prone "cover every possible use-case" +configuration. `journaldriver` instead aims to fit a specific use-case +very well, instead of covering every possible logging setup. + +`journaldriver` can be run on GCP-instances with no additional +configuration as authentication tokens are retrieved from the +[metadata server][]. + +<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc --> +**Table of Contents** + +- [Features](#features) +- [Usage on Google Cloud Platform](#usage-on-google-cloud-platform) +- [Usage outside of Google Cloud Platform](#usage-outside-of-google-cloud-platform) +- [Log levels / severities / priorities](#log-levels--severities--priorities) +- [NixOS module](#nixos-module) +- [Stackdriver Error Reporting](#stackdriver-error-reporting) + +<!-- markdown-toc end --> + +# Features + +* `journaldriver` persists the last forwarded position in the journal + and will resume forwarding at the same position after a restart +* `journaldriver` will recognise log entries in JSON format and + forward them appropriately to make structured log entries available + in Stackdriver +* `journaldriver` can be used outside of GCP by configuring static + credentials +* `journaldriver` will recognise journald's log priority levels and + convert them into equivalent Stackdriver log severity levels + +# Usage on Google Cloud Platform + +`journaldriver` does not require any configuration when running on GCP +instances. + +1. Install `journaldriver` on the instance from which you wish to + forward logs. + +2. Ensure that the instance has the appropriate permissions to write + to Stackdriver. Google continously changes how IAM is implemented + on GCP, so you will have to refer to [Google's documentation][]. + + By default instances have the required permissions if Stackdriver + Logging support is enabled in the project. + +3. Start `journaldriver`, for example via `systemd`. + +# Usage outside of Google Cloud Platform + +When running outside of GCP, the following extra steps need to be +performed: + +1. Create a Google Cloud Platform service account with the "Log + Writer" role and download its private key in JSON-format. +2. When starting `journaldriver`, configure the following environment + variables: + + * `GOOGLE_CLOUD_PROJECT`: Name of the GCP project to which logs + should be written. + * `GOOGLE_APPLICATION_CREDENTIALS`: Filesystem path to the + JSON-file containing the service account's private key. + * `LOG_STREAM`: Name of the target log stream in Stackdriver Logging. + This will be automatically created if it does not yet exist. + * `LOG_NAME`: Name of the target log to write to. This defaults to + `journaldriver` if unset, but it is recommended to - for + example - set it to the machine hostname. + +# Log levels / severities / priorities + +`journaldriver` recognises [journald's priorities][] and converts them +into [equivalent severities][] in Stackdriver. Both sets of values +correspond to standard `syslog` priorities. + +The easiest way to emit log messages with priorites from an +application is to use [priority prefixes][], which are compatible with +structured log messages. + +For example, to emit a simple warning message (structured and +unstructured): + +``` +$ echo '<4>{"fnord":true, "msg":"structured log (warning)"}' | systemd-cat +$ echo '<4>unstructured log (warning)' | systemd-cat +``` + +# NixOS module + +The NixOS package repository [contains a module][] for setting up +`journaldriver` on NixOS machines. NixOS by default uses `systemd` for +service management and `journald` for logging, which means that log +output from most services will be captured automatically. + +On a GCP instance the only required option is this: + +```nix +services.journaldriver.enable = true; +``` + +When running outside of GCP, the configuration looks as follows: + +```nix +services.journaldriver = { + enable = true; + logStream = "prod-environment"; + logName = "hostname"; + googleCloudProject = "gcp-project-name"; + applicationCredentials = keyFile; +}; +``` + +**Note**: The `journaldriver`-module is included in stable releases of +NixOS since NixOS 18.09. + +# Stackdriver Error Reporting + +The [Stackdriver Error Reporting][] service of Google's monitoring +toolbox supports automatically detecting and correlating errors from +log entries. + +To use this functionality log messages must be logged in the expected +[log format][]. + +*Note*: Reporting errors from non-GCP instances requires that the +`LOG_STREAM` environment variable is set to the special value +`global`. + +This value changes the monitored resource descriptor from a log stream +to the project-global stream. Due to a limitation in Stackdriver Error +Reporting, this is the only way to correctly ingest errors from +non-GCP machines. Please see [issue #4][] for more information about +this. + +[Stackdriver Logging]: https://cloud.google.com/logging/ +[metadata server]: https://cloud.google.com/compute/docs/storing-retrieving-metadata +[Google's documentation]: https://cloud.google.com/logging/docs/access-control +[NixOS]: https://nixos.org/ +[contains a module]: https://github.com/NixOS/nixpkgs/pull/42134 +[journald's priorities]: http://0pointer.de/public/systemd-man/sd-daemon.html +[equivalent severities]: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity +[priority prefixes]: http://0pointer.de/public/systemd-man/sd-daemon.html +[Stackdriver Error Reporting]: https://cloud.google.com/error-reporting/ +[log format]: https://cloud.google.com/error-reporting/docs/formatting-error-messages +[issue #4]: https://github.com/tazjin/journaldriver/issues/4 diff --git a/ops/journaldriver/build.rs b/ops/journaldriver/build.rs new file mode 100644 index 000000000000..79eb1001bf09 --- /dev/null +++ b/ops/journaldriver/build.rs @@ -0,0 +1,5 @@ +extern crate pkg_config; + +fn main() { + pkg_config::probe_library("libsystemd").expect("Could not probe libsystemd"); +} diff --git a/ops/journaldriver/default.nix b/ops/journaldriver/default.nix new file mode 100644 index 000000000000..a06a858fa12a --- /dev/null +++ b/ops/journaldriver/default.nix @@ -0,0 +1,11 @@ +{ depot, pkgs, ... }: + +depot.third_party.naersk.buildPackage { + src = ./.; + + buildInputs = with pkgs; [ + pkgconfig + openssl + systemd.dev + ]; +} diff --git a/ops/journaldriver/src/main.rs b/ops/journaldriver/src/main.rs new file mode 100644 index 000000000000..4c404e607e5b --- /dev/null +++ b/ops/journaldriver/src/main.rs @@ -0,0 +1,638 @@ +// Copyright (C) 2018 Vincent Ambo <mail@tazj.in> +// +// journaldriver is free software: you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see <http://www.gnu.org/licenses/>. + +//! This file implements journaldriver, a small application that +//! forwards logs from journald (systemd's log facility) to +//! Stackdriver Logging. +//! +//! Log entries are read continously from journald and are forwarded +//! to Stackdriver in batches. +//! +//! Stackdriver Logging has a concept of monitored resources. In the +//! simplest case this monitored resource will be the GCE instance on +//! which journaldriver is running. +//! +//! Information about the instance, the project and required security +//! credentials are retrieved from Google's metadata instance on GCP. +//! +//! To run journaldriver on non-GCP machines, users must specify the +//! `GOOGLE_APPLICATION_CREDENTIALS`, `GOOGLE_CLOUD_PROJECT` and +//! `LOG_NAME` environment variables. + +use anyhow::{bail, Context, Result}; +use lazy_static::lazy_static; +use log::{debug, error, info, trace}; +use serde::{Deserialize, Serialize}; +use serde_json::{from_str, json, Value}; +use std::convert::TryInto; +use std::fs::{self, rename, File}; +use std::io::{self, ErrorKind, Read, Write}; +use std::path::PathBuf; +use std::time::{Duration, Instant}; +use std::{env, mem, process}; +use systemd::journal::{Journal, JournalFiles, JournalRecord, JournalSeek}; + +#[cfg(test)] +mod tests; + +const LOGGING_SERVICE: &str = "https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"; +const ENTRIES_WRITE_URL: &str = "https://logging.googleapis.com/v2/entries:write"; +const METADATA_TOKEN_URL: &str = + "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"; +const METADATA_ID_URL: &str = "http://metadata.google.internal/computeMetadata/v1/instance/id"; +const METADATA_ZONE_URL: &str = "http://metadata.google.internal/computeMetadata/v1/instance/zone"; +const METADATA_PROJECT_URL: &str = + "http://metadata.google.internal/computeMetadata/v1/project/project-id"; + +/// Representation of static service account credentials for GCP. +#[derive(Debug, Deserialize)] +struct Credentials { + /// PEM encoded private key + private_key: String, + + /// `kid` of this private key + private_key_id: String, + + /// "email" address of the service account + client_email: String, +} + +lazy_static! { + /// ID of the GCP project to which to send logs. + static ref PROJECT_ID: String = get_project_id(); + + /// Name of the log to write to (this should only be manually + /// configured if not running on GCP): + static ref LOG_NAME: String = env::var("LOG_NAME") + .unwrap_or("journaldriver".into()); + + /// Service account credentials (if configured) + static ref SERVICE_ACCOUNT_CREDENTIALS: Option<Credentials> = + env::var("GOOGLE_APPLICATION_CREDENTIALS").ok() + .and_then(|path| File::open(path).ok()) + .and_then(|file| serde_json::from_reader(file).ok()); + + /// Descriptor of the currently monitored instance. Refer to the + /// documentation of `determine_monitored_resource` for more + /// information. + static ref MONITORED_RESOURCE: Value = determine_monitored_resource(); + + /// Path to the directory in which journaldriver should persist + /// its cursor state. + static ref CURSOR_DIR: PathBuf = env::var("CURSOR_POSITION_DIR") + .unwrap_or("/var/lib/journaldriver".into()) + .into(); + + /// Path to the cursor position file itself. + static ref CURSOR_FILE: PathBuf = { + let mut path = CURSOR_DIR.clone(); + path.push("cursor.pos"); + path + }; + + /// Path to the temporary file used for cursor position writes. + static ref CURSOR_TMP_FILE: PathBuf = { + let mut path = CURSOR_DIR.clone(); + path.push("cursor.tmp"); + path + }; +} + +/// Convenience helper for retrieving values from the metadata server. +fn get_metadata(url: &str) -> Result<String> { + let response = crimp::Request::get(url) + .header("Metadata-Flavor", "Google")? + .timeout(std::time::Duration::from_secs(5))? + .send()? + .as_string()?; + + if !response.is_success() { + bail!( + "Error response ({}) from metadata server: {}", + response.status, + response.body + ); + } + + Ok(response.body.trim().to_owned()) +} + +/// Convenience helper for determining the project ID. +fn get_project_id() -> String { + env::var("GOOGLE_CLOUD_PROJECT") + .or_else(|_| get_metadata(METADATA_PROJECT_URL)) + .expect("Could not determine project ID") +} + +/// Determines the monitored resource descriptor used in Stackdriver +/// logs. On GCP this will be set to the instance ID as returned by +/// the metadata server. +/// +/// On non-GCP machines the value is determined by using the +/// `GOOGLE_CLOUD_PROJECT` and `LOG_STREAM` environment variables. +/// +/// [issue #4]: https://github.com/tazjin/journaldriver/issues/4 +fn determine_monitored_resource() -> Value { + if let Ok(log) = env::var("LOG_STREAM") { + // The special value `global` is recognised as a log stream name that + // results in a `global`-type resource descriptor. This is useful in + // cases where Stackdriver Error Reporting is intended to be used on + // a non-GCE instance. See [issue #4][] for details. + if log == "global" { + return json!({ + "type": "global", + "labels": { + "project_id": PROJECT_ID.as_str(), + } + }); + } + + json!({ + "type": "logging_log", + "labels": { + "project_id": PROJECT_ID.as_str(), + "name": log, + } + }) + } else { + let instance_id = get_metadata(METADATA_ID_URL).expect("Could not determine instance ID"); + + let zone = get_metadata(METADATA_ZONE_URL).expect("Could not determine instance zone"); + + json!({ + "type": "gce_instance", + "labels": { + "project_id": PROJECT_ID.as_str(), + "instance_id": instance_id, + "zone": zone, + } + }) + } +} + +/// Represents the response returned by the metadata server's token +/// endpoint. The token is normally valid for an hour. +#[derive(Deserialize)] +struct TokenResponse { + expires_in: u64, + access_token: String, +} + +/// Struct used to store a token together with a sensible +/// representation of when it expires. +struct Token { + token: String, + fetched_at: Instant, + expires: Duration, +} + +impl Token { + /// Does this token need to be renewed? + fn is_expired(&self) -> bool { + self.fetched_at.elapsed() > self.expires + } +} + +/// Retrieves a token from the GCP metadata service. Retrieving these +/// tokens requires no additional authentication. +fn get_metadata_token() -> Result<Token> { + let body = get_metadata(METADATA_TOKEN_URL)?; + let token: TokenResponse = from_str(&body)?; + + debug!("Fetched new token from metadata service"); + + Ok(Token { + fetched_at: Instant::now(), + expires: Duration::from_secs(token.expires_in / 2), + token: token.access_token, + }) +} + +/// Signs a token using static client credentials configured for a +/// service account. This service account must have been given the +/// `Log Writer` role in Google Cloud IAM. +/// +/// The process for creating and signing these tokens is described +/// here: +/// +/// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth +fn sign_service_account_token(credentials: &Credentials) -> Result<Token> { + use medallion::{Algorithm, Header, Payload}; + + let iat = time::OffsetDateTime::now_utc(); + let exp = iat + time::Duration::seconds(3600); + + let header = Header { + alg: Algorithm::RS256, + headers: Some(json!({ + "kid": credentials.private_key_id, + })), + }; + + let payload: Payload<()> = Payload { + iss: Some(credentials.client_email.clone()), + sub: Some(credentials.client_email.clone()), + aud: Some(LOGGING_SERVICE.to_string()), + iat: Some(iat.unix_timestamp().try_into().unwrap()), + exp: Some(exp.unix_timestamp().try_into().unwrap()), + ..Default::default() + }; + + let token = medallion::Token::new(header, payload) + .sign(credentials.private_key.as_bytes()) + .context("Signing service account token failed")?; + + debug!("Signed new service account token"); + + Ok(Token { + token, + fetched_at: Instant::now(), + expires: Duration::from_secs(3000), + }) +} + +/// Retrieve the authentication token either by using static client +/// credentials, or by talking to the metadata server. +/// +/// Which behaviour is used is controlled by the environment variable +/// `GOOGLE_APPLICATION_CREDENTIALS`, which should be configured to +/// point at a JSON private key file if service account authentication +/// is to be used. +fn get_token() -> Result<Token> { + if let Some(credentials) = SERVICE_ACCOUNT_CREDENTIALS.as_ref() { + sign_service_account_token(credentials) + } else { + get_metadata_token() + } +} + +/// This structure represents the different types of payloads +/// supported by journaldriver. +/// +/// Currently log entries can either contain plain text messages or +/// structured payloads in JSON-format. +#[derive(Debug, Serialize, PartialEq)] +#[serde(untagged)] +enum Payload { + TextPayload { + #[serde(rename = "textPayload")] + text_payload: String, + }, + JsonPayload { + #[serde(rename = "jsonPayload")] + json_payload: Value, + }, +} + +/// Attempt to parse a log message as JSON and return it as a +/// structured payload. If parsing fails, return the entry in plain +/// text format. +fn message_to_payload(message: Option<String>) -> Payload { + match message { + None => Payload::TextPayload { + text_payload: "empty log entry".into(), + }, + Some(text_payload) => { + // Attempt to deserialize the text payload as a generic + // JSON value. + if let Ok(json_payload) = serde_json::from_str::<Value>(&text_payload) { + // If JSON-parsing succeeded on the payload, check + // whether we parsed an object (Stackdriver does not + // expect other types of JSON payload) and return it + // in that case. + if json_payload.is_object() { + return Payload::JsonPayload { json_payload }; + } + } + + Payload::TextPayload { text_payload } + } + } +} + +/// Attempt to parse journald's microsecond timestamps into a UTC +/// timestamp. +/// +/// Parse errors are dismissed and returned as empty options: There +/// simply aren't any useful fallback mechanisms other than defaulting +/// to ingestion time for journaldriver's use-case. +fn parse_microseconds(input: String) -> Option<time::OffsetDateTime> { + if input.len() != 16 { + return None; + } + + let micros: i128 = input.parse().ok()?; + let nanos: i128 = micros * 1000; + + time::OffsetDateTime::from_unix_timestamp_nanos(nanos).ok() +} + +/// Converts a journald log message priority to a +/// Stackdriver-compatible severity number. +/// +/// Both Stackdriver and journald specify equivalent +/// severities/priorities. Conveniently, the names are the same. +/// Inconveniently, the numbers are not. +/// +/// For more information on the journald priorities, consult these +/// man-pages: +/// +/// * systemd.journal-fields(7) (section 'PRIORITY') +/// * sd-daemon(3) +/// * systemd.exec(5) (section 'SyslogLevelPrefix') +/// +/// Note that priorities can be logged by applications via the prefix +/// concept described in these man pages, without interfering with +/// structured JSON-payloads. +/// +/// For more information on the Stackdriver severity levels, please +/// consult Google's documentation: +/// +/// https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity +/// +/// Any unknown priority values result in no severity being set. +fn priority_to_severity(priority: String) -> Option<u32> { + match priority.as_ref() { + "0" => Some(800), // emerg + "1" => Some(700), // alert + "2" => Some(600), // crit + "3" => Some(500), // err + "4" => Some(400), // warning + "5" => Some(300), // notice + "6" => Some(200), // info + "7" => Some(100), // debug + _ => None, + } +} + +/// This structure represents a log entry in the format expected by +/// the Stackdriver API. +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct LogEntry { + labels: Value, + + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(with = "time::serde::rfc3339::option")] + timestamp: Option<time::OffsetDateTime>, + + #[serde(flatten)] + payload: Payload, + + // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity + #[serde(skip_serializing_if = "Option::is_none")] + severity: Option<u32>, +} + +impl From<JournalRecord> for LogEntry { + // Converts from the fields contained in a journald record to the + // representation required by Stackdriver Logging. + // + // The fields are documented in systemd.journal-fields(7). + fn from(mut record: JournalRecord) -> LogEntry { + // The message field is technically just a convention, but + // journald seems to default to it when ingesting unit + // output. + let payload = message_to_payload(record.remove("MESSAGE")); + + // Presumably this is always set, but who can be sure + // about anything in this world. + let hostname = record.remove("_HOSTNAME"); + + // The unit is seemingly missing on kernel entries, but + // present on all others. + let unit = record.remove("_SYSTEMD_UNIT"); + + // The source timestamp (if present) is specified in + // microseconds since epoch. + // + // If it is not present or can not be parsed, journaldriver + // will not send a timestamp for the log entry and it will + // default to the ingestion time. + let timestamp = record + .remove("_SOURCE_REALTIME_TIMESTAMP") + .and_then(parse_microseconds); + + // Journald uses syslogd's concept of priority. No idea if this is + // always present, but it's optional in the Stackdriver API, so we just + // omit it if we can't find or parse it. + let severity = record.remove("PRIORITY").and_then(priority_to_severity); + + LogEntry { + payload, + timestamp, + labels: json!({ + "host": hostname, + "unit": unit.unwrap_or_else(|| "syslog".into()), + }), + severity, + } + } +} + +/// Attempt to read from the journal. If no new entry is present, +/// await the next one up to the specified timeout. +fn receive_next_record(timeout: Duration, journal: &mut Journal) -> Result<Option<JournalRecord>> { + let next_record = journal.next_record()?; + if next_record.is_some() { + return Ok(next_record); + } + + Ok(journal.await_next_record(Some(timeout))?) +} + +/// This function starts a double-looped, blocking receiver. It will +/// buffer messages for half a second before flushing them to +/// Stackdriver. +fn receiver_loop(mut journal: Journal) -> Result<()> { + let mut token = get_token()?; + + let mut buf: Vec<LogEntry> = Vec::new(); + let iteration = Duration::from_millis(500); + + loop { + trace!("Beginning outer iteration"); + let now = Instant::now(); + + loop { + if now.elapsed() > iteration { + break; + } + + if let Ok(Some(entry)) = receive_next_record(iteration, &mut journal) { + trace!("Received a new entry"); + buf.push(entry.into()); + } + } + + if !buf.is_empty() { + let to_flush = mem::replace(&mut buf, Vec::new()); + flush(&mut token, to_flush, journal.cursor()?)?; + } + + trace!("Done outer iteration"); + } +} + +/// Writes the current cursor into `/var/journaldriver/cursor.pos`. To +/// avoid issues with journaldriver being terminated while the cursor +/// is still being written, this will first write the cursor into a +/// temporary file and then move it. +fn persist_cursor(cursor: String) -> Result<()> { + // This code exists to aid in tracking down if there are other + // causes of issue #2 than what has already been taken care of. + // + // One theory is that journald (or the Rust library to interface + // with it) may occasionally return empty cursor strings. If this + // is ever the case, we would like to know about it. + if cursor.is_empty() { + error!("Received empty journald cursor position, refusing to persist!"); + error!("Please report this message at https://github.com/tazjin/journaldriver/issues/2"); + return Ok(()); + } + + let mut file = File::create(&*CURSOR_TMP_FILE).context("Failed to create cursor file")?; + + write!(file, "{}", cursor).context("Failed to write cursor file")?; + + rename(&*CURSOR_TMP_FILE, &*CURSOR_FILE) + .context("Failed to move cursor file") + .map_err(Into::into) +} + +/// Flushes all drained records to Stackdriver. Any Stackdriver +/// message can at most contain 1000 log entries which means they are +/// chunked up here. +/// +/// In some cases large payloads seem to cause errors in Stackdriver - +/// the chunks are therefore made smaller here. +/// +/// If flushing is successful the last cursor position will be +/// persisted to disk. +fn flush(token: &mut Token, entries: Vec<LogEntry>, cursor: String) -> Result<()> { + if token.is_expired() { + debug!("Refreshing Google metadata access token"); + let new_token = get_token()?; + *token = new_token; + } + + for chunk in entries.chunks(750) { + let request = prepare_request(chunk); + if let Err(write_error) = write_entries(token, request) { + error!("Failed to write {} entries: {}", chunk.len(), write_error) + } else { + debug!("Wrote {} entries to Stackdriver", chunk.len()) + } + } + + persist_cursor(cursor) +} + +/// Convert a slice of log entries into the format expected by +/// Stackdriver. This format is documented here: +/// +/// https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write +fn prepare_request(entries: &[LogEntry]) -> Value { + json!({ + "logName": format!("projects/{}/logs/{}", PROJECT_ID.as_str(), LOG_NAME.as_str()), + "resource": &*MONITORED_RESOURCE, + "entries": entries, + "partialSuccess": true + }) +} + +/// Perform the log entry insertion in Stackdriver Logging. +fn write_entries(token: &Token, request: Value) -> Result<()> { + let response = crimp::Request::post(ENTRIES_WRITE_URL) + .json(&request)? + .header("Authorization", format!("Bearer {}", token.token).as_str())? + // The timeout values are set relatively high, not because of + // an expectation of Stackdriver being slow but just to + // eventually force an error in case of network troubles. + // Presumably no request in a functioning environment will + // ever hit these limits. + .timeout(std::time::Duration::from_secs(5))? + .send()?; + + if !response.is_success() { + let status = response.status; + let body = response + .as_string() + .map(|r| r.body) + .unwrap_or_else(|_| "no valid response body".to_owned()); + + bail!("Writing to Stackdriver failed({}): {}", status, body); + } + + Ok(()) +} + +/// Attempt to read the initial cursor position from the configured +/// file. If there is no initial cursor position set, read from the +/// tail of the log. +/// +/// The only "acceptable" error when reading the cursor position is +/// the cursor position file not existing, other errors are fatal +/// because they indicate a misconfiguration of journaldriver. +fn initial_cursor() -> Result<JournalSeek> { + let read_result: io::Result<String> = (|| { + let mut contents = String::new(); + let mut file = File::open(&*CURSOR_FILE)?; + file.read_to_string(&mut contents)?; + Ok(contents.trim().into()) + })(); + + match read_result { + Ok(cursor) => Ok(JournalSeek::Cursor { cursor }), + Err(ref err) if err.kind() == ErrorKind::NotFound => { + info!("No previous cursor position, reading from journal tail"); + Ok(JournalSeek::Tail) + } + Err(err) => (Err(err).context("Could not read cursor position"))?, + } +} + +fn main() { + env_logger::init(); + + // The directory in which cursor positions are persisted should + // have been created: + if !CURSOR_DIR.exists() { + error!("Cursor directory at '{:?}' does not exist", *CURSOR_DIR); + process::exit(1); + } + + let cursor_position_dir = CURSOR_FILE + .parent() + .expect("Invalid cursor position file path"); + + fs::create_dir_all(cursor_position_dir) + .expect("Could not create directory to store cursor position in"); + + let mut journal = + Journal::open(JournalFiles::All, false, true).expect("Failed to open systemd journal"); + + let seek_position = initial_cursor().expect("Failed to determine initial cursor position"); + + match journal.seek(seek_position) { + Ok(cursor) => info!("Opened journal at cursor '{}'", cursor), + Err(err) => { + error!("Failed to set initial journal position: {}", err); + process::exit(1) + } + } + + receiver_loop(journal).expect("log receiver encountered an unexpected error"); +} diff --git a/ops/journaldriver/src/tests.rs b/ops/journaldriver/src/tests.rs new file mode 100644 index 000000000000..6f5045d6a5cd --- /dev/null +++ b/ops/journaldriver/src/tests.rs @@ -0,0 +1,131 @@ +use super::*; +use serde_json::to_string; +use time::macros::datetime; + +#[test] +fn test_text_entry_serialization() { + let entry = LogEntry { + labels: Value::Null, + timestamp: None, + payload: Payload::TextPayload { + text_payload: "test entry".into(), + }, + severity: None, + }; + + let expected = "{\"labels\":null,\"textPayload\":\"test entry\"}"; + let result = to_string(&entry).expect("serialization failed"); + + assert_eq!( + expected, result, + "Plain text payload should serialize correctly" + ) +} + +#[test] +fn test_timestamped_entry_serialization() { + let entry = LogEntry { + labels: Value::Null, + timestamp: Some(datetime!(1952-10-07 12:00:00 UTC)), + payload: Payload::TextPayload { + text_payload: "test entry".into(), + }, + severity: None, + }; + + let expected = + "{\"labels\":null,\"timestamp\":\"1952-10-07T12:00:00Z\",\"textPayload\":\"test entry\"}"; + let result = to_string(&entry).expect("serialization failed"); + + assert_eq!( + expected, result, + "Plain text payload should serialize correctly" + ) +} + +#[test] +fn test_json_entry_serialization() { + let entry = LogEntry { + labels: Value::Null, + timestamp: None, + payload: Payload::JsonPayload { + json_payload: json!({ + "message": "JSON test" + }), + }, + severity: None, + }; + + let expected = "{\"labels\":null,\"jsonPayload\":{\"message\":\"JSON test\"}}"; + let result = to_string(&entry).expect("serialization failed"); + + assert_eq!(expected, result, "JSON payload should serialize correctly") +} + +#[test] +fn test_plain_text_payload() { + let message = "plain text payload".into(); + let payload = message_to_payload(Some(message)); + let expected = Payload::TextPayload { + text_payload: "plain text payload".into(), + }; + + assert_eq!( + expected, payload, + "Plain text payload should be detected correctly" + ); +} + +#[test] +fn test_empty_payload() { + let payload = message_to_payload(None); + let expected = Payload::TextPayload { + text_payload: "empty log entry".into(), + }; + + assert_eq!( + expected, payload, + "Empty payload should be handled correctly" + ); +} + +#[test] +fn test_json_payload() { + let message = "{\"someKey\":\"someValue\", \"otherKey\": 42}".into(); + let payload = message_to_payload(Some(message)); + let expected = Payload::JsonPayload { + json_payload: json!({ + "someKey": "someValue", + "otherKey": 42 + }), + }; + + assert_eq!( + expected, payload, + "JSON payload should be detected correctly" + ); +} + +#[test] +fn test_json_no_object() { + // This message can be parsed as valid JSON, but it is not an + // object - it should be returned as a plain-text payload. + let message = "42".into(); + let payload = message_to_payload(Some(message)); + let expected = Payload::TextPayload { + text_payload: "42".into(), + }; + + assert_eq!( + expected, payload, + "Non-object JSON payload should be plain text" + ); +} + +#[test] +fn test_parse_microseconds() { + let input: String = "1529175149291187".into(); + let expected: time::OffsetDateTime = datetime!(2018-06-16 18:52:29.291187 UTC); + + assert_eq!(Some(expected), parse_microseconds(input)); +} diff --git a/ops/keycloak/.gitignore b/ops/keycloak/.gitignore new file mode 100644 index 000000000000..017878c614d0 --- /dev/null +++ b/ops/keycloak/.gitignore @@ -0,0 +1,3 @@ +.terraform* +*.tfstate* +.envrc diff --git a/ops/keycloak/README.md b/ops/keycloak/README.md new file mode 100644 index 000000000000..e8ffd700b5e2 --- /dev/null +++ b/ops/keycloak/README.md @@ -0,0 +1,18 @@ +Terraform for Keycloak +====================== + +This contains the Terraform configuration for deploying TVL's Keycloak +instance (which lives at `auth.tvl.fyi`). + +Secrets are needed for applying this. The encrypted file +`//ops/secrets/tf-keycloak.age` contains `export` calls which should +be sourced, for example via `direnv`, by users with the appropriate +credentials. + +An example `direnv` configuration used by tazjin is this: + +``` +# //ops/secrets/.envrc +source_up +eval $(age --decrypt -i ~/.ssh/id_ed25519 $(git rev-parse --show-toplevel)/ops/secrets/tf-keycloak.age) +``` diff --git a/ops/keycloak/clients.tf b/ops/keycloak/clients.tf new file mode 100644 index 000000000000..5f2fd21a3557 --- /dev/null +++ b/ops/keycloak/clients.tf @@ -0,0 +1,92 @@ +# All Keycloak clients, that is applications which authenticate +# through Keycloak. +# +# Includes first-party (i.e. TVL-hosted) and third-party clients. + +resource "keycloak_openid_client" "grafana" { + realm_id = keycloak_realm.tvl.id + client_id = "grafana" + name = "Grafana" + enabled = true + access_type = "CONFIDENTIAL" + standard_flow_enabled = true + base_url = "https://status.tvl.su" + + valid_redirect_uris = [ + "https://status.tvl.su/*", + ] +} + +resource "keycloak_openid_client" "gerrit" { + realm_id = keycloak_realm.tvl.id + client_id = "gerrit" + name = "TVL Gerrit" + enabled = true + access_type = "CONFIDENTIAL" + standard_flow_enabled = true + base_url = "https://cl.tvl.fyi" + description = "TVL's code review tool" + direct_access_grants_enabled = true + exclude_session_state_from_auth_response = false + + valid_redirect_uris = [ + "https://cl.tvl.fyi/*", + ] + + web_origins = [ + "https://cl.tvl.fyi", + ] +} + +resource "keycloak_saml_client" "buildkite" { + realm_id = keycloak_realm.tvl.id + client_id = "https://buildkite.com" + name = "Buildkite" + base_url = "https://buildkite.com/sso/tvl" + + client_signature_required = false + assertion_consumer_post_url = "https://buildkite.com/sso/~/1531aca5-f49c-4151-8832-a451e758af4c/saml/consume" + + valid_redirect_uris = [ + "https://buildkite.com/sso/~/1531aca5-f49c-4151-8832-a451e758af4c/saml/consume" + ] +} + +resource "keycloak_saml_user_attribute_protocol_mapper" "buildkite_email" { + realm_id = keycloak_realm.tvl.id + client_id = keycloak_saml_client.buildkite.id + name = "buildkite-email-mapper" + user_attribute = "email" + saml_attribute_name = "email" + saml_attribute_name_format = "Unspecified" +} + +resource "keycloak_saml_user_attribute_protocol_mapper" "buildkite_name" { + realm_id = keycloak_realm.tvl.id + client_id = keycloak_saml_client.buildkite.id + name = "buildkite-name-mapper" + user_attribute = "displayName" + saml_attribute_name = "name" + saml_attribute_name_format = "Unspecified" +} + +resource "keycloak_openid_client" "oauth2_proxy" { + realm_id = keycloak_realm.tvl.id + client_id = "oauth2-proxy" + name = "TVL OAuth2 Proxy" + enabled = true + access_type = "CONFIDENTIAL" + standard_flow_enabled = true + + valid_redirect_uris = [ + "https://login.tvl.fyi/oauth2/callback", + "http://localhost:4774/oauth2/callback", + ] +} + +resource "keycloak_openid_audience_protocol_mapper" "oauth2_proxy_audience" { + realm_id = keycloak_realm.tvl.id + client_id = keycloak_openid_client.oauth2_proxy.id + name = "oauth2-proxy-audience" + included_custom_audience = keycloak_openid_client.oauth2_proxy.client_id +} diff --git a/ops/keycloak/default.nix b/ops/keycloak/default.nix new file mode 100644 index 000000000000..5757debd1a39 --- /dev/null +++ b/ops/keycloak/default.nix @@ -0,0 +1,8 @@ +{ depot, pkgs, ... }: + +depot.nix.readTree.drvTargets { + # Provide a Terraform wrapper with the right provider installed. + terraform = pkgs.terraform.withPlugins (p: [ + p.keycloak + ]); +} diff --git a/ops/keycloak/main.tf b/ops/keycloak/main.tf new file mode 100644 index 000000000000..819267ff96c5 --- /dev/null +++ b/ops/keycloak/main.tf @@ -0,0 +1,34 @@ +# Configure TVL Keycloak instance. +# +# TODO(tazjin): Configure GitHub/GitLab IDP + +terraform { + required_providers { + keycloak = { + source = "mrparkers/keycloak" + } + } + + backend "s3" { + endpoint = "https://objects.dc-sto1.glesys.net" + bucket = "tvl-state" + key = "terraform/tvl-keycloak" + region = "glesys" + + skip_credentials_validation = true + skip_region_validation = true + skip_metadata_api_check = true + } +} + +provider "keycloak" { + client_id = "terraform" + url = "https://auth.tvl.fyi" +} + +resource "keycloak_realm" "tvl" { + realm = "TVL" + enabled = true + display_name = "The Virus Lounge" + default_signature_algorithm = "RS256" +} diff --git a/ops/keycloak/user_sources.tf b/ops/keycloak/user_sources.tf new file mode 100644 index 000000000000..3fde6e07cc91 --- /dev/null +++ b/ops/keycloak/user_sources.tf @@ -0,0 +1,21 @@ +# All user sources, that is services from which Keycloak gets user +# information (either by accessing a system like LDAP or integration +# through protocols like OIDC). + +resource "keycloak_ldap_user_federation" "tvl_ldap" { + name = "tvl-ldap" + realm_id = keycloak_realm.tvl.id + enabled = true + connection_url = "ldap://localhost" + users_dn = "ou=users,dc=tvl,dc=fyi" + username_ldap_attribute = "cn" + uuid_ldap_attribute = "cn" + rdn_ldap_attribute = "cn" + full_sync_period = 86400 + trust_email = true + + user_object_classes = [ + "inetOrgPerson", + "organizationalPerson", + ] +} diff --git a/ops/kontemplate/.gitignore b/ops/kontemplate/.gitignore new file mode 100644 index 000000000000..53a04aab3a89 --- /dev/null +++ b/ops/kontemplate/.gitignore @@ -0,0 +1,2 @@ +.idea/ +release/ diff --git a/ops/kontemplate/LICENSE b/ops/kontemplate/LICENSE new file mode 100644 index 000000000000..94a9ed024d38 --- /dev/null +++ b/ops/kontemplate/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/ops/kontemplate/README.md b/ops/kontemplate/README.md new file mode 100644 index 000000000000..803a1c4f16fb --- /dev/null +++ b/ops/kontemplate/README.md @@ -0,0 +1,185 @@ +Kontemplate - A simple Kubernetes templater +=========================================== + +Kontemplate is a simple CLI tool that can take sets of Kubernetes resource files +with placeholders and insert values per environment. + +This tool was made because in many cases all I want in terms of Kubernetes +configuration is simple value interpolation per environment (i.e. Kubernetes +cluster), but with the same deployment files. + +In my experience this is often enough and more complex solutions such as +[Helm][] are not required. + +Check out a Kontemplate setup example and the feature list below! + +<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc --> +**Table of Contents** + +- [Kontemplate - A simple Kubernetes templater](#kontemplate---a-simple-kubernetes-templater) + - [Features](#features) + - [Example](#example) + - [Installation](#installation) + - [Homebrew](#homebrew) + - [Arch Linux](#arch-linux) + - [Building repeatably from source](#building-repeatably-from-source) + - [Building from source](#building-from-source) + - [Usage](#usage) + - [Contributing](#contributing) + +<!-- markdown-toc end --> + +## Features + +* [Simple, yet powerful templates](docs/templates.md) +* [Clean cluster configuration files](docs/cluster-config.md) +* [Resources organised as simple resource sets](docs/resource-sets.md) +* Integration with pass +* Integration with kubectl + +## Example + +Kontemplate lets you describe resources as you normally would in a simple folder structure: + +``` +. +├── prod-cluster.yaml +└── some-api + ├── deployment.yaml + └── service.yaml +``` + +This example has all resources belonging to `some-api` (no file naming conventions enforced at all!) in the `some-api` +folder and the configuration for the cluster `prod-cluster` in the corresponding file. + +Lets take a short look at `prod-cluster.yaml`: + +```yaml +--- +context: k8s.prod.mydomain.com +global: + globalVar: lizards +include: + - name: some-api + values: + version: 1.0-0e6884d + importantFeature: true + apiPort: 4567 +``` + +Those values are then templated into the resource files of `some-api`. That's it! + +You can also set up more complicated folder structures for organisation, for example: + +``` +. +├── api +│ ├── image-api +│ │ └── deployment.yaml +│ └── music-api +│ └── deployment.yaml +│ │ └── default.json +├── frontend +│ ├── main-app +│ │ ├── deployment.yaml +│ │ └── service.yaml +│ └── user-page +│ ├── deployment.yaml +│ └── service.yaml +├── prod-cluster.yaml +└── test-cluster.yaml +``` + +And selectively template or apply resources with a command such as +`kontemplate apply test-cluster.yaml --include api --include frontend/user-page` +to only update the `api` resource sets and the `frontend/user-page` resource set. + +## Installation + +It is recommended to install Kontemplate from the [Nix](https://nixos.org/) package set, +where it is available since NixOS 17.09 as `kontemplate`. + +If using Nix is not an option for you, several other methods of installation are +available: + +### Binary releases + +Signed binary releases are available on the [releases page][] for Linux, OS X, FreeBSD and +Windows. + +Releases are signed with the GPG key `DCF34CFAC1AC44B87E26333136EE34814F6D294A`. + +### Building from source + +You can clone Kontemplate either by cloning the full TVL +[depot][https://code.tvl.fyi] or by just cloning the kontemplate +subtree like so: + + git clone https://code.tvl.fyi/depot.git:/ops/kontemplate.git + +The `go` tooling can be used as normal with this cloned repository. In +a full clone of the depot, Nix can be used to build Kontemplate: + + nix-build -A ops.kontemplate + +## Usage + +You must have `kubectl` installed to use Kontemplate effectively. + +``` +usage: kontemplate [<flags>] <command> [<args> ...] + +simple Kubernetes resource templating + +Flags: + -h, --help Show context-sensitive help (also try --help-long and --help-man). + -i, --include=INCLUDE ... Resource sets to include explicitly + -e, --exclude=EXCLUDE ... Resource sets to exclude explicitly + +Commands: + help [<command>...] + Show help. + + template <file> + Template resource sets and print them + + apply [<flags>] <file> + Template resources and pass to 'kubectl apply' + + replace <file> + Template resources and pass to 'kubectl replace' + + delete <file> + Template resources and pass to 'kubectl delete' + + create <file> + Template resources and pass to 'kubectl create' + +``` + +Examples: + +``` +# Look at output for a specific resource set and check to see if it's correct ... +kontemplate template example/prod-cluster.yaml -i some-api + +# ... maybe do a dry-run to see what kubectl would do: +kontemplate apply example/prod-cluster.yaml --dry-run + +# And actually apply it if you like what you see: +kontemplate apply example/prod-cluster.yaml +``` + +Check out the feature list and the individual feature documentation above. Then you should be good to go! + +## Contributing + +Feel free to contribute pull requests, file bugs and open issues with feature suggestions! + +Kontemplate is licensed under the GPLv3, a copy of the license and its terms can be found +in the `LICENSE` file. + +Please follow the [code of conduct](CODE_OF_CONDUCT.md). + +[Helm]: https://helm.sh/ +[releases page]: https://github.com/tazjin/kontemplate/releases diff --git a/ops/kontemplate/build-release.sh b/ops/kontemplate/build-release.sh new file mode 100755 index 000000000000..e4258c53dd09 --- /dev/null +++ b/ops/kontemplate/build-release.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +set -ueo pipefail + +# Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +# +# This file is part of Kontemplate. +# +# Kontemplate is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +readonly GIT_HASH="$(git rev-parse --short HEAD)" +readonly LDFLAGS="-X main.gitHash=${GIT_HASH} -w -s" +readonly VERSION="1.8.0-${GIT_HASH}" + +function binary-name() { + local os="${1}" + local target="${2}" + if [ "${os}" = "windows" ]; then + echo -n "${target}/kontemplate.exe" + else + echo -n "${target}/kontemplate" + fi +} + +function build-for() { + local os="${1}" + local arch="${2}" + local target="release/${os}/${arch}" + local bin=$(binary-name "${os}" "${target}") + + echo "Building kontemplate for ${os}-${arch} in ${target}" + + mkdir -p "${target}" + + env GOOS="${os}" GOARCH="${arch}" go build \ + -ldflags "${LDFLAGS}" \ + -o "${bin}" \ + -tags netgo +} + +function sign-for() { + local os="${1}" + local arch="${2}" + local target="release/${os}/${arch}" + local bin=$(binary-name "${os}" "${target}") + local tar="release/kontemplate-${VERSION}-${os}-${arch}.tar.gz" + + echo "Packing release into ${tar}" + tar czvf "${tar}" -C "${target}" $(basename "${bin}") + + local hash=$(sha256sum "${tar}") + echo "Signing kontemplate release tarball for ${os}-${arch} with SHA256 ${hash}" + gpg --armor --detach-sig --sign "${tar}" +} + +case "${1}" in + "build") + # Build releases for various operating systems: + build-for "linux" "amd64" + build-for "darwin" "amd64" + build-for "windows" "amd64" + build-for "freebsd" "amd64" + exit 0 + ;; + "sign") + # Bundle and sign releases: + sign-for "linux" "amd64" + sign-for "darwin" "amd64" + sign-for "windows" "amd64" + sign-for "freebsd" "amd64" + exit 0 + ;; +esac diff --git a/ops/kontemplate/context/context.go b/ops/kontemplate/context/context.go new file mode 100644 index 000000000000..2d0378a0ec23 --- /dev/null +++ b/ops/kontemplate/context/context.go @@ -0,0 +1,266 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +package context + +import ( + "fmt" + "path" + "strings" + + "github.com/tazjin/kontemplate/util" +) + +type ResourceSet struct { + // Name of the resource set. This can be used in include/exclude statements during kontemplate runs. + Name string `json:"name"` + + // Path to the folder containing the files for this resource set. This defaults to the value of the 'name' field + // if unset. + Path string `json:"path"` + + // Values to include when interpolating resources from this resource set. + Values map[string]interface{} `json:"values"` + + // Args to pass on to kubectl for this resource set. + Args []string `json:"args"` + + // Nested resource sets to include + Include []ResourceSet `json:"include"` + + // Parent resource set for flattened resource sets. Should not be manually specified. + Parent string +} + +type Context struct { + // The name of the kubectl context + Name string `json:"context"` + + // Global variables that should be accessible by all resource sets + Global map[string]interface{} `json:"global"` + + // File names of YAML or JSON files including extra variables that should be globally accessible + VariableImportFiles []string `json:"import"` + + // The resource sets to include in this context + ResourceSets []ResourceSet `json:"include"` + + // Variables imported from additional files + ImportedVars map[string]interface{} + + // Explicitly set variables (via `--var`) that should override all others + ExplicitVars map[string]interface{} + + // This field represents the absolute path to the context base directory and should not be manually specified. + BaseDir string +} + +func contextLoadingError(filename string, cause error) error { + return fmt.Errorf("Context loading failed on file %s due to: \n%v", filename, cause) +} + +// Attempt to load and deserialise a Context from the specified file. +func LoadContext(filename string, explicitVars *[]string) (*Context, error) { + var ctx Context + err := util.LoadData(filename, &ctx) + + if err != nil { + return nil, contextLoadingError(filename, err) + } + + ctx.BaseDir = path.Dir(filename) + + // Prepare the resource sets by resolving parents etc. + ctx.ResourceSets = flattenPrepareResourceSetPaths(&ctx.BaseDir, &ctx.ResourceSets) + + // Add variables explicitly specified on the command line + ctx.ExplicitVars, err = loadExplicitVars(explicitVars) + if err != nil { + return nil, fmt.Errorf("Error setting explicit variables: %v\n", err) + } + + // Add variables loaded from import files + ctx.ImportedVars, err = ctx.loadImportedVariables() + if err != nil { + return nil, contextLoadingError(filename, err) + } + + // Merge variables defined at different levels. The + // `mergeContextValues` function is documented with the merge + // hierarchy. + ctx.ResourceSets = ctx.mergeContextValues() + + if err != nil { + return nil, contextLoadingError(filename, err) + } + + return &ctx, nil +} + +// Kontemplate supports specifying additional variable files with the +// `import` keyword. This function loads those variable files and +// merges them together with the context's other global variables. +func (ctx *Context) loadImportedVariables() (map[string]interface{}, error) { + allImportedVars := make(map[string]interface{}) + + for _, file := range ctx.VariableImportFiles { + // Ensure that the filename is not merged with the baseDir if + // it is set to an absolute path. + var filePath string + if path.IsAbs(file) { + filePath = file + } else { + filePath = path.Join(ctx.BaseDir, file) + } + + var importedVars map[string]interface{} + err := util.LoadData(filePath, &importedVars) + + if err != nil { + return nil, err + } + + allImportedVars = *util.Merge(&allImportedVars, &importedVars) + } + + return allImportedVars, nil +} + +// Correctly prepares the file paths for resource sets by inferring implicit paths and flattening resource set +// collections, i.e. resource sets that themselves have an additional 'include' field set. +// Those will be regarded as a short-hand for including multiple resource sets from a subfolder. +// See https://github.com/tazjin/kontemplate/issues/9 for more information. +func flattenPrepareResourceSetPaths(baseDir *string, rs *[]ResourceSet) []ResourceSet { + flattened := make([]ResourceSet, 0) + + for _, r := range *rs { + // If a path is not explicitly specified it should default to the resource set name. + // This is also the classic behaviour prior to kontemplate 1.2 + if r.Path == "" { + r.Path = r.Name + } + + // Paths are made absolute by resolving them relative to the context base, + // unless absolute paths were specified. + if !path.IsAbs(r.Path) { + r.Path = path.Join(*baseDir, r.Path) + } + + if len(r.Include) == 0 { + flattened = append(flattened, r) + } else { + for _, subResourceSet := range r.Include { + if subResourceSet.Path == "" { + subResourceSet.Path = subResourceSet.Name + } + + subResourceSet.Parent = r.Name + subResourceSet.Name = path.Join(r.Name, subResourceSet.Name) + subResourceSet.Path = path.Join(r.Path, subResourceSet.Path) + subResourceSet.Values = *util.Merge(&r.Values, &subResourceSet.Values) + flattened = append(flattened, subResourceSet) + } + } + } + + return flattened +} + +// Merges the context and resource set variables according in the +// desired precedence order. +// +// For now the reasoning behind the merge order is from least specific +// in relation to the cluster configuration, which means that the +// precedence is (in ascending order): +// +// 1. Default values in resource sets. +// 2. Values imported from files (via `import:`) +// 3. Global values in a cluster configuration +// 4. Values set in a resource set's `include`-section +// 5. Explicit values set on the CLI (`--var`) +// +// For a discussion on the reasoning behind this order, please consult +// https://github.com/tazjin/kontemplate/issues/142 +func (ctx *Context) mergeContextValues() []ResourceSet { + updated := make([]ResourceSet, len(ctx.ResourceSets)) + + // Merging has to happen separately for every individual + // resource set to make use of the default values: + for i, rs := range ctx.ResourceSets { + // Begin by loading default values from the resource + // sets configuration. + // + // Resource sets are used across different cluster + // contexts and the default values in them have the + // lowest precedence. + defaultValues := loadDefaultValues(&rs, ctx) + + // Continue by merging default values with values + // imported from external files. Those values are also + // used across cluster contexts, but have higher + // precedence than defaults. + merged := util.Merge(defaultValues, &ctx.ImportedVars) + + // Merge global values defined in the cluster context: + merged = util.Merge(merged, &ctx.Global) + + // Merge values configured in the resource set's + // `include` section: + merged = util.Merge(merged, &rs.Values) + + // Merge values defined explicitly on the CLI: + merged = util.Merge(merged, &ctx.ExplicitVars) + + // Continue with the newly merged resource set: + rs.Values = *merged + updated[i] = rs + } + + return updated +} + +// Loads default values for a resource set collection from +// path/to/set/default.{json|yaml}. +func loadDefaultValues(rs *ResourceSet, c *Context) *map[string]interface{} { + var defaultVars map[string]interface{} + + for _, filename := range util.DefaultFilenames { + err := util.LoadData(path.Join(rs.Path, filename), &defaultVars) + if err == nil { + return &defaultVars + } + } + + // The actual error is not inspected here. The reasoning for + // this is that in case of serious problems (e.g. permission + // issues with the folder / folder not existing) failure will + // occur a bit later anyways. + // + // Otherwise we'd have to differentiate between + // file-not-found-errors (no default values specified) and + // other errors here. + return &rs.Values +} + +// Prepares the variables specified explicitly via `--var` when +// executing kontemplate for adding to the context. +func loadExplicitVars(vars *[]string) (map[string]interface{}, error) { + explicitVars := make(map[string]interface{}, len(*vars)) + + for _, v := range *vars { + varParts := strings.SplitN(v, "=", 2) + if len(varParts) != 2 { + return nil, fmt.Errorf(`invalid explicit variable provided (%s), name and value should be separated with "="`, v) + } + + explicitVars[varParts[0]] = varParts[1] + } + + return explicitVars, nil +} diff --git a/ops/kontemplate/context/context_test.go b/ops/kontemplate/context/context_test.go new file mode 100644 index 000000000000..471eb246cf2f --- /dev/null +++ b/ops/kontemplate/context/context_test.go @@ -0,0 +1,353 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +package context + +import ( + "reflect" + "testing" +) + +var noExplicitVars []string = make([]string, 0) + +func TestLoadFlatContextFromFile(t *testing.T) { + ctx, err := LoadContext("testdata/flat-test.yaml", &noExplicitVars) + + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + Global: map[string]interface{}{ + "globalVar": "lizards", + }, + ResourceSets: []ResourceSet{ + { + Name: "some-api", + Path: "testdata/some-api", + Values: map[string]interface{}{ + "apiPort": float64(4567), // yep! + "importantFeature": true, + "version": "1.0-0e6884d", + "globalVar": "lizards", + }, + Include: nil, + Parent: "", + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded context and expected context did not match") + t.Fail() + } +} + +func TestLoadContextWithArgs(t *testing.T) { + ctx, err := LoadContext("testdata/flat-with-args-test.yaml", &noExplicitVars) + + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + ResourceSets: []ResourceSet{ + { + Name: "some-api", + Path: "testdata/some-api", + Values: make(map[string]interface{}, 0), + Args: []string{ + "--as=some-user", + "--as-group=hello:world", + "--as-banana", + "true", + }, + Include: nil, + Parent: "", + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded context and expected context did not match") + t.Fail() + } +} + +func TestLoadContextWithResourceSetCollections(t *testing.T) { + ctx, err := LoadContext("testdata/collections-test.yaml", &noExplicitVars) + + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + Global: map[string]interface{}{ + "globalVar": "lizards", + }, + ResourceSets: []ResourceSet{ + { + Name: "some-api", + Path: "testdata/some-api", + Values: map[string]interface{}{ + "apiPort": float64(4567), // yep! + "importantFeature": true, + "version": "1.0-0e6884d", + "globalVar": "lizards", + }, + Include: nil, + Parent: "", + }, + { + Name: "collection/nested", + Path: "testdata/collection/nested", + Values: map[string]interface{}{ + "lizards": "good", + "globalVar": "lizards", + }, + Include: nil, + Parent: "collection", + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded context and expected context did not match") + t.Fail() + } + +} + +func TestSubresourceVariableInheritance(t *testing.T) { + ctx, err := LoadContext("testdata/parent-variables.yaml", &noExplicitVars) + + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + ResourceSets: []ResourceSet{ + { + Name: "parent/child", + Path: "testdata/parent/child", + Values: map[string]interface{}{ + "foo": "bar", + "bar": "baz", + }, + Include: nil, + Parent: "parent", + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded and expected context did not match") + t.Fail() + } +} + +func TestSubresourceVariableInheritanceOverride(t *testing.T) { + ctx, err := LoadContext("testdata/parent-variable-override.yaml", &noExplicitVars) + + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + ResourceSets: []ResourceSet{ + { + Name: "parent/child", + Path: "testdata/parent/child", + Values: map[string]interface{}{ + "foo": "newvalue", + }, + Include: nil, + Parent: "parent", + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded and expected context did not match") + t.Fail() + } +} + +func TestDefaultValuesLoading(t *testing.T) { + ctx, err := LoadContext("testdata/default-loading.yaml", &noExplicitVars) + if err != nil { + t.Error(err) + t.Fail() + } + + rs := ctx.ResourceSets[0] + if rs.Values["defaultValues"] != "loaded" { + t.Errorf("Default values not loaded from YAML file") + t.Fail() + } + + if rs.Values["override"] != "notAtAll" { + t.Error("Default values should not override other values") + t.Fail() + } +} + +func TestImportValuesLoading(t *testing.T) { + ctx, err := LoadContext("testdata/import-vars-simple.yaml", &noExplicitVars) + if err != nil { + t.Error(err) + t.Fail() + } + + expected := map[string]interface{}{ + "override": "true", + "music": map[string]interface{}{ + "artist": "Pallida", + "track": "Tractor Beam", + }, + } + + if !reflect.DeepEqual(ctx.ImportedVars, expected) { + t.Error("Expected imported values after loading imports did not match!") + t.Fail() + } +} + +func TestExplicitPathLoading(t *testing.T) { + ctx, err := LoadContext("testdata/explicit-path.yaml", &noExplicitVars) + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + ResourceSets: []ResourceSet{ + { + Name: "some-api-europe", + Path: "testdata/some-api", + Values: map[string]interface{}{ + "location": "europe", + }, + Include: nil, + Parent: "", + }, + { + Name: "some-api-asia", + Path: "testdata/some-api", + Values: map[string]interface{}{ + "location": "asia", + }, + Include: nil, + Parent: "", + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded context and expected context did not match") + t.Fail() + } +} + +func TestExplicitSubresourcePathLoading(t *testing.T) { + ctx, err := LoadContext("testdata/explicit-subresource-path.yaml", &noExplicitVars) + if err != nil { + t.Error(err) + t.Fail() + } + + expected := Context{ + Name: "k8s.prod.mydomain.com", + ResourceSets: []ResourceSet{ + { + Name: "parent/child", + Path: "testdata/parent-path/child-path", + Parent: "parent", + Values: make(map[string]interface{}, 0), + }, + }, + BaseDir: "testdata", + ImportedVars: make(map[string]interface{}, 0), + ExplicitVars: make(map[string]interface{}, 0), + } + + if !reflect.DeepEqual(*ctx, expected) { + t.Error("Loaded context and expected context did not match") + t.Fail() + } +} + +func TestSetVariablesFromArguments(t *testing.T) { + vars := []string{"version=some-service-version"} + ctx, _ := LoadContext("testdata/default-loading.yaml", &vars) + + if version := ctx.ExplicitVars["version"]; version != "some-service-version" { + t.Errorf(`Expected variable "version" to have value "some-service-version" but was "%s"`, version) + } +} + +func TestSetInvalidVariablesFromArguments(t *testing.T) { + vars := []string{"version: some-service-version"} + _, err := LoadContext("testdata/default-loading.yaml", &vars) + + if err == nil { + t.Error("Expected invalid variable to return an error") + } +} + +// This test ensures that variables are merged in the correct order. +// Please consult the test data in `testdata/merging`. +func TestValueMergePrecedence(t *testing.T) { + cliVars := []string{"cliVar=cliVar"} + ctx, _ := LoadContext("testdata/merging/context.yaml", &cliVars) + + expected := map[string]interface{}{ + "defaultVar": "defaultVar", + "importVar": "importVar", + "globalVar": "globalVar", + "includeVar": "includeVar", + "cliVar": "cliVar", + } + + result := ctx.ResourceSets[0].Values + + if !reflect.DeepEqual(expected, result) { + t.Errorf("Merged values did not match expected result: \n%v", result) + t.Fail() + } +} diff --git a/ops/kontemplate/context/testdata/collections-test.yaml b/ops/kontemplate/context/testdata/collections-test.yaml new file mode 100644 index 000000000000..a619c8cfddcc --- /dev/null +++ b/ops/kontemplate/context/testdata/collections-test.yaml @@ -0,0 +1,15 @@ +--- +context: k8s.prod.mydomain.com +global: + globalVar: lizards +include: + - name: some-api + values: + version: 1.0-0e6884d + importantFeature: true + apiPort: 4567 + - name: collection + include: + - name: nested + values: + lizards: good diff --git a/ops/kontemplate/context/testdata/default-loading.yaml b/ops/kontemplate/context/testdata/default-loading.yaml new file mode 100644 index 000000000000..d589c99b4eaf --- /dev/null +++ b/ops/kontemplate/context/testdata/default-loading.yaml @@ -0,0 +1,6 @@ +--- +context: default-loading +include: + - name: default + values: + override: notAtAll \ No newline at end of file diff --git a/ops/kontemplate/context/testdata/default/default.yaml b/ops/kontemplate/context/testdata/default/default.yaml new file mode 100644 index 000000000000..0ffa3cd81f24 --- /dev/null +++ b/ops/kontemplate/context/testdata/default/default.yaml @@ -0,0 +1,2 @@ +defaultValues: loaded +override: noop \ No newline at end of file diff --git a/ops/kontemplate/context/testdata/explicit-path.yaml b/ops/kontemplate/context/testdata/explicit-path.yaml new file mode 100644 index 000000000000..2c81f83c0919 --- /dev/null +++ b/ops/kontemplate/context/testdata/explicit-path.yaml @@ -0,0 +1,11 @@ +--- +context: k8s.prod.mydomain.com +include: + - name: some-api-europe + path: some-api + values: + location: europe + - name: some-api-asia + path: some-api + values: + location: asia diff --git a/ops/kontemplate/context/testdata/explicit-subresource-path.yaml b/ops/kontemplate/context/testdata/explicit-subresource-path.yaml new file mode 100644 index 000000000000..6cf86183229e --- /dev/null +++ b/ops/kontemplate/context/testdata/explicit-subresource-path.yaml @@ -0,0 +1,8 @@ +--- +context: k8s.prod.mydomain.com +include: + - name: parent + path: parent-path + include: + - name: child + path: child-path diff --git a/ops/kontemplate/context/testdata/flat-test.yaml b/ops/kontemplate/context/testdata/flat-test.yaml new file mode 100644 index 000000000000..dd7804f719c3 --- /dev/null +++ b/ops/kontemplate/context/testdata/flat-test.yaml @@ -0,0 +1,10 @@ +--- +context: k8s.prod.mydomain.com +global: + globalVar: lizards +include: + - name: some-api + values: + version: 1.0-0e6884d + importantFeature: true + apiPort: 4567 diff --git a/ops/kontemplate/context/testdata/flat-with-args-test.yaml b/ops/kontemplate/context/testdata/flat-with-args-test.yaml new file mode 100644 index 000000000000..29d3334fb54d --- /dev/null +++ b/ops/kontemplate/context/testdata/flat-with-args-test.yaml @@ -0,0 +1,9 @@ +--- +context: k8s.prod.mydomain.com +include: + - name: some-api + args: + - --as=some-user + - --as-group=hello:world + - --as-banana + - "true" diff --git a/ops/kontemplate/context/testdata/import-vars-simple.yaml b/ops/kontemplate/context/testdata/import-vars-simple.yaml new file mode 100644 index 000000000000..12244e1ab174 --- /dev/null +++ b/ops/kontemplate/context/testdata/import-vars-simple.yaml @@ -0,0 +1,5 @@ +--- +context: k8s.prod.mydomain.com +import: + - test-vars.yaml +include: [] diff --git a/ops/kontemplate/context/testdata/merging/context.yaml b/ops/kontemplate/context/testdata/merging/context.yaml new file mode 100644 index 000000000000..df30d3d8cbe3 --- /dev/null +++ b/ops/kontemplate/context/testdata/merging/context.yaml @@ -0,0 +1,15 @@ +# This context file is intended to test the merge hierarchy of +# variables defined at different levels. +--- +context: merging.in.kontemplate.works +global: + globalVar: globalVar + includeVar: should be overridden (global) + cliVar: should be overridden (global) +import: + - import-vars.yaml +include: + - name: resource + values: + includeVar: includeVar + cliVar: should be overridden (include) diff --git a/ops/kontemplate/context/testdata/merging/import-vars.yaml b/ops/kontemplate/context/testdata/merging/import-vars.yaml new file mode 100644 index 000000000000..2a51352571a6 --- /dev/null +++ b/ops/kontemplate/context/testdata/merging/import-vars.yaml @@ -0,0 +1,4 @@ +importVar: importVar +globalVar: should be overridden (import) +includeVar: should be overridden (import) +cliVar: should be overridden (import) diff --git a/ops/kontemplate/context/testdata/merging/resource/default.yaml b/ops/kontemplate/context/testdata/merging/resource/default.yaml new file mode 100644 index 000000000000..040a19aaba25 --- /dev/null +++ b/ops/kontemplate/context/testdata/merging/resource/default.yaml @@ -0,0 +1,5 @@ +defaultVar: defaultVar +importVar: should be overridden (default) +globalVar: should be overridden (default) +includeVar: should be overridden (default) +cliVar: should be overridden (default) diff --git a/ops/kontemplate/context/testdata/merging/resource/output.yaml b/ops/kontemplate/context/testdata/merging/resource/output.yaml new file mode 100644 index 000000000000..5920b2720780 --- /dev/null +++ b/ops/kontemplate/context/testdata/merging/resource/output.yaml @@ -0,0 +1,5 @@ +defaultVar: {{ .defaultVar }} +importVar: {{ .importVar }} +globalVar: {{ .globalVar }} +includeVar: {{ .includeVar }} +cliVar: {{ .cliVar }} diff --git a/ops/kontemplate/context/testdata/parent-variable-override.yaml b/ops/kontemplate/context/testdata/parent-variable-override.yaml new file mode 100644 index 000000000000..42676c3028fe --- /dev/null +++ b/ops/kontemplate/context/testdata/parent-variable-override.yaml @@ -0,0 +1,10 @@ +--- +context: k8s.prod.mydomain.com +include: + - name: parent + values: + foo: bar + include: + - name: child + values: + foo: newvalue diff --git a/ops/kontemplate/context/testdata/parent-variables.yaml b/ops/kontemplate/context/testdata/parent-variables.yaml new file mode 100644 index 000000000000..8459fd30405b --- /dev/null +++ b/ops/kontemplate/context/testdata/parent-variables.yaml @@ -0,0 +1,10 @@ +--- +context: k8s.prod.mydomain.com +include: + - name: parent + values: + foo: bar + include: + - name: child + values: + bar: baz diff --git a/ops/kontemplate/context/testdata/test-vars-override.yaml b/ops/kontemplate/context/testdata/test-vars-override.yaml new file mode 100644 index 000000000000..5215c559c136 --- /dev/null +++ b/ops/kontemplate/context/testdata/test-vars-override.yaml @@ -0,0 +1,3 @@ +--- +override: 3 +place: Oslo diff --git a/ops/kontemplate/context/testdata/test-vars.yaml b/ops/kontemplate/context/testdata/test-vars.yaml new file mode 100644 index 000000000000..af27bdc455bf --- /dev/null +++ b/ops/kontemplate/context/testdata/test-vars.yaml @@ -0,0 +1,5 @@ +--- +override: 'true' +music: + artist: Pallida + track: Tractor Beam diff --git a/ops/kontemplate/default.nix b/ops/kontemplate/default.nix new file mode 100644 index 000000000000..1190869c3fda --- /dev/null +++ b/ops/kontemplate/default.nix @@ -0,0 +1,36 @@ +# Copyright (C) 2016-2021 Vincent Ambo <mail@tazj.in> +# +# This file is part of Kontemplate. +# +# Kontemplate is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This file is the Nix derivation used to install Kontemplate on +# Nix-based systems. + +{ lib, pkgs, ... }: + +pkgs.buildGoPackage rec { + name = "kontemplate-${version}"; + version = "canon"; + src = ./.; + goPackagePath = "github.com/tazjin/kontemplate"; + goDeps = ./deps.nix; + buildInputs = [ pkgs.parallel ]; + + # Enable checks and configure check-phase to include vet: + doCheck = true; + preCheck = '' + for pkg in $(getGoDirs ""); do + buildGoDir vet "$pkg" + done + ''; + + meta = with lib; { + description = "A resource templating helper for Kubernetes"; + homepage = "http://kontemplate.works/"; + license = licenses.gpl3; + }; +} diff --git a/ops/kontemplate/deps.nix b/ops/kontemplate/deps.nix new file mode 100644 index 000000000000..7693968bd550 --- /dev/null +++ b/ops/kontemplate/deps.nix @@ -0,0 +1,111 @@ +# This file was generated by https://github.com/kamilchm/go2nix v1.3.0 +[ + { + goPackagePath = "github.com/Masterminds/goutils"; + fetch = { + type = "git"; + url = "https://github.com/Masterminds/goutils"; + rev = "41ac8693c5c10a92ea1ff5ac3a7f95646f6123b0"; + sha256 = "180px47gj936qyk5bkv5mbbgiil9abdjq6kwkf7sq70vyi9mcfiq"; + }; + } + { + goPackagePath = "github.com/Masterminds/semver"; + fetch = { + type = "git"; + url = "https://github.com/Masterminds/semver"; + rev = "5bc3b9184d48f1412b300b87a200cf020d9254cf"; + sha256 = "1vdfm653v50jf63cw0kg2hslx50cn4mk6lj3p51bi11jrg48kfng"; + }; + } + { + goPackagePath = "github.com/Masterminds/sprig"; + fetch = { + type = "git"; + url = "https://github.com/Masterminds/sprig"; + rev = "6f509977777c33eae63b2136d97f7b976cb971cc"; + sha256 = "05h9k6fhjxnpwlihj3z02q9kvqvnq53jix0ab84sx0666bci3cdh"; + }; + } + { + goPackagePath = "github.com/alecthomas/template"; + fetch = { + type = "git"; + url = "https://github.com/alecthomas/template"; + rev = "fb15b899a75114aa79cc930e33c46b577cc664b1"; + sha256 = "1vlasv4dgycydh5wx6jdcvz40zdv90zz1h7836z7lhsi2ymvii26"; + }; + } + { + goPackagePath = "github.com/alecthomas/units"; + fetch = { + type = "git"; + url = "https://github.com/alecthomas/units"; + rev = "c3de453c63f4bdb4dadffab9805ec00426c505f7"; + sha256 = "0js37zlgv37y61j4a2d46jh72xm5kxmpaiw0ya9v944bjpc386my"; + }; + } + { + goPackagePath = "github.com/ghodss/yaml"; + fetch = { + type = "git"; + url = "https://github.com/ghodss/yaml"; + rev = "25d852aebe32c875e9c044af3eef9c7dc6bc777f"; + sha256 = "1w9yq0bxzygc4qwkwwiy7k1k1yviaspcqqv18255k2xkjv5ipccz"; + }; + } + { + goPackagePath = "github.com/google/uuid"; + fetch = { + type = "git"; + url = "https://github.com/google/uuid"; + rev = "c2e93f3ae59f2904160ceaab466009f965df46d6"; + sha256 = "0zw8fvl6jqg0fmv6kmvhss0g4gkrbvgyvl2zgy5wdbdlgp4fja0h"; + }; + } + { + goPackagePath = "github.com/huandu/xstrings"; + fetch = { + type = "git"; + url = "https://github.com/huandu/xstrings"; + rev = "8bbcf2f9ccb55755e748b7644164cd4bdce94c1d"; + sha256 = "1ivvc95514z63k7cpz71l0dwlanffmsh1pijhaqmp41kfiby8rsx"; + }; + } + { + goPackagePath = "github.com/imdario/mergo"; + fetch = { + type = "git"; + url = "https://github.com/imdario/mergo"; + rev = "4c317f2286be3bd0c4f1a0e622edc6398ec4656d"; + sha256 = "0bihha1qsgfjk14yv1hwddv3d8dzxpbjlaxwwyys6lhgxz1cr9h9"; + }; + } + { + goPackagePath = "golang.org/x/crypto"; + fetch = { + type = "git"; + url = "https://go.googlesource.com/crypto"; + rev = "9756ffdc24725223350eb3266ffb92590d28f278"; + sha256 = "0q7hxaaq6lp0v8qqzifvysl47z5rfdlrxkh3d29vsl3wyby3dxl8"; + }; + } + { + goPackagePath = "gopkg.in/alecthomas/kingpin.v2"; + fetch = { + type = "git"; + url = "https://gopkg.in/alecthomas/kingpin.v2"; + rev = "947dcec5ba9c011838740e680966fd7087a71d0d"; + sha256 = "0mndnv3hdngr3bxp7yxfd47cas4prv98sqw534mx7vp38gd88n5r"; + }; + } + { + goPackagePath = "gopkg.in/yaml.v2"; + fetch = { + type = "git"; + url = "https://gopkg.in/yaml.v2"; + rev = "51d6538a90f86fe93ac480b35f37b2be17fef232"; + sha256 = "01wj12jzsdqlnidpyjssmj0r4yavlqy7dwrg7adqd8dicjc4ncsa"; + }; + } +] diff --git a/ops/kontemplate/docs/cluster-config.md b/ops/kontemplate/docs/cluster-config.md new file mode 100644 index 000000000000..4e870161796d --- /dev/null +++ b/ops/kontemplate/docs/cluster-config.md @@ -0,0 +1,106 @@ +Cluster configuration +========================== + +Every cluster (or "environment") that requires individual configuration is specified in +a very simple YAML file in Kontemplate. + +An example file for a hypothetical test environment could look like this: + +```yaml +--- +context: k8s.test.mydomain.com +global: + clusterName: test-cluster + defaultReplicas: 2 +import: + - test-secrets.yaml +include: + - name: gateway + path: tools/nginx + values: + tlsDomains: + - test.oslo.pub + - test.tazj.in + - path: backend + values: + env: test + include: + - name: blog + values: + url: test.tazj.in + - name: pub-service +``` + +<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc --> +**Table of Contents** + +- [Cluster configuration](#cluster-configuration) + - [Fields](#fields) + - [`context`](#context) + - [`global`](#global) + - [`import`](#import) + - [`include`](#include) + - [External variables](#external-variables) + +<!-- markdown-toc end --> + +## Fields + +This is documentation for the individual fields in a cluster context file. + +### `context` + +The `context` field contains the name of the kubectl-context. You can list context names with +'kubectl config get-contexts'. + +This must be set here so that Kontemplate can use the correct context when calling kubectl. + +This field is **required** for `kubectl`-wrapping commands. It can be left out if only the `template`-command is used. + +### `global` + +The `global` field contains a key/value map of variables that should be available to all resource +sets in the cluster. + +This field is **optional**. + +### `import` + +The `import` field contains the file names of additional YAML or JSON files from which global +variables should be loaded. Using this field makes it possible to keep certain configuration that +is the same for some, but not all, clusters in a common place. + +This field is **optional**. + +### `include` + +The `include` field contains the actual resource sets to be included in the cluster. + +Information about the structure of resource sets can be found in the [resource set documentation][]. + +This field is **required**. + +## External variables + +As mentioned above, extra variables can be loaded from additional YAML or JSON files. Assuming you +have a file called `test-secrets.yaml` which contains variables that should be shared between a `test` +and `dev` cluster, you could import it in your context as such: + +```yaml +# test-secrets.yaml: +mySecretVar: foo-bar-12345 + +# test-cluster.yaml: +context: k8s.test.mydomain.com +import: + - test-secrets.yaml + +# dev-cluster.yaml: +context: k8s.dev.mydomain.com +import: + - test-secrets.yaml +``` + +The variable `mySecretVar` is then available as a global variable. + +[resource set documentation]: resource-sets.md diff --git a/ops/kontemplate/docs/resource-sets.md b/ops/kontemplate/docs/resource-sets.md new file mode 100644 index 000000000000..1444dd491249 --- /dev/null +++ b/ops/kontemplate/docs/resource-sets.md @@ -0,0 +1,170 @@ +Resource Sets +================ + +Resource sets are collections of Kubernetes resources that should be passed to `kubectl` together. + +Technically a resource set is simply a folder with a few YAML and/or JSON templates in it. + +<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc --> +**Table of Contents** + +- [Resource Sets](#resource-sets) +- [Creating resource sets](#creating-resource-sets) + - [Default variables](#default-variables) +- [Including resource sets](#including-resource-sets) + - [Fields](#fields) + - [`name`](#name) + - [`path`](#path) + - [`values`](#values) + - [`args`](#args) + - [`include`](#include) + - [Multiple includes](#multiple-includes) + - [Nesting resource sets](#nesting-resource-sets) + - [Caveats](#caveats) + +<!-- markdown-toc end --> + +# Creating resource sets + +Simply create a folder in your Kontemplate repository and place a YAML or JSON file in it. These +files get interpreted as [templates][] during Kontemplate runs and variables (as well as template +logic or functions) will be interpolated. + +Refer to the template documentation for information on how to write templates. + +## Default variables + +Sometimes it is useful to specify default values for variables that should be interpolated during +a run if the [cluster configuration][] does not specify a variable explicitly. + +This can be done simply by placing a `default.yaml` or `default.json` file in the resource set +folder and filling it with key/value pairs of the intended default variables. + +Kontemplate will error during interpolation if any variables are left unspecified. + +# Including resource sets + +Under the cluster configuration `include` key resource sets are included and required variables +are specified. For example: + +```yaml +include: + - name: some-api + values: + version: 1.2-SNAPSHOT +``` + +This will include a resource set from a folder called `some-api` and set the specified `version` variable. + +## Fields + +The available fields when including a resource set are these: + +### `name` + +The `name` field contains the name of the resource set. This name can be used to refer to the resource set +when specifying explicit includes or excludes during a run. + +By default it is assumed that the `name` is the path to the resource set folder, but this can be overridden. + +This field is **required**. + +### `path` + +The `path` field specifies an explicit path to a resource set folder in the case that it should differ from +the resource set's `name`. + +This field is **optional**. + +### `values` + +The `values` field specifies key/values pairs of variables that should be available during templating. + +This field is **optional**. + +### `args` + +The `args` field specifies a list of arguments that should be passed to `kubectl`. + +This field is **optional**. + +### `include` + +The `include` field specifies additional resource sets that should be included and that should inherit the +variables of this resource set. + +The fully qualified names of "nested" resource sets are set to `${PARENT_NAME}/${CHILD_NAME}` and paths are +merged in the same way. + +This makes it easy to organise different resource sets as "groups" to include / exclude them collectively +during runs. + +This field is **optional**. + +## Multiple includes + +Resource sets can be included multiple times with different configurations. In this case it is recommended +to set the `path` and `name` fields explicitly. For example: + +```yaml +include: + - name: forwarder-europe + path: tools/forwarder + values: + source: europe + - name: forwarder-asia + path: tools/forwarder + values: + source: asia +``` + +The two different configurations can be referred to by their set names, but will use the same resource +templates with different configurations. + +## Nesting resource sets + +As mentioned above for the `include` field, resource sets can be nested. This lets users group resource +sets in logical ways using simple folder structures. + +Assuming a folder structure like: + +``` +├── backend +│ ├── auth-api +│ ├── message-api +│ └── order-api +└── frontend + ├── app-page + └── login-page +``` + +With each of these folders being a resource set, they could be included in a cluster configuration like so: + +```yaml +include: + - name: backend + include: + - name: auth-api + - name: message-api + - name: order-api + - name: frontend: + include: + - name: app-page + - name: login-page +``` + +Kontemplate could then be run with, for example, `--include backend` to only include the resource sets nested +in the backend group. Specific resource sets can also be targeted, for example as `--include backend/order-api`. + +Variables specified in the parent resource set are inherited by the children. + +### Caveats + +Two caveats apply that users should be aware of: + +1. The parent resource set can not contain any resource templates itself. + +2. Only one level of nesting is supported. Specifying `include` again on a nested resource set will be ignored. + +[templates]: templates.md +[cluster configuration]: cluster-config.md diff --git a/ops/kontemplate/docs/templates.md b/ops/kontemplate/docs/templates.md new file mode 100644 index 000000000000..32da205108de --- /dev/null +++ b/ops/kontemplate/docs/templates.md @@ -0,0 +1,153 @@ +Kontemplate templates +===================== + +The template file format is based on Go's [templating engine][] in combination +with a small extension library called [sprig][] that adds additional template +functions. + +Go templates can either simply display variables or build more complicated +*pipelines* in which variables are passed to functions for further processing, +or in which conditionals are evaluated for more complex template logic. + +It is recommended that you check out the Golang [documentation][] for the templating +engine in addition to the cherry-picked features listed here. + +<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc --> +**Table of Contents** + +- [Kontemplate templates](#kontemplate-templates) + - [Basic variable interpolation](#basic-variable-interpolation) + - [Example:](#example) + - [Template functions](#template-functions) + - [Examples:](#examples) + - [Conditionals & ranges](#conditionals--ranges) + - [Caveats](#caveats) + +<!-- markdown-toc end --> + +## Basic variable interpolation + +The basic template format uses `{{ .variableName }}` as the interpolation format. + +### Example: + +Assuming that you include a resource set as such: + +``` +- name: api-gateway + values: + internalHost: http://my-internal-host/ +``` + +And the api-gateway resource set includes a ConfigMap (some fields left out for +the example): + +``` +# api-gateway/configmap.yaml: +--- +kind: ConfigMap +metadata: + name: api-gateway-config +data: + internalHost: {{ .internalHost }} +``` + +The resulting output will be: + +``` + +--- +kind: ConfigMap +metadata: + name: api-gateway-config +data: + internalHost: http://my-internal-host/ +``` + +## Template functions + +Go templates support template functions which you can think of as a sort of +shell-like pipeline where text flows through transformations from left to +right. + +Some template functions come from Go's standard library and are listed in the +[Go documentation][]. In addition the functions declared by [sprig][] are +available in kontemplate, as well as five custom functions: + +* `json`: Encodes any supplied data structure as JSON. +* `gitHEAD`: Retrieves the commit hash at Git `HEAD`. +* `passLookup`: Looks up the supplied key in [pass][]. +* `insertFile`: Insert the contents of the given file in the resource + set folder as a string. +* `insertTemplate`: Insert the contents of the given template in the resource + set folder as a string. + +## Examples: + +``` +# With the following values: +name: Donald +certKeyPath: my-website/cert-key + +# The following interpolations are possible: + +{{ .name | upper }} +-> DONALD + +{{ .name | upper | repeat 2 }} +-> DONALD DONALD + +{{ .certKeyPath | passLookup }} +-> Returns content of 'my-website/cert-key' from pass + +{{ gitHEAD }} +-> Returns the Git commit hash at HEAD. +``` + +## Conditionals & ranges + +Some logic is supported in Golang templates and can be used in Kontemplate, too. + +With the following values: + +``` +useKube2IAM: true +servicePorts: + - 8080 + - 9090 +``` + +The following interpolations are possible: + +``` +# Conditionally insert something in the template: +metadata: + annotations: + foo: bar + {{ if .useKube2IAM -}} iam.amazonaws.com/role: my-api {{- end }} +``` + +``` +# Iterate over a list of values +ports: + {{ range .servicePorts }} + - port: {{ . }} + {{ end }} +``` + +Check out the Golang documentation (linked above) for more information about template logic. + +## Caveats + +Kontemplate does not by itself parse any of the content of the templates, which +means that it does not validate whether the resources you supply are valid YAML +or JSON. + +You can perform some validation by using `kontemplate apply --dry-run` which +will make use of the Dry-Run functionality in `kubectl`. + +[templating engine]: https://golang.org/pkg/text/template/ +[documentation]: https://golang.org/pkg/text/template/ +[sprig]: http://masterminds.github.io/sprig/ +[Go documentation]: https://golang.org/pkg/text/template/#hdr-Functions +[pass]: https://www.passwordstore.org/ diff --git a/ops/kontemplate/docs/tips-and-tricks.md b/ops/kontemplate/docs/tips-and-tricks.md new file mode 100644 index 000000000000..5401ac91e5a3 --- /dev/null +++ b/ops/kontemplate/docs/tips-and-tricks.md @@ -0,0 +1,77 @@ +Kontemplate tips & tricks +========================= + +<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc --> +**Table of Contents** + +- [Kontemplate tips & tricks](#kontemplate-tips--tricks) + - [Update Deployments when ConfigMaps change](#update-deployments-when-configmaps-change) + - [direnv & pass](#direnv--pass) + +<!-- markdown-toc end --> + +## Update Deployments when ConfigMaps change + +Kubernetes does [not currently][] have the ability to perform rolling updates +of Deployments and other resource types when `ConfigMap` or `Secret` objects +are updated. + +It is possible to make use of annotations and templating functions in +Kontemplate to force updates to these resources anyways. + +For example: + +```yaml +# A ConfigMap that contains some configuration for your app +--- +kind: ConfigMap +metadata: + name: app-config +data: + app.conf: | + name: {{ .appName }} + foo: bar +``` + +Now whenever the `appName` variable changes or we make an edit to the +`ConfigMap` we would like to update the `Deployment` making use of it, too. We +can do this by adding a hash of the parsed template to the annotations of the +created `Pod` objects: + +```yaml + +--- +kind: Deployment +metadata: + name: app +spec: + template: + metadata: + annotations: + configHash: {{ insertTemplate "app-config.yaml" | sha256sum }} + spec: + containers: + - name: app + # Some details omitted ... + volumeMounts: + - name: config + mountPath: /etc/app/ + volumes: + - name: config + configMap: + name: app-config +``` + +Now any change to the `ConfigMap` - either by directly editing the yaml file or +via a changed template variable - will cause the annotation to change, +triggering a rolling update of all relevant pods. + +## direnv & pass + +Users of `pass` may have multiple different password stores on their machines. +Assuming that `kontemplate` configuration exists somewhere on the filesystem +per project, it is easy to use [direnv][] to switch to the correct +`PASSWORD_STORE_DIR` variable when entering the folder. + +[not currently]: https://github.com/kubernetes/kubernetes/issues/22368 +[direnv]: https://direnv.net/ diff --git a/ops/kontemplate/example/other-config.yaml b/ops/kontemplate/example/other-config.yaml new file mode 100644 index 000000000000..87370569c46e --- /dev/null +++ b/ops/kontemplate/example/other-config.yaml @@ -0,0 +1,7 @@ +--- +apiVersion: extensions/v1beta1 +kind: ConfigMap +metadata: + name: other-config +data: + globalData: {{ .globalVar }} diff --git a/ops/kontemplate/example/prod-cluster.json b/ops/kontemplate/example/prod-cluster.json new file mode 100644 index 000000000000..70e2365f1710 --- /dev/null +++ b/ops/kontemplate/example/prod-cluster.json @@ -0,0 +1,16 @@ +{ + "context": "k8s.prod.mydomain.com", + "global": { + "globalVar": "lizards" + }, + "include": [ + { + "name": "some-api", + "values": { + "version": "1.0-SNAPSHOT-0e6884d", + "importantFeature": true, + "apiPort": 4567 + } + } + ] +} diff --git a/ops/kontemplate/example/prod-cluster.yaml b/ops/kontemplate/example/prod-cluster.yaml new file mode 100644 index 000000000000..9f300a492080 --- /dev/null +++ b/ops/kontemplate/example/prod-cluster.yaml @@ -0,0 +1,17 @@ +--- +context: k8s.prod.mydomain.com +global: + globalVar: lizards +include: + # By default resource sets are included from a folder with the same + # name as the resource set's name + - name: some-api + values: + version: 1.0-0e6884d + importantFeature: true + apiPort: 4567 + + # Paths can also be specified manually (and point at single template + # files!) + - name: other-config + path: other-config.yaml diff --git a/ops/kontemplate/example/some-api/some-api.yaml b/ops/kontemplate/example/some-api/some-api.yaml new file mode 100644 index 000000000000..f0188f9dbde3 --- /dev/null +++ b/ops/kontemplate/example/some-api/some-api.yaml @@ -0,0 +1,52 @@ +--- +apiVersion: v1 +kind: Secret +metadata: + name: secret-certificate +data: + cert.pem: {{ passLookup "my/secret/certificate" | b64enc }} +--- +apiVersion: extensions/v1beta1 +kind: ConfigMap +metadata: + name: some-config +data: + # The content of the example configuration file is templated in here + # by the 'insertFile' function and indented for YAML-compatibility + # with the 'indent' function: + some.cfg: | +{{ insertFile "some.cfg" | indent 4 }} +--- +apiVersion: extensions/v1beta1 +kind: Deployment +metadata: + name: some-api +spec: + replicas: 1 + template: + metadata: + labels: + app: some-api + spec: + containers: + - image: my.container.repo/some-api:{{ .version }} + name: some-api + env: + - name: ENABLE_IMPORTANT_FEATURE + value: {{ .importantFeature }} + - name: SOME_GLOBAL_VAR + value: {{ .globalVar }} +--- +apiVersion: v1 +kind: Service +metadata: + name: some-api + labels: + app: some-api +spec: + selector: + app: some-api + ports: + - port: 80 + targetPort: {{ .apiPort }} + name: http diff --git a/ops/kontemplate/example/some-api/some.cfg b/ops/kontemplate/example/some-api/some.cfg new file mode 100644 index 000000000000..733d5e16789a --- /dev/null +++ b/ops/kontemplate/example/some-api/some.cfg @@ -0,0 +1,4 @@ +{ + "something": 1542, + "other-thing": "да" +} diff --git a/ops/kontemplate/image/Dockerfile b/ops/kontemplate/image/Dockerfile new file mode 100644 index 000000000000..a40fa83b0867 --- /dev/null +++ b/ops/kontemplate/image/Dockerfile @@ -0,0 +1,15 @@ +FROM alpine:3.10 + +ADD hashes /root/hashes +ADD https://storage.googleapis.com/kubernetes-release/release/v1.15.3/bin/linux/amd64/kubectl /usr/bin/kubectl +ADD https://github.com/tazjin/kontemplate/releases/download/v1.8.0/kontemplate-1.8.0-6c3b299-linux-amd64.tar.gz /tmp/kontemplate.tar.gz + +# Pass release version is 1.7.3 +ADD https://raw.githubusercontent.com/zx2c4/password-store/74fdfb5022f317ad48d449e29543710bdad1afda/src/password-store.sh /usr/bin/pass + +RUN sha256sum -c /root/hashes && \ + apk add -U bash tree gnupg git && \ + chmod +x /usr/bin/kubectl /usr/bin/pass && \ + tar xzvf /tmp/kontemplate.tar.gz && \ + mv kontemplate /usr/bin/kontemplate && \ + /usr/bin/kontemplate version diff --git a/ops/kontemplate/image/README.md b/ops/kontemplate/image/README.md new file mode 100644 index 000000000000..fe04765401be --- /dev/null +++ b/ops/kontemplate/image/README.md @@ -0,0 +1,12 @@ +Kontemplate Docker image +======================== + +This builds a simple Docker image available on the Docker Hub as `tazjin/kontemplate`. + +Builds are automated based on the Dockerfile contained here. + +It contains both `kontemplate` and `kubectl` and can be used as part of container-based +CI pipelines. + +`pass` and its dependencies are also installed to enable the use of the `passLookup` +template function if desired. diff --git a/ops/kontemplate/image/hashes b/ops/kontemplate/image/hashes new file mode 100644 index 000000000000..bfd87c0201e7 --- /dev/null +++ b/ops/kontemplate/image/hashes @@ -0,0 +1,2 @@ +a39dfdd77e4655acaabe301285cf389cb5fc8145060f5677dc93db1cc20911a4 /tmp/kontemplate.tar.gz +6e805054a1fb2280abb53f75b57a1b92bf9c66ffe0d2cdcd46e81b079d93c322 /usr/bin/kubectl diff --git a/ops/kontemplate/main.go b/ops/kontemplate/main.go new file mode 100644 index 000000000000..e55d42465c6b --- /dev/null +++ b/ops/kontemplate/main.go @@ -0,0 +1,242 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see <http://www.gnu.org/licenses/>. + +package main + +import ( + "fmt" + "os" + "os/exec" + "strings" + + "github.com/tazjin/kontemplate/context" + "github.com/tazjin/kontemplate/templater" + "gopkg.in/alecthomas/kingpin.v2" +) + +const version string = "1.8.0" + +// This variable will be initialised by the Go linker during the builder +var gitHash string + +var ( + app = kingpin.New("kontemplate", "simple Kubernetes resource templating") + + // Global flags + includes = app.Flag("include", "Resource sets to include explicitly").Short('i').Strings() + excludes = app.Flag("exclude", "Resource sets to exclude explicitly").Short('e').Strings() + variables = app.Flag("var", "Provide variables to templates explicitly").Strings() + kubectlBin = app.Flag("kubectl", "Path to the kubectl binary (default 'kubectl')").Default("kubectl").String() + + // Commands + template = app.Command("template", "Template resource sets and print them") + templateFile = template.Arg("file", "Cluster configuration file to use").Required().String() + templateOutputDir = template.Flag("output", "Output directory in which to save templated files instead of printing them").Short('o').String() + + apply = app.Command("apply", "Template resources and pass to 'kubectl apply'") + applyFile = apply.Arg("file", "Cluster configuration file to use").Required().String() + applyDryRun = apply.Flag("dry-run", "Print remote operations without executing them").Default("false").Bool() + + replace = app.Command("replace", "Template resources and pass to 'kubectl replace'") + replaceFile = replace.Arg("file", "Cluster configuration file to use").Required().String() + + delete = app.Command("delete", "Template resources and pass to 'kubectl delete'") + deleteFile = delete.Arg("file", "Cluster configuration file to use").Required().String() + + create = app.Command("create", "Template resources and pass to 'kubectl create'") + createFile = create.Arg("file", "Cluster configuration file to use").Required().String() + + versionCmd = app.Command("version", "Show kontemplate version") +) + +func main() { + app.HelpFlag.Short('h') + + switch kingpin.MustParse(app.Parse(os.Args[1:])) { + case template.FullCommand(): + templateCommand() + + case apply.FullCommand(): + applyCommand() + + case replace.FullCommand(): + replaceCommand() + + case delete.FullCommand(): + deleteCommand() + + case create.FullCommand(): + createCommand() + + case versionCmd.FullCommand(): + versionCommand() + } +} + +func versionCommand() { + if gitHash == "" { + fmt.Printf("Kontemplate version %s (git commit unknown)\n", version) + } else { + fmt.Printf("Kontemplate version %s (git commit: %s)\n", version, gitHash) + } +} + +func templateCommand() { + _, resourceSets := loadContextAndResources(templateFile) + + for _, rs := range *resourceSets { + if len(rs.Resources) == 0 { + fmt.Fprintf(os.Stderr, "Warning: Resource set '%s' does not exist or contains no valid templates\n", rs.Name) + continue + } + + if *templateOutputDir != "" { + templateIntoDirectory(templateOutputDir, rs) + } else { + for _, r := range rs.Resources { + fmt.Fprintf(os.Stderr, "Rendered file %s/%s:\n", rs.Name, r.Filename) + fmt.Println(r.Rendered) + } + } + } +} + +func templateIntoDirectory(outputDir *string, rs templater.RenderedResourceSet) { + // Attempt to create the output directory if it does not + // already exist: + if err := os.MkdirAll(*templateOutputDir, 0775); err != nil { + app.Fatalf("Could not create output directory: %v\n", err) + } + + // Nested resource sets may contain slashes in their names. + // These are replaced with dashes for the purpose of writing a + // flat list of output files: + setName := strings.Replace(rs.Name, "/", "-", -1) + + for _, r := range rs.Resources { + filename := fmt.Sprintf("%s/%s-%s", *templateOutputDir, setName, r.Filename) + fmt.Fprintf(os.Stderr, "Writing file %s\n", filename) + + file, err := os.Create(filename) + if err != nil { + app.Fatalf("Could not create file %s: %v\n", filename, err) + } + + _, err = fmt.Fprintf(file, r.Rendered) + if err != nil { + app.Fatalf("Error writing file %s: %v\n", filename, err) + } + } +} + +func applyCommand() { + ctx, resources := loadContextAndResources(applyFile) + + var kubectlArgs []string + + if *applyDryRun { + kubectlArgs = []string{"apply", "-f", "-", "--dry-run"} + } else { + kubectlArgs = []string{"apply", "-f", "-"} + } + + if err := runKubectlWithResources(ctx, &kubectlArgs, resources); err != nil { + failWithKubectlError(err) + } +} + +func replaceCommand() { + ctx, resources := loadContextAndResources(replaceFile) + args := []string{"replace", "--save-config=true", "-f", "-"} + + if err := runKubectlWithResources(ctx, &args, resources); err != nil { + failWithKubectlError(err) + } +} + +func deleteCommand() { + ctx, resources := loadContextAndResources(deleteFile) + args := []string{"delete", "-f", "-"} + + if err := runKubectlWithResources(ctx, &args, resources); err != nil { + failWithKubectlError(err) + } +} + +func createCommand() { + ctx, resources := loadContextAndResources(createFile) + args := []string{"create", "--save-config=true", "-f", "-"} + + if err := runKubectlWithResources(ctx, &args, resources); err != nil { + failWithKubectlError(err) + } +} + +func loadContextAndResources(file *string) (*context.Context, *[]templater.RenderedResourceSet) { + ctx, err := context.LoadContext(*file, variables) + if err != nil { + app.Fatalf("Error loading context: %v\n", err) + } + + resources, err := templater.LoadAndApplyTemplates(includes, excludes, ctx) + if err != nil { + app.Fatalf("Error templating resource sets: %v\n", err) + } + + return ctx, &resources +} + +func runKubectlWithResources(c *context.Context, kubectlArgs *[]string, resourceSets *[]templater.RenderedResourceSet) error { + argsWithContext := append(*kubectlArgs, fmt.Sprintf("--context=%s", c.Name)) + + for _, rs := range *resourceSets { + if len(rs.Resources) == 0 { + fmt.Fprintf(os.Stderr, "Warning: Resource set '%s' contains no valid templates\n", rs.Name) + continue + } + + argsWithResourceSetArgs := append(argsWithContext, rs.Args...) + + kubectl := exec.Command(*kubectlBin, argsWithResourceSetArgs...) + + stdin, err := kubectl.StdinPipe() + if err != nil { + return fmt.Errorf("kubectl error: %v", err) + } + + kubectl.Stdout = os.Stdout + kubectl.Stderr = os.Stderr + + if err = kubectl.Start(); err != nil { + return fmt.Errorf("kubectl error: %v", err) + } + + for _, r := range rs.Resources { + fmt.Printf("Passing file %s/%s to kubectl\n", rs.Name, r.Filename) + fmt.Fprintln(stdin, r.Rendered) + } + stdin.Close() + + if err = kubectl.Wait(); err != nil { + return err + } + } + + return nil +} + +func failWithKubectlError(err error) { + app.Fatalf("Kubectl error: %v\n", err) +} diff --git a/ops/kontemplate/release.nix b/ops/kontemplate/release.nix new file mode 100644 index 000000000000..6a3dbd5efe87 --- /dev/null +++ b/ops/kontemplate/release.nix @@ -0,0 +1,58 @@ +# Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +# +# This file is part of Kontemplate. +# +# Kontemplate is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This file is the Nix derivation used to build release binaries for +# several different architectures and operating systems. + +let + pkgs = import + ((import <nixpkgs> { }).fetchFromGitHub { + owner = "NixOS"; + repo = "nixpkgs-channels"; + rev = "541d9cce8af7a490fb9085305939569567cb58e6"; + sha256 = "0jgz72hhzkd5vyq5v69vpljjlnf0lqaz7fh327bvb3cvmwbfxrja"; + }) + { }; +in +with pkgs; buildGoPackage rec { + name = "kontemplate-${version}"; + version = "canon"; + src = ./.; + goPackagePath = "github.com/tazjin/kontemplate"; + goDeps = ./deps.nix; + + # This configuration enables the building of statically linked + # executables. For some reason, those will have multiple references + # to the Go compiler's installation path in them, which is the + # reason for setting the 'allowGoReference' flag. + dontStrip = true; # Linker configuration handles stripping + allowGoReference = true; + CGO_ENABLED = "0"; + GOCACHE = "off"; + + # Configure release builds via the "build-matrix" script: + buildInputs = [ git ]; + buildPhase = '' + cd go/src/${goPackagePath} + patchShebangs build-release.sh + ./build-release.sh build + ''; + + outputs = [ "out" ]; + installPhase = '' + mkdir $out + cp -r release/ $out + ''; + + meta = with lib; { + description = "A resource templating helper for Kubernetes"; + homepage = "http://kontemplate.works/"; + license = licenses.gpl3; + }; +} diff --git a/ops/kontemplate/templater/dns.go b/ops/kontemplate/templater/dns.go new file mode 100644 index 000000000000..6cd974dd9324 --- /dev/null +++ b/ops/kontemplate/templater/dns.go @@ -0,0 +1,35 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This file contains the implementation of a template function for retrieving +// IP addresses from DNS + +package templater + +import ( + "fmt" + "net" + "os" +) + +func GetIPsFromDNS(host string) ([]interface{}, error) { + fmt.Fprintf(os.Stderr, "Attempting to look up IP for %s in DNS\n", host) + ips, err := net.LookupIP(host) + + if err != nil { + return nil, fmt.Errorf("IP address lookup failed: %v", err) + } + + var result []interface{} = make([]interface{}, len(ips)) + for i, ip := range ips { + result[i] = ip + } + + return result, nil +} diff --git a/ops/kontemplate/templater/pass.go b/ops/kontemplate/templater/pass.go new file mode 100644 index 000000000000..f7fbcb433de5 --- /dev/null +++ b/ops/kontemplate/templater/pass.go @@ -0,0 +1,34 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This file contains the implementation of a template function for retrieving +// variables from 'pass', the standard UNIX password manager. + +package templater + +import ( + "fmt" + "os" + "os/exec" + "strings" +) + +func GetFromPass(key string) (string, error) { + fmt.Fprintf(os.Stderr, "Attempting to look up %s in pass\n", key) + pass := exec.Command("pass", "show", key) + + output, err := pass.CombinedOutput() + if err != nil { + return "", fmt.Errorf("Pass lookup failed: %s (%v)", output, err) + } + + trimmed := strings.TrimSpace(string(output)) + + return trimmed, nil +} diff --git a/ops/kontemplate/templater/templater.go b/ops/kontemplate/templater/templater.go new file mode 100644 index 000000000000..a8f0c670a603 --- /dev/null +++ b/ops/kontemplate/templater/templater.go @@ -0,0 +1,236 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +package templater + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "os" + "os/exec" + "path" + "strings" + "text/template" + + "github.com/Masterminds/sprig" + "github.com/tazjin/kontemplate/context" + "github.com/tazjin/kontemplate/util" +) + +const failOnMissingKeys string = "missingkey=error" + +type RenderedResource struct { + Filename string + Rendered string +} + +type RenderedResourceSet struct { + Name string + Resources []RenderedResource + Args []string +} + +func LoadAndApplyTemplates(include *[]string, exclude *[]string, c *context.Context) ([]RenderedResourceSet, error) { + limitedResourceSets := applyLimits(&c.ResourceSets, include, exclude) + renderedResourceSets := make([]RenderedResourceSet, 0) + + if len(*limitedResourceSets) == 0 { + return renderedResourceSets, fmt.Errorf("No valid resource sets included!") + } + + for _, rs := range *limitedResourceSets { + set, err := processResourceSet(c, &rs) + + if err != nil { + return nil, err + } + + renderedResourceSets = append(renderedResourceSets, *set) + } + + return renderedResourceSets, nil +} + +func processResourceSet(ctx *context.Context, rs *context.ResourceSet) (*RenderedResourceSet, error) { + fmt.Fprintf(os.Stderr, "Loading resources for %s\n", rs.Name) + + fileInfo, err := os.Stat(rs.Path) + if err != nil { + return nil, err + } + + var files []os.FileInfo + var resources []RenderedResource + + // Treat single-file resource paths separately from resource + // sets containing multiple templates + if fileInfo.IsDir() { + // Explicitly discard this error, which will give us an empty + // list of files instead. + // This will end up printing a warning to the user, but it + // won't stop the rest of the process. + files, _ = ioutil.ReadDir(rs.Path) + resources, err = processFiles(ctx, rs, files) + if err != nil { + return nil, err + } + } else { + resource, err := templateFile(ctx, rs, rs.Path) + if err != nil { + return nil, err + } + + resources = []RenderedResource{resource} + } + + return &RenderedResourceSet{ + Name: rs.Name, + Resources: resources, + Args: rs.Args, + }, nil +} + +func processFiles(ctx *context.Context, rs *context.ResourceSet, files []os.FileInfo) ([]RenderedResource, error) { + resources := make([]RenderedResource, 0) + + for _, file := range files { + if !file.IsDir() && isResourceFile(file) { + path := path.Join(rs.Path, file.Name()) + res, err := templateFile(ctx, rs, path) + + if err != nil { + return resources, err + } + + resources = append(resources, res) + } + } + + return resources, nil +} + +func templateFile(ctx *context.Context, rs *context.ResourceSet, filepath string) (RenderedResource, error) { + var resource RenderedResource + + tpl, err := template.New(path.Base(filepath)).Funcs(templateFuncs(ctx, rs)).Option(failOnMissingKeys).ParseFiles(filepath) + if err != nil { + return resource, fmt.Errorf("Could not load template %s: %v", filepath, err) + } + + var b bytes.Buffer + err = tpl.Execute(&b, rs.Values) + if err != nil { + return resource, fmt.Errorf("Error while templating %s: %v", filepath, err) + } + + resource = RenderedResource{ + Filename: path.Base(filepath), + Rendered: b.String(), + } + + return resource, nil +} + +// Applies the limits of explicitly included or excluded resources and returns the updated resource set. +// Exclude takes priority over include +func applyLimits(rs *[]context.ResourceSet, include *[]string, exclude *[]string) *[]context.ResourceSet { + if len(*include) == 0 && len(*exclude) == 0 { + return rs + } + + // Exclude excluded resource sets + excluded := make([]context.ResourceSet, 0) + for _, r := range *rs { + if !matchesResourceSet(exclude, &r) { + excluded = append(excluded, r) + } + } + + // Include included resource sets + if len(*include) == 0 { + return &excluded + } + included := make([]context.ResourceSet, 0) + for _, r := range excluded { + if matchesResourceSet(include, &r) { + included = append(included, r) + } + } + + return &included +} + +// Check whether an include/exclude string slice matches a resource set +func matchesResourceSet(s *[]string, rs *context.ResourceSet) bool { + for _, r := range *s { + r = strings.TrimSuffix(r, "/") + if r == rs.Name || r == rs.Parent { + return true + } + } + + return false +} + +func templateFuncs(c *context.Context, rs *context.ResourceSet) template.FuncMap { + m := sprig.TxtFuncMap() + m["json"] = func(data interface{}) string { + b, _ := json.Marshal(data) + return string(b) + } + m["passLookup"] = GetFromPass + m["gitHEAD"] = func() (string, error) { + out, err := exec.Command("git", "-C", c.BaseDir, "rev-parse", "HEAD").Output() + if err != nil { + return "", err + } + output := strings.TrimSpace(string(out)) + return output, nil + } + m["lookupIPAddr"] = GetIPsFromDNS + m["insertFile"] = func(file string) (string, error) { + data, err := ioutil.ReadFile(path.Join(rs.Path, file)) + if err != nil { + return "", err + } + + return string(data), nil + } + m["insertTemplate"] = func(file string) (string, error) { + data, err := templateFile(c, rs, path.Join(rs.Path, file)) + if err != nil { + return "", err + } + + return data.Rendered, nil + } + m["default"] = func(defaultVal interface{}, varName string) interface{} { + if val, ok := rs.Values[varName]; ok { + return val + } + + return defaultVal + } + return m +} + +// Checks whether a file is a resource file (i.e. is YAML or JSON) and not a default values file. +func isResourceFile(f os.FileInfo) bool { + for _, defaultFile := range util.DefaultFilenames { + if f.Name() == defaultFile { + return false + } + } + + return strings.HasSuffix(f.Name(), "yaml") || + strings.HasSuffix(f.Name(), "yml") || + strings.HasSuffix(f.Name(), "json") +} diff --git a/ops/kontemplate/templater/templater_test.go b/ops/kontemplate/templater/templater_test.go new file mode 100644 index 000000000000..9d9fc8d1ffa7 --- /dev/null +++ b/ops/kontemplate/templater/templater_test.go @@ -0,0 +1,205 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +package templater + +import ( + "github.com/tazjin/kontemplate/context" + "reflect" + "strings" + "testing" +) + +func TestApplyNoLimits(t *testing.T) { + resources := []context.ResourceSet{ + { + Name: "testResourceSet1", + }, + { + Name: "testResourceSet2", + }, + } + + result := applyLimits(&resources, &[]string{}, &[]string{}) + + if !reflect.DeepEqual(resources, *result) { + t.Error("Resource set slice changed, but shouldn't have.") + t.Errorf("Expected: %v\nResult: %v\n", resources, *result) + t.Fail() + } +} + +func TestApplyIncludeLimits(t *testing.T) { + resources := []context.ResourceSet{ + { + Name: "testResourceSet1", + }, + { + Name: "testResourceSet2", + }, + { + Name: "testResourceSet3", + Parent: "included", + }, + } + + includes := []string{"testResourceSet1", "included"} + + result := applyLimits(&resources, &includes, &[]string{}) + + expected := []context.ResourceSet{ + { + Name: "testResourceSet1", + }, + { + Name: "testResourceSet3", + Parent: "included", + }, + } + + if !reflect.DeepEqual(expected, *result) { + t.Error("Result does not contain expected resource sets.") + t.Errorf("Expected: %v\nResult: %v\n", expected, *result) + t.Fail() + } +} + +func TestApplyExcludeLimits(t *testing.T) { + resources := []context.ResourceSet{ + { + Name: "testResourceSet1", + }, + { + Name: "testResourceSet2", + }, + { + Name: "testResourceSet3", + Parent: "included", + }, + } + + exclude := []string{"testResourceSet2"} + + result := applyLimits(&resources, &[]string{}, &exclude) + + expected := []context.ResourceSet{ + { + Name: "testResourceSet1", + }, + { + Name: "testResourceSet3", + Parent: "included", + }, + } + + if !reflect.DeepEqual(expected, *result) { + t.Error("Result does not contain expected resource sets.") + t.Errorf("Expected: %v\nResult: %v\n", expected, *result) + t.Fail() + } +} + +func TestApplyLimitsExcludeIncludePrecedence(t *testing.T) { + resources := []context.ResourceSet{ + { + Name: "collection/nested1", + Parent: "collection", + }, + { + Name: "collection/nested2", + Parent: "collection", + }, + { + Name: "collection/nested3", + Parent: "collection", + }, + { + Name: "something-else", + }, + } + + include := []string{"collection"} + exclude := []string{"collection/nested2"} + + result := applyLimits(&resources, &include, &exclude) + + expected := []context.ResourceSet{ + { + Name: "collection/nested1", + Parent: "collection", + }, + { + Name: "collection/nested3", + Parent: "collection", + }, + } + + if !reflect.DeepEqual(expected, *result) { + t.Error("Result does not contain expected resource sets.") + t.Errorf("Expected: %v\nResult: %v\n", expected, *result) + t.Fail() + } +} + +func TestFailOnMissingKeys(t *testing.T) { + ctx := context.Context{} + resourceSet := context.ResourceSet{} + + _, err := templateFile(&ctx, &resourceSet, "testdata/test-template.txt") + + if err == nil { + t.Errorf("Template with missing keys should have failed.\n") + t.Fail() + } + + if !strings.Contains(err.Error(), "map has no entry for key \"testName\"") { + t.Errorf("Templating failed with unexpected error: %v\n", err) + } +} + +func TestDefaultTemplateFunction(t *testing.T) { + ctx := context.Context{} + resourceSet := context.ResourceSet{} + + res, err := templateFile(&ctx, &resourceSet, "testdata/test-default.txt") + + if err != nil { + t.Errorf("Templating with default values should have succeeded.\n") + t.Fail() + } + + if res.Rendered != "defaultValue\n" { + t.Error("Result does not contain expected rendered default value.") + t.Fail() + } +} + +func TestInsertTemplateFunction(t *testing.T) { + ctx := context.Context{} + resourceSet := context.ResourceSet{ + Path: "testdata", + Values: map[string]interface{}{ + "testName": "TestInsertTemplateFunction", + }, + } + + res, err := templateFile(&ctx, &resourceSet, "testdata/test-insertTemplate.txt") + + if err != nil { + t.Error(err) + t.Errorf("Templating with an insertTemplate call should have succeeded.\n") + t.Fail() + } + + if res.Rendered != "Inserting \"Template for test TestInsertTemplateFunction\".\n" { + t.Error("Result does not contain expected rendered template value.") + t.Error(res.Rendered) + t.Fail() + } +} diff --git a/ops/kontemplate/templater/testdata/test-default.txt b/ops/kontemplate/templater/testdata/test-default.txt new file mode 100644 index 000000000000..4f7997bd69d2 --- /dev/null +++ b/ops/kontemplate/templater/testdata/test-default.txt @@ -0,0 +1 @@ +{{ default "defaultValue" "missingVar" }} diff --git a/ops/kontemplate/templater/testdata/test-insertTemplate.txt b/ops/kontemplate/templater/testdata/test-insertTemplate.txt new file mode 100644 index 000000000000..8155e174fe00 --- /dev/null +++ b/ops/kontemplate/templater/testdata/test-insertTemplate.txt @@ -0,0 +1 @@ +Inserting "{{ insertTemplate "test-template.txt" | trim }}". diff --git a/ops/kontemplate/templater/testdata/test-template.txt b/ops/kontemplate/templater/testdata/test-template.txt new file mode 100644 index 000000000000..06f1cfc630c3 --- /dev/null +++ b/ops/kontemplate/templater/testdata/test-template.txt @@ -0,0 +1 @@ +Template for test {{ .testName }} diff --git a/ops/kontemplate/util/util.go b/ops/kontemplate/util/util.go new file mode 100644 index 000000000000..56fa1e3fc9c5 --- /dev/null +++ b/ops/kontemplate/util/util.go @@ -0,0 +1,58 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +package util + +import ( + "io/ioutil" + + "github.com/ghodss/yaml" +) + +// Filenames excluded from templating for the purpose of containing default variable values inside a resource set. +var DefaultFilenames []string = []string{"default.yml", "default.yaml", "default.json"} + +// Merges two maps together. Values from the second map override values in the first map. +// The returned map is new if anything was changed. +func Merge(in1 *map[string]interface{}, in2 *map[string]interface{}) *map[string]interface{} { + if in1 == nil || len(*in1) == 0 { + return in2 + } + + if in2 == nil || len(*in2) == 0 { + return in1 + } + + new := make(map[string]interface{}) + for k, v := range *in1 { + new[k] = v + } + + for k, v := range *in2 { + new[k] = v + } + + return &new +} + +// Loads either a YAML or JSON file from the specified path and +// deserialises it into the provided interface. +func LoadData(filename string, addr interface{}) error { + file, err := ioutil.ReadFile(filename) + if err != nil { + return err + } + + err = yaml.Unmarshal(file, addr) + if err != nil { + return err + } + + return nil +} diff --git a/ops/kontemplate/util/util_test.go b/ops/kontemplate/util/util_test.go new file mode 100644 index 000000000000..53c56081758c --- /dev/null +++ b/ops/kontemplate/util/util_test.go @@ -0,0 +1,83 @@ +// Copyright (C) 2016-2019 Vincent Ambo <mail@tazj.in> +// +// This file is part of Kontemplate. +// +// Kontemplate is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +package util + +import ( + "reflect" + "testing" +) + +func TestMergeWithEmptyMap(t *testing.T) { + testMap := map[string]interface{}{ + "foo": "bar", + } + + empty := make(map[string]interface{}) + + res1 := Merge(&testMap, &empty) + res2 := Merge(&empty, &testMap) + + if res1 != &testMap || res2 != &testMap { + t.Error("A new map was returned incorrectly.") + t.Fail() + } +} + +func TestMergeWithNilMap(t *testing.T) { + testMap := map[string]interface{}{ + "foo": "bar", + } + + res1 := Merge(&testMap, nil) + res2 := Merge(nil, &testMap) + + if res1 != &testMap || res2 != &testMap { + t.Error("A new map was returned incorrectly.") + t.Fail() + } +} + +func TestMergeMaps(t *testing.T) { + map1 := map[string]interface{}{ + "foo": "bar", + } + + map2 := map[string]interface{}{ + "bar": "baz", + } + + result := Merge(&map1, &map2) + expected := map[string]interface{}{ + "foo": "bar", + "bar": "baz", + } + + if !reflect.DeepEqual(*result, expected) { + t.Error("Maps were merged incorrectly.") + t.Fail() + } +} + +func TestMergeMapsPrecedence(t *testing.T) { + map1 := map[string]interface{}{ + "foo": "incorrect", + } + + map2 := map[string]interface{}{ + "foo": "correct", + } + + result := Merge(&map1, &map2) + + if (*result)["foo"] != "correct" { + t.Error("Map merge precedence test failed.") + t.Fail() + } +} diff --git a/ops/machines/all-systems.nix b/ops/machines/all-systems.nix new file mode 100644 index 000000000000..9f77f0048d86 --- /dev/null +++ b/ops/machines/all-systems.nix @@ -0,0 +1,23 @@ +{ depot, ... }: + +(with depot.ops.machines; [ + sanduny + whitby +]) ++ + +(with depot.users.tazjin.nixos; [ + camden + frog + tverskoy + zamalek +]) ++ + +(with depot.users.grfn.system.system; [ + yeren + mugwump +]) ++ + +(with depot.users.wpcarro.nixos; [ + ava + marcus +]) diff --git a/ops/machines/sanduny/default.nix b/ops/machines/sanduny/default.nix new file mode 100644 index 000000000000..109e6e693d96 --- /dev/null +++ b/ops/machines/sanduny/default.nix @@ -0,0 +1,111 @@ +# sanduny.tvl.su +# +# This is a VPS hosted with Bitfolk, intended to additionally serve +# some of our public services like cgit, josh and the websites. +# +# In case of whitby going down, sanduny will keep depot available. + +_: # ignore readTree options + +{ config, depot, lib, pkgs, ... }: + +let + mod = name: depot.path + ("/ops/modules/" + name); +in +{ + imports = [ + (mod "journaldriver.nix") + (mod "known-hosts.nix") + (mod "tvl-users.nix") + (mod "www/self-redirect.nix") + ]; + + networking = { + hostName = "sanduny"; + domain = "tvl.su"; + useDHCP = false; + + interfaces.eth0 = { + ipv4.addresses = lib.singleton { + address = "85.119.82.231"; + prefixLength = 21; + }; + + ipv6.addresses = lib.singleton { + address = "2001:ba8:1f1:f109::feed:edef:beef"; + prefixLength = 64; + }; + }; + + defaultGateway = "85.119.80.1"; + defaultGateway6.address = "2001:ba8:1f1:f109::1"; + + firewall.allowedTCPPorts = [ 22 80 443 ]; + + # https://bitfolk.com/customer_information.html#toc_2_DNS + nameservers = [ + "85.119.80.232" + "85.119.80.233" + "2001:ba8:1f1:f205::53" + "2001:ba8:1f1:f206::53" + ]; + }; + + security.sudo.wheelNeedsPassword = false; + + environment.systemPackages = with pkgs; [ + emacs-nox + vim + curl + unzip + htop + ]; + + programs.mtr.enable = true; + + services.openssh.enable = true; + services.fail2ban.enable = true; + + # Automatically collect garbage from the Nix store. + services.depot.automatic-gc = { + enable = true; + interval = "1 hour"; + diskThreshold = 2; # GiB + maxFreed = 5; # GiB + preserveGenerations = "90d"; + }; + + time.timeZone = "UTC"; + + # GRUB does not actually need to be installed on disk; Bitfolk have + # their own way of booting systems as long as config is in place. + boot.loader.grub.device = "nodev"; + boot.loader.grub.enable = true; + boot.loader.grub.version = 2; + boot.initrd.availableKernelModules = [ "xen_blkfront" ]; + + hardware.cpu.intel.updateMicrocode = true; + + fileSystems = { + "/" = { + device = "/dev/disk/by-uuid/aabc3638-43ca-45f3-af89-c451e8448e92"; + fsType = "ext4"; + }; + + "/boot" = { + device = "/dev/disk/by-uuid/75aa99d5-fed7-4c5c-8570-7745f6cff9f5"; + fsType = "ext3"; + }; + + "/nix" = { + device = "/dev/disk/by-uuid/d1721678-c294-482b-b72e-3b15f2c56c63"; + fsType = "ext4"; + }; + }; + + swapDevices = lib.singleton { + device = "/dev/disk/by-uuid/df4ad9da-0a06-4c27-93e5-5d44e4750e55"; + }; + + system.stateVersion = "22.05"; # Did you read the comment? +} diff --git a/ops/machines/whitby/OWNERS b/ops/machines/whitby/OWNERS new file mode 100644 index 000000000000..b1b749e871e1 --- /dev/null +++ b/ops/machines/whitby/OWNERS @@ -0,0 +1,6 @@ +inherited: false + +# Want in on this list? Try paying! +owners: + - lukegb + - tazjin diff --git a/ops/machines/whitby/README.md b/ops/machines/whitby/README.md new file mode 100644 index 000000000000..55287c541256 --- /dev/null +++ b/ops/machines/whitby/README.md @@ -0,0 +1,5 @@ +whitby +====== + +`whitby.tvl.fyi` is our dedicated server providing continuous +integration services and other random nonsense. diff --git a/ops/machines/whitby/default.nix b/ops/machines/whitby/default.nix new file mode 100644 index 000000000000..5de8481878bf --- /dev/null +++ b/ops/machines/whitby/default.nix @@ -0,0 +1,645 @@ +{ depot, lib, pkgs, ... }: # readTree options +{ config, ... }: # passed by module system + +let + inherit (builtins) listToAttrs; + inherit (lib) range; +in +{ + imports = [ + "${depot.path}/ops/modules/atward.nix" + "${depot.path}/ops/modules/cgit/default.nix" + "${depot.path}/ops/modules/clbot.nix" + "${depot.path}/ops/modules/gerrit-queue.nix" + "${depot.path}/ops/modules/irccat.nix" + "${depot.path}/ops/modules/josh.nix" + "${depot.path}/ops/modules/journaldriver.nix" + "${depot.path}/ops/modules/known-hosts.nix" + "${depot.path}/ops/modules/monorepo-gerrit.nix" + "${depot.path}/ops/modules/nixery.nix" + "${depot.path}/ops/modules/oauth2_proxy.nix" + "${depot.path}/ops/modules/owothia.nix" + "${depot.path}/ops/modules/panettone.nix" + "${depot.path}/ops/modules/paroxysm.nix" + "${depot.path}/ops/modules/restic.nix" + "${depot.path}/ops/modules/smtprelay.nix" + "${depot.path}/ops/modules/sourcegraph.nix" + "${depot.path}/ops/modules/tvl-buildkite.nix" + "${depot.path}/ops/modules/tvl-slapd/default.nix" + "${depot.path}/ops/modules/tvl-users.nix" + "${depot.path}/ops/modules/www/atward.tvl.fyi.nix" + "${depot.path}/ops/modules/www/auth.tvl.fyi.nix" + "${depot.path}/ops/modules/www/b.tvl.fyi.nix" + "${depot.path}/ops/modules/www/cache.tvl.su.nix" + "${depot.path}/ops/modules/www/cl.tvl.fyi.nix" + "${depot.path}/ops/modules/www/code.tvl.fyi.nix" + "${depot.path}/ops/modules/www/cs.tvl.fyi.nix" + "${depot.path}/ops/modules/www/deploys.tvl.fyi.nix" + "${depot.path}/ops/modules/www/images.tvl.fyi.nix" + "${depot.path}/ops/modules/www/nixery.dev.nix" + "${depot.path}/ops/modules/www/self-redirect.nix" + "${depot.path}/ops/modules/www/static.tvl.fyi.nix" + "${depot.path}/ops/modules/www/status.tvl.su.nix" + "${depot.path}/ops/modules/www/tazj.in.nix" + "${depot.path}/ops/modules/www/todo.tvl.fyi.nix" + "${depot.path}/ops/modules/www/tvl.fyi.nix" + "${depot.path}/ops/modules/www/tvl.su.nix" + "${depot.path}/ops/modules/www/wigglydonke.rs.nix" + "${depot.third_party.agenix.src}/modules/age.nix" + "${pkgs.path}/nixos/modules/services/web-apps/gerrit.nix" + ]; + + hardware = { + enableRedistributableFirmware = true; + cpu.amd.updateMicrocode = true; + }; + + boot = { + tmpOnTmpfs = true; + kernelModules = [ "kvm-amd" ]; + supportedFilesystems = [ "zfs" ]; + + initrd = { + availableKernelModules = [ + "igb" + "xhci_pci" + "nvme" + "ahci" + "usbhid" + "usb_storage" + "sr_mod" + ]; + + # Enable SSH in the initrd so that we can enter disk encryption + # passwords remotely. + network = { + enable = true; + ssh = { + enable = true; + port = 2222; + authorizedKeys = + depot.users.tazjin.keys.all + ++ depot.users.lukegb.keys.all + ++ [ depot.users.grfn.keys.whitby ]; + + hostKeys = [ + /etc/secrets/initrd_host_ed25519_key + ]; + }; + + # this will launch the zfs password prompt on login and kill the + # other prompt + postCommands = '' + echo "zfs load-key -a && killall zfs" >> /root/.profile + ''; + }; + }; + + kernel.sysctl = { + "net.ipv4.tcp_congestion_control" = "bbr"; + }; + + loader.grub = { + enable = true; + version = 2; + efiSupport = true; + efiInstallAsRemovable = true; + device = "/dev/disk/by-id/nvme-SAMSUNG_MZQLB1T9HAJR-00007_S439NA0N201620"; + }; + + zfs.requestEncryptionCredentials = true; + }; + + fileSystems = { + "/" = { + device = "zroot/root"; + fsType = "zfs"; + }; + + "/boot" = { + device = "/dev/disk/by-uuid/073E-7FBD"; + fsType = "vfat"; + }; + + "/nix" = { + device = "zroot/nix"; + fsType = "zfs"; + }; + + "/home" = { + device = "zroot/home"; + fsType = "zfs"; + }; + }; + + networking = { + # Glass is boring, but Luke doesn't like Wapping - the Prospect of + # Whitby, however, is quite a pleasant establishment. + hostName = "whitby"; + domain = "tvl.fyi"; + hostId = "b38ca543"; + useDHCP = false; + + # Don't use Hetzner's DNS servers. + nameservers = [ + "8.8.8.8" + "8.8.4.4" + ]; + + defaultGateway6 = { + address = "fe80::1"; + interface = "enp196s0"; + }; + + firewall.allowedTCPPorts = [ 22 80 443 4238 8443 29418 ]; + firewall.allowedUDPPorts = [ 8443 ]; + + interfaces.enp196s0.useDHCP = true; + interfaces.enp196s0.ipv6.addresses = [ + { + address = "2a01:04f8:0242:5b21::feed:edef:beef"; + prefixLength = 64; + } + ]; + }; + + # Generate an immutable /etc/resolv.conf from the nameserver settings + # above (otherwise DHCP overwrites it): + environment.etc."resolv.conf" = with lib; { + source = pkgs.writeText "resolv.conf" '' + ${concatStringsSep "\n" (map (ns: "nameserver ${ns}") config.networking.nameservers)} + options edns0 + ''; + }; + + # Disable background git gc system-wide, as it has a tendency to break CI. + environment.etc."gitconfig".source = pkgs.writeText "gitconfig" '' + [gc] + autoDetach = false + ''; + + time.timeZone = "UTC"; + + nix = { + nrBuildUsers = 256; + maxJobs = lib.mkDefault 64; + extraOptions = '' + secret-key-files = /run/agenix/nix-cache-priv + ''; + + trustedUsers = [ + "grfn" + "lukegb" + "tazjin" + "sterni" + ]; + + sshServe = { + enable = true; + keys = with depot.users; + tazjin.keys.all + ++ lukegb.keys.all + ++ [ grfn.keys.whitby ] + ++ sterni.keys.all + ; + }; + }; + + programs.mtr.enable = true; + programs.mosh.enable = true; + services.openssh = { + enable = true; + passwordAuthentication = false; + challengeResponseAuthentication = false; + }; + + # Configure secrets for services that need them. + age.secrets = + let + secretFile = name: depot.ops.secrets."${name}.age"; + in + { + clbot.file = secretFile "clbot"; + gerrit-queue.file = secretFile "gerrit-queue"; + grafana.file = secretFile "grafana"; + irccat.file = secretFile "irccat"; + keycloak-db.file = secretFile "keycloak-db"; + nix-cache-priv.file = secretFile "nix-cache-priv"; + oauth2_proxy.file = secretFile "oauth2_proxy"; + owothia.file = secretFile "owothia"; + panettone.file = secretFile "panettone"; + smtprelay.file = secretFile "smtprelay"; + + buildkite-agent-token = { + file = secretFile "buildkite-agent-token"; + mode = "0440"; + group = "buildkite-agents"; + }; + + buildkite-graphql-token = { + file = secretFile "buildkite-graphql-token"; + mode = "0440"; + group = "buildkite-agents"; + }; + + buildkite-besadii-config = { + file = secretFile "besadii"; + mode = "0440"; + group = "buildkite-agents"; + }; + + gerrit-besadii-config = { + file = secretFile "besadii"; + owner = "git"; + }; + + gerrit-secrets = { + file = secretFile "gerrit-secrets"; + path = "/var/lib/gerrit/etc/secure.config"; + owner = "git"; + mode = "0400"; + }; + + clbot-ssh = { + file = secretFile "clbot-ssh"; + owner = "clbot"; + }; + + # Not actually a secret + nix-cache-pub = { + file = secretFile "nix-cache-pub"; + mode = "0444"; + }; + }; + + # Automatically collect garbage from the Nix store. + services.depot.automatic-gc = { + enable = true; + interval = "1 hour"; + diskThreshold = 200; # GiB + maxFreed = 420; # GiB + preserveGenerations = "90d"; + }; + + # Run a handful of Buildkite agents to support parallel builds. + services.depot.buildkite = { + enable = true; + agentCount = 32; + }; + + # Start a local SMTP relay to Gmail (used by gerrit) + services.depot.smtprelay = { + enable = true; + args = { + listen = ":2525"; + remote_host = "smtp.gmail.com:587"; + remote_auth = "plain"; + remote_user = "tvlbot@tazj.in"; + }; + }; + + # Start a ZNC instance which bounces for tvlbot and owothia. + services.znc = { + enable = true; + useLegacyConfig = false; + config = { + LoadModule = [ + "webadmin" + "adminlog" + ]; + + User.admin = { + Admin = true; + Pass.password = { + Method = "sha256"; + Hash = "bb00aa8239de484c2925b1c3f6a196fb7612633f001daa9b674f83abe7e1103f"; + Salt = "TiB0Ochb1CrtpMTl;2;j"; + }; + }; + + Listener.l = { + Host = "localhost"; + Port = 2627; # bncr + SSL = false; + }; + }; + }; + + # Start the Gerrit->IRC bot + services.depot.clbot = { + enable = true; + channels = [ "#tvl" ]; + + # See //fun/clbot for details. + flags = { + gerrit_host = "cl.tvl.fyi:29418"; + gerrit_ssh_auth_username = "clbot"; + gerrit_ssh_auth_key = "/run/agenix/clbot-ssh"; + + irc_server = "localhost:${toString config.services.znc.config.Listener.l.Port}"; + irc_user = "tvlbot"; + irc_nick = "tvlbot"; + + notify_branches = "canon,refs/meta/config"; + notify_repo = "depot"; + + # This secret is read from an environment variable, which is + # populated by a systemd EnvironmentFile. + irc_pass = "$CLBOT_PASS"; + }; + }; + + services.depot = { + # Run a SourceGraph code search instance + sourcegraph.enable = true; + + # Run the Panettone issue tracker + panettone = { + enable = true; + dbUser = "panettone"; + dbName = "panettone"; + irccatChannel = "#tvl"; + }; + + # Run the first cursed bot (quote bot) + paroxysm.enable = true; + + # Run the second cursed bot + owothia = { + enable = true; + ircServer = "localhost"; + ircPort = config.services.znc.config.Listener.l.Port; + }; + + # Run irccat to forward messages to IRC + irccat = { + enable = true; + config = { + tcp.listen = ":4722"; # "ircc" + irc = { + server = "localhost:${toString config.services.znc.config.Listener.l.Port}"; + tls = false; + nick = "tvlbot"; + # Note: irccat means 'ident' where it says 'realname', so + # this is critical for connecting to ZNC. + realname = "tvlbot"; + channels = [ + "#tvl" + ]; + }; + }; + }; + + # Run atward, the search engine redirection thing. + atward.enable = true; + + # Run a Nixery instance + nixery.enable = true; + + # Run cgit & josh to serve git + cgit.enable = true; + josh.enable = true; + + # Configure backups to GleSYS + restic = { + enable = true; + paths = [ + "/var/backup/postgresql" + "/var/lib/grafana" + "/var/lib/znc" + ]; + }; + + # Run autosubmit bot for Gerrit + gerrit-queue.enable = true; + + # Run oauth2_proxy for internal service auth + oauth2_proxy.enable = true; + }; + + services.postgresql = { + enable = true; + enableTCPIP = true; + + authentication = lib.mkForce '' + local all all trust + host all all 127.0.0.1/32 password + host all all ::1/128 password + hostnossl all all 127.0.0.1/32 password + hostnossl all all ::1/128 password + ''; + + ensureDatabases = [ + "panettone" + ]; + + ensureUsers = [{ + name = "panettone"; + ensurePermissions = { + "DATABASE panettone" = "ALL PRIVILEGES"; + }; + }]; + }; + + services.postgresqlBackup = { + enable = true; + databases = [ + "keycloak" + "panettone" + "tvldb" + ]; + }; + + services.nix-serve = { + enable = true; + port = 6443; + secretKeyFile = "/run/agenix/nix-cache-priv"; + bindAddress = "localhost"; + }; + + services.fail2ban.enable = true; + + environment.systemPackages = (with pkgs; [ + bat + bb + curl + direnv + emacs-nox + fd + git + htop + hyperfine + jq + nano + nvd + ripgrep + tree + unzip + vim + zfs + zfstools + ]) ++ (with depot; [ + ops.deploy-whitby + ]); + + # Required for prometheus to be able to scrape stats + services.nginx.statusPage = true; + + # Configure Prometheus & Grafana. Exporter configuration for + # Prometheus is inside the respective service modules. + services.prometheus = { + enable = true; + retentionTime = "90d"; + + exporters = { + node = { + enable = true; + + enabledCollectors = [ + "logind" + "processes" + "systemd" + ]; + }; + + nginx = { + enable = true; + sslVerify = false; + constLabels = [ "host=whitby" ]; + }; + }; + + scrapeConfigs = [{ + job_name = "node"; + scrape_interval = "5s"; + static_configs = [{ + targets = [ "localhost:${toString config.services.prometheus.exporters.node.port}" ]; + }]; + } + { + job_name = "nginx"; + scrape_interval = "5s"; + static_configs = [{ + targets = [ "localhost:${toString config.services.prometheus.exporters.nginx.port}" ]; + }]; + }]; + }; + + services.grafana = { + enable = true; + port = 4723; # "graf" on phone keyboard + domain = "status.tvl.su"; + rootUrl = "https://status.tvl.su"; + analytics.reporting.enable = false; + extraOptions = + let + options = { + auth = { + generic_oauth = { + enabled = true; + client_id = "grafana"; + scopes = "openid profile email"; + name = "TVL"; + email_attribute_path = "mail"; + login_attribute_path = "sub"; + name_attribute_path = "displayName"; + auth_url = "https://auth.tvl.fyi/auth/realms/TVL/protocol/openid-connect/auth"; + token_url = "https://auth.tvl.fyi/auth/realms/TVL/protocol/openid-connect/token"; + api_url = "https://auth.tvl.fyi/auth/realms/TVL/protocol/openid-connect/userinfo"; + + # Give lukegb, grfn, tazjin "Admin" rights. + role_attribute_path = "((sub == 'lukegb' || sub == 'grfn' || sub == 'tazjin') && 'Admin') || 'Editor'"; + + # Allow creating new Grafana accounts from OAuth accounts. + allow_sign_up = true; + }; + + anonymous = { + enabled = true; + org_name = "The Virus Lounge"; + org_role = "Viewer"; + }; + + basic.enabled = false; + oauth_auto_login = true; + disable_login_form = true; + }; + }; + inherit (builtins) typeOf replaceStrings listToAttrs concatLists; + inherit (lib) toUpper mapAttrsToList nameValuePair concatStringsSep; + + # Take ["auth" "generic_oauth" "enabled"] and turn it into OPTIONS_GENERIC_OAUTH_ENABLED. + encodeName = raw: replaceStrings [ "." ] [ "_" ] (toUpper (concatStringsSep "_" raw)); + + # Turn an option value into a string, but we want bools to be sensible strings and not "1" or "". + optionToString = value: + if (typeOf value) == "bool" then + if value then "true" else "false" + else builtins.toString value; + + # Turn an nested options attrset into a flat listToAttrs-compatible list. + encodeOptions = prefix: inp: concatLists (mapAttrsToList + (name: value: + if (typeOf value) == "set" + then encodeOptions (prefix ++ [ name ]) value + else [ (nameValuePair (encodeName (prefix ++ [ name ])) (optionToString value)) ] + ) + inp); + in + listToAttrs (encodeOptions [ ] options); + + provision = { + enable = true; + datasources = [{ + name = "Prometheus"; + type = "prometheus"; + url = "http://localhost:9090"; + }]; + }; + }; + + # Contains GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET. + systemd.services.grafana.serviceConfig.EnvironmentFile = "/run/agenix/grafana"; + + services.keycloak = { + enable = true; + httpPort = "5925"; # "kycl" + + settings = { + hostname = "auth.tvl.fyi"; + http-relative-path = "/auth"; + proxy = "edge"; + }; + + database = { + type = "postgresql"; + passwordFile = "/run/agenix/keycloak-db"; + createLocally = false; + }; + }; + + # Allow Keycloak access to the LDAP module by forcing in the JVM + # configuration + systemd.services.keycloak.environment.PREPEND_JAVA_OPTS = + "--add-exports=java.naming/com.sun.jndi.ldap=ALL-UNNAMED"; + + security.sudo.extraRules = [ + { + groups = [ "wheel" ]; + commands = [{ command = "ALL"; options = [ "NOPASSWD" ]; }]; + } + ]; + + users = { + # Set up a user & group for git shenanigans + groups.git = { }; + users.git = { + group = "git"; + isSystemUser = true; + createHome = true; + home = "/var/lib/git"; + }; + }; + + system.stateVersion = "20.03"; +} diff --git a/ops/modules/.skip-subtree b/ops/modules/.skip-subtree new file mode 100644 index 000000000000..09520f8c831f --- /dev/null +++ b/ops/modules/.skip-subtree @@ -0,0 +1 @@ +NixOS modules are not readTree compatible. diff --git a/ops/modules/README.md b/ops/modules/README.md new file mode 100644 index 000000000000..595b4c3344c6 --- /dev/null +++ b/ops/modules/README.md @@ -0,0 +1,7 @@ +NixOS modules +============= + +This folder contains various NixOS modules shared by our NixOS +configurations. + +It is not read by `readTree`. diff --git a/ops/modules/atward.nix b/ops/modules/atward.nix new file mode 100644 index 000000000000..f345a08e3131 --- /dev/null +++ b/ops/modules/atward.nix @@ -0,0 +1,38 @@ +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.atward; + description = "atward - (attempt to) cleverly route queries"; +in +{ + options.services.depot.atward = { + enable = lib.mkEnableOption description; + + host = lib.mkOption { + type = lib.types.str; + default = "[::1]"; + description = "Host on which atward should listen"; + }; + + port = lib.mkOption { + type = lib.types.int; + default = 28973; + description = "Port on which atward should listen"; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.atward = { + inherit description; + script = "${depot.web.atward}/bin/atward"; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + DynamicUser = true; + Restart = "always"; + }; + + environment.ATWARD_LISTEN_ADDRESS = "${cfg.host}:${toString cfg.port}"; + }; + }; +} diff --git a/ops/modules/auto-deploy.nix b/ops/modules/auto-deploy.nix new file mode 100644 index 000000000000..c504906b2b94 --- /dev/null +++ b/ops/modules/auto-deploy.nix @@ -0,0 +1,104 @@ +# Defines a service for automatically and periodically calling depot's +# rebuild-system on a NixOS machine. +# +# Deploys can be stopped in emergency situations by creating an empty +# file called `stop` in the state directory of the auto-deploy service +# (typically /var/lib/auto-deploy). +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.auto-deploy; + description = "to automatically rebuild the current system's NixOS config from the latest checkout of depot"; + + rebuild-system = depot.ops.nixos.rebuildSystemWith "$STATE_DIRECTORY/deploy"; + deployScript = pkgs.writeShellScript "auto-deploy" '' + set -ueo pipefail + + if [[ $EUID -ne 0 ]]; then + echo "Oh no! Only root is allowed to run auto-deploy!" >&2 + exit 1 + fi + + if [[ -f $STATE_DIRECTORY/stop ]]; then + echo "stop file exists in $STATE_DIRECTORY, not deploying!" >&2 + exit 1 + fi + + readonly depot=$STATE_DIRECTORY/depot.git + readonly deploy=$STATE_DIRECTORY/deploy + readonly git="git -C $depot" + + # find-or-create depot + if [ ! -d $depot ]; then + # cannot use $git here because $depot doesn't exist + git clone --bare ${cfg.git-remote} $depot + fi + + function cleanup() { + $git worktree remove $deploy + } + trap cleanup EXIT + + $git fetch origin + $git worktree add --force $deploy FETCH_HEAD + # unsure why, but without this switch-to-configuration attempts to install + # NixOS in $STATE_DIRECTORY + (cd / && ${rebuild-system}/bin/rebuild-system) + ''; +in +{ + options.services.depot.auto-deploy = { + enable = lib.mkEnableOption description; + + git-remote = lib.mkOption { + type = lib.types.str; + default = "https://cl.tvl.fyi/depot.git"; + description = '' + The (possibly remote) repository from which to clone as specified by the + GIT URLS section of `man git-clone`. + ''; + }; + + interval = lib.mkOption { + type = lib.types.str; + example = "1h"; + description = '' + Interval between Nix builds, specified in systemd.time(7) format. + ''; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.auto-deploy = { + inherit description; + script = "${deployScript}"; + path = with pkgs; [ + bash + git + gnutar + gzip + ]; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + + # We need to prevent NixOS from interrupting us while it attempts to + # restart systemd units. + restartIfChanged = false; + + serviceConfig = { + Type = "oneshot"; + StateDirectory = "auto-deploy"; + }; + }; + + systemd.timers.auto-deploy = { + inherit description; + wantedBy = [ "multi-user.target" ]; + + timerConfig = { + OnActiveSec = "1"; + OnUnitActiveSec = cfg.interval; + }; + }; + }; +} diff --git a/ops/modules/automatic-gc.nix b/ops/modules/automatic-gc.nix new file mode 100644 index 000000000000..ad53a63f7f16 --- /dev/null +++ b/ops/modules/automatic-gc.nix @@ -0,0 +1,92 @@ +# Defines a service for automatically collecting Nix garbage +# periodically, without relying on the (ostensibly broken) Nix options +# for min/max space available. +{ config, lib, pkgs, ... }: + +let + cfg = config.services.depot.automatic-gc; + description = "Automatically collect Nix garbage"; + + GiBtoKiB = n: n * 1024 * 1024; + GiBtoBytes = n: n * 1024 * 1024 * 1024; + + gcScript = pkgs.writeShellScript "automatic-nix-gc" '' + set -ueo pipefail + + readonly MIN_THRESHOLD_KIB="${toString (GiBtoKiB cfg.diskThreshold)}" + readonly MAX_FREED_BYTES="${toString (GiBtoBytes cfg.maxFreed)}" + readonly GEN_THRESHOLD="${cfg.preserveGenerations}" + readonly AVAILABLE_KIB=$(df --sync /nix --output=avail | tail -n1) + + if [ "''${AVAILABLE_KIB}" -lt "''${MIN_THRESHOLD_KIB}" ]; then + echo "Have ''${AVAILABLE_KIB} KiB, but want ''${MIN_THRESHOLD_KIB} KiB." + echo "Triggering Nix garbage collection up to ''${MAX_FREED_BYTES} bytes." + set -x + ${config.nix.package}/bin/nix-collect-garbage \ + --delete-older-than "''${GEN_THRESHOLD}" \ + --max-freed "''${MAX_FREED_BYTES}" + else + echo "Skipping GC, enough space available" + fi + ''; +in +{ + options.services.depot.automatic-gc = { + enable = lib.mkEnableOption description; + + interval = lib.mkOption { + type = lib.types.str; + example = "1h"; + description = '' + Interval between garbage collection runs, specified in + systemd.time(7) format. + ''; + }; + + diskThreshold = lib.mkOption { + type = lib.types.int; + example = "100"; + description = '' + Minimum amount of space that needs to be available (in GiB) on + the partition holding /nix. Garbage collection is triggered if + it falls below this. + ''; + }; + + maxFreed = lib.mkOption { + type = lib.types.int; + example = "420"; + description = '' + Maximum amount of space to free in a single GC run, in GiB. + ''; + }; + + preserveGenerations = lib.mkOption { + type = lib.types.str; + default = "90d"; + description = '' + Preserve NixOS generations younger than the specified value, + in the format expected by nix-collect-garbage(1). + ''; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.automatic-gc = { + inherit description; + script = "${gcScript}"; + serviceConfig.Type = "oneshot"; + }; + + systemd.timers.automatic-gc = { + inherit description; + requisite = [ "nix-daemon.service" ]; + wantedBy = [ "multi-user.target" ]; + + timerConfig = { + OnActiveSec = "1"; + OnUnitActiveSec = cfg.interval; + }; + }; + }; +} diff --git a/ops/modules/cgit/default.nix b/ops/modules/cgit/default.nix new file mode 100644 index 000000000000..580b8384bd90 --- /dev/null +++ b/ops/modules/cgit/default.nix @@ -0,0 +1,92 @@ +# Configuration for running the TVL cgit instance using thttpd. +{ config, depot, lib, pkgs, ... }: + +let + inherit (pkgs) writeText; + + cfg = config.services.depot.cgit; + + cgitConfig = writeText "cgitrc" '' + # Global configuration + virtual-root=/ + enable-http-clone=0 + readme=:README.md + about-filter=${depot.tools.cheddar.about-filter}/bin/cheddar-about + source-filter=${depot.tools.cheddar}/bin/cheddar + enable-log-filecount=1 + enable-log-linecount=1 + enable-follow-links=1 + enable-blame=1 + mimetype-file=${pkgs.mime-types}/etc/mime.types + logo=https://static.tvl.fyi/${depot.web.static.drvHash}/logo-animated.svg + + # Repository configuration + repo.url=depot + repo.path=/var/lib/gerrit/git/depot.git/ + repo.desc=monorepo for the virus lounge + repo.owner=The Virus Lounge + repo.clone-url=https://code.tvl.fyi/depot.git + ''; + + thttpdConfig = writeText "thttpd.conf" '' + port=${toString cfg.port} + dir=${depot.third_party.cgit}/cgit + nochroot + novhost + cgipat=**.cgi + ''; + + # Patched version of thttpd that serves cgit.cgi as the index and + # sets the environment variable for pointing cgit at the correct + # configuration. + # + # Things are done this way because recompilation of thttpd is much + # faster than cgit. + thttpdConfigPatch = writeText "thttpd_cgit_conf.patch" '' + diff --git a/libhttpd.c b/libhttpd.c + index c6b1622..eef4b73 100644 + --- a/libhttpd.c + +++ b/libhttpd.c + @@ -3055,4 +3055,6 @@ make_envp( httpd_conn* hc ) + + envn = 0; + + // force cgit to load the correct configuration + + envp[envn++] = "CGIT_CONFIG=${cgitConfig}"; + envp[envn++] = build_env( "PATH=%s", CGI_PATH ); + #ifdef CGI_LD_LIBRARY_PATH + ''; + + thttpdCgit = pkgs.thttpd.overrideAttrs (old: { + patches = [ + ./thttpd_cgi_idx.patch + thttpdConfigPatch + ]; + }); +in +{ + options.services.depot.cgit = with lib; { + enable = mkEnableOption "Run cgit web interface for depot"; + + port = mkOption { + description = "Port on which cgit should listen"; + type = types.int; + default = 2448; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.cgit = { + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + Restart = "on-failure"; + User = "git"; + Group = "git"; + + ExecStart = pkgs.writeShellScript "cgit-launch" '' + exec ${thttpdCgit}/bin/thttpd -D -C ${thttpdConfig} + ''; + }; + }; + }; +} diff --git a/ops/modules/cgit/thttpd_cgi_idx.patch b/ops/modules/cgit/thttpd_cgi_idx.patch new file mode 100644 index 000000000000..67dbc0c7ab80 --- /dev/null +++ b/ops/modules/cgit/thttpd_cgi_idx.patch @@ -0,0 +1,13 @@ +diff --git a/config.h b/config.h +index 65ab1e3..cde470f 100644 +--- a/config.h ++++ b/config.h +@@ -327,7 +327,7 @@ + /* CONFIGURE: A list of index filenames to check. The files are searched + ** for in this order. + */ +-#define INDEX_NAMES "index.html", "index.htm", "index.xhtml", "index.xht", "Default.htm", "index.cgi" ++#define INDEX_NAMES "cgit.cgi" + + /* CONFIGURE: If this is defined then thttpd will automatically generate + ** index pages for directories that don't have an explicit index file. diff --git a/ops/modules/clbot.nix b/ops/modules/clbot.nix new file mode 100644 index 000000000000..958d321f81ad --- /dev/null +++ b/ops/modules/clbot.nix @@ -0,0 +1,82 @@ +# Module that configures CLBot, our Gerrit->IRC info bridge. +{ depot, config, lib, pkgs, ... }: + +let + inherit (builtins) attrValues concatStringsSep mapAttrs readFile; + inherit (pkgs) runCommandNoCC; + + inherit (lib) + listToAttrs + mkEnableOption + mkIf + mkOption + removeSuffix + types; + + description = "Bot to forward CL notifications"; + cfg = config.services.depot.clbot; + + mkFlags = flags: + concatStringsSep " " + (attrValues (mapAttrs (key: value: "-${key} \"${toString value}\"") flags)); + + # Escapes a unit name for use in systemd + systemdEscape = name: removeSuffix "\n" (readFile (runCommandNoCC "unit-name" { } '' + ${pkgs.systemd}/bin/systemd-escape '${name}' >> $out + '')); + + mkUnit = flags: channel: { + name = "clbot-${systemdEscape channel}"; + value = { + description = "${description} to ${channel}"; + wantedBy = [ "multi-user.target" ]; + + script = "${depot.fun.clbot}/bin/clbot ${mkFlags (cfg.flags // { + irc_channel = channel; + })} -alsologtostderr"; + + serviceConfig = { + User = "clbot"; + EnvironmentFile = cfg.secretsFile; + Restart = "always"; + }; + }; + }; +in +{ + options.services.depot.clbot = { + enable = mkEnableOption description; + + flags = mkOption { + type = types.attrsOf types.str; + description = "Key value pairs for command line flags"; + }; + + channels = mkOption { + type = with types; listOf str; + description = "Channels in which to post (generates one unit per channel)"; + }; + + secretsFile = mkOption { + type = types.str; + description = "EnvironmentFile from which to load secrets"; + default = "/run/agenix/clbot"; + }; + }; + + config = mkIf cfg.enable { + # This does not use DynamicUser because we need to make some files + # (notably the SSH private key) readable by this user outside of + # the module. + users = { + groups.clbot = { }; + + users.clbot = { + group = "clbot"; + isSystemUser = true; + }; + }; + + systemd.services = listToAttrs (map (mkUnit cfg.flags) cfg.channels); + }; +} diff --git a/ops/modules/default-imports.nix b/ops/modules/default-imports.nix new file mode 100644 index 000000000000..11514a437a42 --- /dev/null +++ b/ops/modules/default-imports.nix @@ -0,0 +1,14 @@ +{ depot, ... }: + +# Default set of modules that are imported in all Depot nixos systems +# +# All modules here should be properly gated behind a `lib.mkEnableOption` with a +# `lib.mkIf` for the config. + +{ + imports = [ + ./automatic-gc.nix + ./auto-deploy.nix + ./tvl-cache.nix + ]; +} diff --git a/ops/modules/default.nix b/ops/modules/default.nix new file mode 100644 index 000000000000..d747e8e1319a --- /dev/null +++ b/ops/modules/default.nix @@ -0,0 +1,2 @@ +# Make readTree happy at this level. +_: { } diff --git a/ops/modules/gerrit-queue.nix b/ops/modules/gerrit-queue.nix new file mode 100644 index 000000000000..66d584cc3361 --- /dev/null +++ b/ops/modules/gerrit-queue.nix @@ -0,0 +1,52 @@ +# Configuration for the Gerrit autosubmit bot (//third_party/gerrit-queue) +{ depot, pkgs, config, lib, ... }: + +let + cfg = config.services.depot.gerrit-queue; + description = "gerrit-queue - autosubmit bot for Gerrit"; + mkStringOption = default: lib.mkOption { + inherit default; + type = lib.types.str; + }; +in +{ + options.services.depot.gerrit-queue = { + enable = lib.mkEnableOption description; + gerritUrl = mkStringOption "https://cl.tvl.fyi"; + gerritProject = mkStringOption "depot"; + gerritBranch = mkStringOption "canon"; + + interval = with lib; mkOption { + type = types.int; + default = 60; + description = "Interval (in seconds) for submit queue checks"; + }; + + secretsFile = with lib; mkOption { + description = "Path to a systemd EnvironmentFile containing secrets"; + default = "/run/agenix/gerrit-queue"; + type = types.str; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.gerrit-queue = { + inherit description; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + ExecStart = "${depot.third_party.gerrit-queue}/bin/gerrit-queue"; + DynamicUser = true; + Restart = "always"; + EnvironmentFile = cfg.secretsFile; + }; + + environment = { + GERRIT_URL = cfg.gerritUrl; + GERRIT_PROJECT = cfg.gerritProject; + GERRIT_BRANCH = cfg.gerritBranch; + SUBMIT_QUEUE_TRIGGER_INTERVAL = toString cfg.interval; + }; + }; + }; +} diff --git a/ops/modules/irccat.nix b/ops/modules/irccat.nix new file mode 100644 index 000000000000..05a783fd6614 --- /dev/null +++ b/ops/modules/irccat.nix @@ -0,0 +1,62 @@ +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.irccat; + description = "irccat - forward messages to IRC"; + + # irccat expects to read its configuration from the *current + # directory*, and its configuration contains secrets. + # + # To make this work we construct the JSON configuration file and + # then recursively merge it with an on-disk secret using jq on + # service launch. + configJson = pkgs.writeText "irccat.json" (builtins.toJSON cfg.config); + + # Right now, merging configuration file with secrets and running the main + # application needs to happen both in ExecStart=, due to + # https://github.com/systemd/systemd/issues/19604#issuecomment-989279884 + mergeAndLaunch = pkgs.writeShellScript "merge-irccat-config" '' + if [ ! -f "$CREDENTIALS_DIRECTORY/secrets" ]; then + echo "irccat secrets file is missing" + exit 1 + fi + + # jq's * is the recursive merge operator + ${pkgs.jq}/bin/jq -s '.[0] * .[1]' ${configJson} "$CREDENTIALS_DIRECTORY/secrets" \ + > /var/lib/irccat/irccat.json + + exec ${depot.third_party.irccat}/bin/irccat + ''; +in +{ + options.services.depot.irccat = { + enable = lib.mkEnableOption description; + + config = lib.mkOption { + type = lib.types.attrs; # varying value types + description = "Configuration structure (unchecked!)"; + }; + + secretsFile = lib.mkOption { + type = lib.types.str; + description = "Path to the secrets file to be merged"; + default = "/run/agenix/irccat"; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.irccat = { + inherit description; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + ExecStart = "${mergeAndLaunch}"; + DynamicUser = true; + StateDirectory = "irccat"; + WorkingDirectory = "/var/lib/irccat"; + LoadCredential = "secrets:${cfg.secretsFile}"; + Restart = "always"; + }; + }; + }; +} diff --git a/ops/modules/josh.nix b/ops/modules/josh.nix new file mode 100644 index 000000000000..be9e9e966e6b --- /dev/null +++ b/ops/modules/josh.nix @@ -0,0 +1,33 @@ +# Configures the public josh instance for serving the depot. +{ config, depot, lib, pkgs, ... }: + +let + cfg = config.services.depot.josh; +in +{ + options.services.depot.josh = with lib; { + enable = mkEnableOption "Enable josh for serving the depot"; + + port = mkOption { + description = "Port on which josh should listen"; + type = types.int; + default = 5674; + }; + }; + + config = lib.mkIf cfg.enable { + # Run josh for the depot. + systemd.services.josh = { + description = "josh - partial cloning of monorepos"; + wantedBy = [ "multi-user.target" ]; + path = [ pkgs.git pkgs.bash ]; + + serviceConfig = { + DynamicUser = true; + StateDirectory = "josh"; + Restart = "always"; + ExecStart = "${depot.third_party.josh}/bin/josh-proxy --no-background --local /var/lib/josh --port ${toString cfg.port} --remote https://cl.tvl.fyi/"; + }; + }; + }; +} diff --git a/ops/modules/journaldriver.nix b/ops/modules/journaldriver.nix new file mode 100644 index 000000000000..0d6b0bcc7f63 --- /dev/null +++ b/ops/modules/journaldriver.nix @@ -0,0 +1,26 @@ +# Configures journaldriver to forward to the tvl-fyi GCP project from +# TVL machines. +{ config, depot, lib, pkgs, ... }: + +{ + imports = [ + (depot.third_party.agenix.src + "/modules/age.nix") + ]; + + age.secrets.journaldriver.file = depot.ops.secrets."journaldriver.age"; + + services.journaldriver = { + enable = true; + googleCloudProject = "tvl-fyi"; + logStream = config.networking.hostName; + }; + + # Override the systemd service defined in the nixpkgs module to use + # the credentials provided by agenix. + systemd.services.journaldriver = { + serviceConfig = { + LoadCredential = "journaldriver.json:/run/agenix/journaldriver"; + ExecStart = lib.mkForce "${pkgs.coreutils}/bin/env GOOGLE_APPLICATION_CREDENTIALS=\"\${CREDENTIALS_DIRECTORY}/journaldriver.json\" ${depot.ops.journaldriver}/bin/journaldriver"; + }; + }; +} diff --git a/ops/modules/known-hosts.nix b/ops/modules/known-hosts.nix new file mode 100644 index 000000000000..ef24d61c5767 --- /dev/null +++ b/ops/modules/known-hosts.nix @@ -0,0 +1,21 @@ +# Configure public keys for SSH hosts known to TVL. +{ ... }: + +{ + programs.ssh.knownHosts = { + whitby = { + hostNames = [ "whitby.tvl.fyi" "whitby.tvl.su" ]; + publicKey = "whitby.tvl.fyi ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILNh/w4BSKov0jdz3gKBc98tpoLta5bb87fQXWBhAl2I"; + }; + + sanduny = { + hostNames = [ "sanduny.tvl.su" ]; + publicKey = "sanduny.tvl.su ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOag0XhylaTVhmT6HB8EN2Fv5Ymrc4ZfypOXONUkykTX"; + }; + + github = { + hostNames = [ "github.com" ]; + publicKey = "github.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl"; + }; + }; +} diff --git a/ops/modules/monorepo-gerrit.nix b/ops/modules/monorepo-gerrit.nix new file mode 100644 index 000000000000..509500c9139d --- /dev/null +++ b/ops/modules/monorepo-gerrit.nix @@ -0,0 +1,152 @@ +# Gerrit configuration for the TVL monorepo +{ depot, pkgs, config, lib, ... }: + +let + cfg = config.services.gerrit; + + besadiiWithConfig = name: pkgs.writeShellScript "besadii-whitby" '' + export BESADII_CONFIG=/run/agenix/gerrit-besadii-config + exec -a ${name} ${depot.ops.besadii}/bin/besadii "$@" + ''; + + gerritHooks = pkgs.runCommandNoCC "gerrit-hooks" { } '' + mkdir -p $out + ln -s ${besadiiWithConfig "change-merged"} $out/change-merged + ln -s ${besadiiWithConfig "patchset-created"} $out/patchset-created + ''; +in +{ + services.gerrit = { + enable = true; + listenAddress = "[::]:4778"; # 4778 - grrt + serverId = "4fdfa107-4df9-4596-8e0a-1d2bbdd96e36"; + builtinPlugins = [ + "download-commands" + "hooks" + ]; + + plugins = with depot.third_party.gerrit_plugins; [ + owners + oauth + depot.ops.gerrit-tvl + ]; + + package = depot.third_party.gerrit; + + jvmHeapLimit = "4g"; + + # In some NixOS channel bump, the default version of OpenJDK has + # changed to one that is incompatible with our current version of + # Gerrit. + # + # TODO(tazjin): Update Gerrit and remove this when possible. + jvmPackage = pkgs.openjdk11_headless; + + settings = { + core.packedGitLimit = "100m"; + log.jsonLogging = true; + log.textLogging = false; + sshd.advertisedAddress = "code.tvl.fyi:29418"; + hooks.path = "${gerritHooks}"; + cache.web_sessions.maxAge = "3 months"; + plugins.allowRemoteAdmin = false; + change.enableAttentionSet = true; + change.enableAssignee = false; + + # Configures gerrit for being reverse-proxied by nginx as per + # https://gerrit-review.googlesource.com/Documentation/config-reverseproxy.html + gerrit = { + canonicalWebUrl = "https://cl.tvl.fyi"; + docUrl = "/Documentation"; + }; + + httpd.listenUrl = "proxy-https://${cfg.listenAddress}"; + + download.command = [ + "checkout" + "cherry_pick" + "format_patch" + "pull" + ]; + + # Configure for cgit. + gitweb = { + type = "custom"; + url = "https://code.tvl.fyi"; + project = "/"; + revision = "/commit/?id=\${commit}"; + branch = "/log/?h=\${branch}"; + tag = "/tag/?h=\${tag}"; + roottree = "/tree/?h=\${commit}"; + file = "/tree/\${file}?h=\${commit}"; + filehistory = "/log/\${file}?h=\${branch}"; + linkname = "cgit"; + }; + + # Auto-link panettone bug links + commentlink.panettone = { + match = "b/(\\\\d+)"; + html = "<a href=\"https://b.tvl.fyi/issues/$1\">b/$1</a>"; + }; + + # Auto-link other CLs + commentlink.gerrit = { + match = "cl/(\\\\d+)"; + html = "<a href=\"https://cl.tvl.fyi/$1\">cl/$1</a>"; + }; + + # Configures integration with Keycloak, which then integrates with a + # variety of backends. + auth.type = "OAUTH"; + plugin.gerrit-oauth-provider-keycloak-oauth = { + root-url = "https://auth.tvl.fyi"; + realm = "TVL"; + client-id = "gerrit"; + # client-secret is set in /var/lib/gerrit/etc/secure.config. + }; + + # Allow users to add additional email addresses to their accounts. + oauth.allowRegisterNewEmail = true; + + # Use Gerrit's built-in HTTP passwords, rather than trying to use the + # password against the backing OAuth provider. + auth.gitBasicAuthPolicy = "HTTP"; + + # Email sending (emails are relayed via the tazj.in domain's + # GSuite currently). + # + # Note that sendemail.smtpPass is stored in + # $site_path/etc/secure.config and is *not* controlled by Nix. + # + # Receiving email is not currently supported. + sendemail = { + enable = true; + html = false; + connectTimeout = "10sec"; + from = "TVL Code Review <tvlbot@tazj.in>"; + includeDiff = true; + smtpEncryption = "none"; + smtpServer = "localhost"; + smtpServerPort = 2525; + }; + }; + }; + + systemd.services.gerrit = { + serviceConfig = { + # There seems to be no easy way to get `DynamicUser` to play + # well with other services (e.g. by using SupplementaryGroups, + # which seem to have no effect) so we force the DynamicUser + # setting for the Gerrit service to be disabled and reuse the + # existing 'git' user. + DynamicUser = lib.mkForce false; + User = "git"; + Group = "git"; + }; + }; + + services.depot.restic = { + paths = [ "/var/lib/gerrit" ]; + exclude = [ "/var/lib/gerrit/tmp" ]; + }; +} diff --git a/ops/modules/nixery.nix b/ops/modules/nixery.nix new file mode 100644 index 000000000000..cb80eff2e57c --- /dev/null +++ b/ops/modules/nixery.nix @@ -0,0 +1,43 @@ +# NixOS module to run Nixery, currently with local-storage as the +# backend for storing/serving image layers. +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.nixery; + description = "Nixery - container images on-demand"; + storagePath = "/var/lib/nixery/${pkgs.nixpkgsCommits.unstable}"; +in +{ + options.services.depot.nixery = { + enable = lib.mkEnableOption description; + + port = lib.mkOption { + type = lib.types.int; + default = 45243; # "image" + description = "Port on which Nixery should listen"; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.nixery = { + inherit description; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + DynamicUser = true; + StateDirectory = "nixery"; + Restart = "always"; + ExecStartPre = "${pkgs.coreutils}/bin/mkdir -p ${storagePath}"; + ExecStart = "${depot.tools.nixery.nixery-bin}/bin/nixery"; + }; + + environment = { + PORT = toString cfg.port; + NIXERY_PKGS_PATH = pkgs.path; + NIXERY_STORAGE_BACKEND = "filesystem"; + NIX_TIMEOUT = "60"; # seconds + STORAGE_PATH = storagePath; + }; + }; + }; +} diff --git a/ops/modules/oauth2_proxy.nix b/ops/modules/oauth2_proxy.nix new file mode 100644 index 000000000000..58b3a222a80d --- /dev/null +++ b/ops/modules/oauth2_proxy.nix @@ -0,0 +1,59 @@ +# Configuration for oauth2_proxy, which is used as a handler for nginx +# auth-request setups. +# +# This module exports a helper function at +# `config.services.depot.oauth2_proxy.withAuth` that can be wrapped +# around nginx server configuration blocks to configure their +# authentication setup. +{ config, depot, pkgs, lib, ... }: + +let + description = "OAuth2 proxy to authenticate TVL services"; + cfg = config.services.depot.oauth2_proxy; + configFile = pkgs.writeText "oauth2_proxy.cfg" '' + email_domains = [ "*" ] + http_address = "127.0.0.1:${toString cfg.port}" + provider = "keycloak-oidc" + client_id = "oauth2-proxy" + oidc_issuer_url = "https://auth.tvl.fyi/auth/realms/TVL" + reverse_proxy = true + set_xauthrequest = true + ''; + + # Depend on the Keycloak service if it is running on the same + # machine. + depends_on = lib.optional config.services.keycloak.enable "keycloak.service"; +in +{ + options.services.depot.oauth2_proxy = { + enable = lib.mkEnableOption description; + + port = lib.mkOption { + description = "Port to listen on"; + type = lib.types.int; + default = 2884; # "auth" + }; + + secretsFile = lib.mkOption { + type = lib.types.str; + description = "EnvironmentFile from which to load secrets"; + default = "/run/agenix/oauth2_proxy"; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.oauth2_proxy = { + inherit description; + after = depends_on; + wants = depends_on; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + Restart = "always"; + DynamicUser = true; + EnvironmentFile = cfg.secretsFile; + ExecStart = "${pkgs.oauth2_proxy}/bin/oauth2-proxy --config ${configFile}"; + }; + }; + }; +} diff --git a/ops/modules/open_eid.nix b/ops/modules/open_eid.nix new file mode 100644 index 000000000000..9fd325933198 --- /dev/null +++ b/ops/modules/open_eid.nix @@ -0,0 +1,35 @@ +# NixOS module to configure the Estonian e-ID software. +{ pkgs, ... }: + +let + # Wrapper script to tell to Chrome/Chromium to use p11-kit-proxy to load + # security devices. + # Each user needs to run this themselves, it does not work on a system level + # due to a bug in Chromium: + # + # https://bugs.chromium.org/p/chromium/issues/detail?id=16387 + # + # Firefox users can just set + # extraPolicies.SecurityDevices.p11-kit-proxy "${pkgs.p11-kit}/lib/p11-kit-proxy.so"; + # when overriding the firefox derivation. + setup-browser-eid = pkgs.writeShellScriptBin "setup-browser-eid" '' + NSSDB="''${HOME}/.pki/nssdb" + mkdir -p ''${NSSDB} + + ${pkgs.nssTools}/bin/modutil -force -dbdir sql:$NSSDB -add p11-kit-proxy \ + -libfile ${pkgs.p11-kit}/lib/p11-kit-proxy.so + ''; +in +{ + services.pcscd.enable = true; + + # Tell p11-kit to load onepin-opensc-pkcs11.so + environment.etc."pkcs11/modules/onepin-opensc-pkcs11".text = '' + module: ${pkgs.opensc}/lib/onepin-opensc-pkcs11.so + ''; + + environment.systemPackages = with pkgs; [ + qdigidoc + setup-browser-eid + ]; +} diff --git a/ops/modules/owothia.nix b/ops/modules/owothia.nix new file mode 100644 index 000000000000..d11fdd26ecbc --- /dev/null +++ b/ops/modules/owothia.nix @@ -0,0 +1,68 @@ +# Run the owothia IRC bot. +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.owothia; + description = "owothia - i'm a service owo"; +in +{ + options.services.depot.owothia = { + enable = lib.mkEnableOption description; + + secretsFile = lib.mkOption { + type = lib.types.str; + description = "File path from which systemd should read secrets"; + default = "/run/agenix/owothia"; + }; + + owoChance = lib.mkOption { + type = lib.types.int; + description = "How likely is owo?"; + default = 200; + }; + + ircServer = lib.mkOption { + type = lib.types.str; + description = "IRC server hostname"; + }; + + ircPort = lib.mkOption { + type = lib.types.int; + description = "IRC server port"; + }; + + ircIdent = lib.mkOption { + type = lib.types.str; + description = "IRC username"; + default = "owothia"; + }; + + ircChannels = lib.mkOption { + type = with lib.types; listOf str; + description = "IRC channels to join"; + default = [ "#tvl" ]; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.owothia = { + inherit description; + script = "${depot.fun.owothia}/bin/owothia"; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + DynamicUser = true; + Restart = "always"; + EnvironmentFile = cfg.secretsFile; + }; + + environment = { + OWO_CHANCE = toString cfg.owoChance; + IRC_SERVER = cfg.ircServer; + IRC_PORT = toString cfg.ircPort; + IRC_IDENT = cfg.ircIdent; + IRC_CHANNELS = builtins.toJSON cfg.ircChannels; + }; + }; + }; +} diff --git a/ops/modules/panettone.nix b/ops/modules/panettone.nix new file mode 100644 index 000000000000..d57e53e75442 --- /dev/null +++ b/ops/modules/panettone.nix @@ -0,0 +1,108 @@ +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.panettone; +in +{ + options.services.depot.panettone = with lib; { + enable = mkEnableOption "Panettone issue tracker"; + + port = mkOption { + description = "Port on which Panettone should listen"; + type = types.int; + default = 7268; + }; + + dbHost = mkOption { + description = "Postgresql host to connect to for Panettone"; + type = types.str; + default = "localhost"; + }; + + dbName = mkOption { + description = "Name of the database for Panettone"; + type = types.str; + default = "panettone"; + }; + + dbUser = mkOption { + description = "Name of the database user for Panettone"; + type = types.str; + default = "panettone"; + }; + + secretsFile = mkOption { + description = '' + Path to a file containing secrets, in the format accepted + by systemd's EnvironmentFile + ''; + type = types.str; + default = "/run/agenix/panettone"; + }; + + irccatHost = mkOption { + description = "Hostname for the irccat instance"; + type = types.str; + default = "localhost"; + }; + + irccatPort = mkOption { + description = "Port for the irccat instance"; + type = types.int; + default = 4722; + }; + + irccatChannel = mkOption { + description = "IRC channels to post to via irccat"; + type = types.str; + }; + }; + + config = lib.mkIf cfg.enable { + assertions = [{ + assertion = + cfg.dbHost != "localhost" || config.services.postgresql.enable; + message = "Panettone requires a postgresql database"; + } + { + assertion = + cfg.dbHost != "localhost" || config.services.postgresql.enableTCPIP; + message = "Panettone can only connect to the postgresql database over TCP"; + } + { + assertion = + cfg.dbHost != "localhost" || (lib.any + (user: user.name == cfg.dbUser) + config.services.postgresql.ensureUsers); + message = "Panettone requires a database user"; + } + { + assertion = + cfg.dbHost != "localhost" || (lib.any + (db: db == cfg.dbName) + config.services.postgresql.ensureDatabases); + message = "Panettone requires a database"; + }]; + + systemd.services.panettone = { + wantedBy = [ "multi-user.target" ]; + script = "${depot.web.panettone}/bin/panettone"; + + serviceConfig = { + DynamicUser = true; + Restart = "always"; + EnvironmentFile = cfg.secretsFile; + }; + + environment = { + PANETTONE_PORT = toString cfg.port; + PGHOST = "localhost"; + PGUSER = cfg.dbUser; + PGDATABASE = cfg.dbName; + IRCCATHOST = cfg.irccatHost; + IRCCATPORT = toString cfg.irccatPort; + ISSUECHANNEL = cfg.irccatChannel; + }; + }; + }; +} diff --git a/ops/modules/paroxysm.nix b/ops/modules/paroxysm.nix new file mode 100644 index 000000000000..070e7623db09 --- /dev/null +++ b/ops/modules/paroxysm.nix @@ -0,0 +1,28 @@ +{ depot, config, lib, pkgs, ... }: + +let + cfg = config.services.depot.paroxysm; + description = "TVL's majestic IRC bot"; +in +{ + options.services.depot.paroxysm.enable = lib.mkEnableOption description; + + config = lib.mkIf cfg.enable { + systemd.services.paroxysm = { + inherit description; + script = "${depot.fun.paroxysm}/bin/paroxysm"; + wantedBy = [ "multi-user.target" ]; + + environment = { + PARX_DATABASE_URL = "postgresql://tvldb:tvldb@localhost/tvldb"; + PARX_IRC_CONFIG_PATH = "/var/lib/paroxysm/irc.toml"; + }; + + serviceConfig = { + DynamicUser = true; + StateDirectory = "paroxysm"; + Restart = "always"; + }; + }; + }; +} diff --git a/ops/modules/prometheus-fail2ban-exporter.nix b/ops/modules/prometheus-fail2ban-exporter.nix new file mode 100644 index 000000000000..349364f9b7ed --- /dev/null +++ b/ops/modules/prometheus-fail2ban-exporter.nix @@ -0,0 +1,52 @@ +{ config, lib, pkgs, depot, ... }: + +let + cfg = config.services.prometheus-fail2ban-exporter; +in + +{ + options.services.prometheus-fail2ban-exporter = with lib; { + enable = mkEnableOption "Prometheus Fail2ban Exporter"; + + interval = mkOption { + description = "Systemd calendar expression for how often to run the interval"; + type = types.string; + default = "minutely"; + example = "hourly"; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services."prometheus-fail2ban-exporter" = { + wantedBy = [ "multi-user.target" ]; + after = [ "network.target" "fail2ban.service" ]; + serviceConfig = { + User = "root"; + Type = "oneshot"; + ExecStart = pkgs.writeShellScript "prometheus-fail2ban-exporter" '' + set -eo pipefail + mkdir -p /var/lib/prometheus/node-exporter + exec prometheus-fail2ban-exporter + ''; + }; + + path = [ + pkgs.fail2ban + depot.third_party.prometheus-fail2ban-exporter + ]; + }; + + systemd.timers."prometheus-fail2ban-exporter" = { + wantedBy = [ "multi-user.target" ]; + timerConfig.OnCalendar = cfg.interval; + }; + + services.prometheus.exporters.node = { + enabledCollectors = [ "textfile" ]; + + extraFlags = [ + "--collector.textfile.directory=/var/lib/prometheus/node-exporter" + ]; + }; + }; +} diff --git a/ops/modules/quassel.nix b/ops/modules/quassel.nix new file mode 100644 index 000000000000..275e2809d793 --- /dev/null +++ b/ops/modules/quassel.nix @@ -0,0 +1,79 @@ +# A more modern module for running Quassel. +{ config, lib, pkgs, ... }: + +let + cfg = config.services.depot.quassel; + quasselDaemon = pkgs.quassel.override { + monolithic = false; + enableDaemon = true; + withKDE = false; + }; +in +{ + options.services.depot.quassel = with lib; { + enable = mkEnableOption "Quassel IRC daemon"; + + acmeHost = mkOption { + description = "ACME host to use for the Quassel TLS certificate"; + type = lib.types.str; + }; + + bindAddresses = mkOption { + description = "Addresses Quassel will bind to/listen on"; + default = [ "127.0.0.1" ]; + }; + + logLevel = mkOption { + description = "Log level for Quassel Core"; + default = "Info"; + type = lib.types.enum [ + "Debug" + "Info" + "Warning" + "Error" + ]; + }; + + port = mkOption { + default = 6698; + description = '' + The port number the Quassel daemon will be listening to. + ''; + }; + }; + + config = with lib; mkIf cfg.enable { + networking.firewall.allowedTCPPorts = [ cfg.port ]; + + systemd.services.quassel = { + description = "Quassel IRC daemon"; + wantedBy = [ "multi-user.target" ]; + + script = concatStringsSep " " [ + "${quasselDaemon}/bin/quasselcore" + "--listen=${concatStringsSep "," cfg.bindAddresses}" + "--port=${toString cfg.port}" + "--configdir=/var/lib/quassel" + "--require-ssl" + "--ssl-cert=/var/lib/acme/${cfg.acmeHost}/full.pem" + "--loglevel=${cfg.logLevel}" + ]; + + serviceConfig = { + Restart = "always"; + User = "quassel"; + Group = "quassel"; + StateDirectory = "quassel"; + }; + }; + + users = { + users.quassel = { + isSystemUser = true; + group = "quassel"; + }; + + groups.quassel = { }; + }; + }; +} diff --git a/ops/modules/restic.nix b/ops/modules/restic.nix new file mode 100644 index 000000000000..869539603578 --- /dev/null +++ b/ops/modules/restic.nix @@ -0,0 +1,62 @@ +# Configure restic backups to S3-compatible storage, in our case +# GleSYS object storage. +# +# Conventions: +# - restic's cache lives in /var/backup/restic/cache +# - repository password lives in /var/backup/restic/secret +# - object storage credentials in /var/backup/restic/glesys-key +{ config, lib, pkgs, ... }: + +let + cfg = config.services.depot.restic; + description = "Restic backups to GleSYS"; + mkStringOption = default: lib.mkOption { + inherit default; + type = lib.types.str; + }; +in +{ + options.services.depot.restic = { + enable = lib.mkEnableOption description; + bucketEndpoint = mkStringOption "objects.dc-sto1.glesys.net"; + bucketName = mkStringOption "aged-resonance"; + bucketCredentials = mkStringOption "/var/backup/restic/glesys-key"; + repository = mkStringOption config.networking.hostName; + interval = mkStringOption "hourly"; + + paths = with lib; mkOption { + description = "Directories that should be backed up"; + type = types.listOf types.str; + }; + + exclude = with lib; mkOption { + description = "Files that should be excluded from backups"; + type = types.listOf types.str; + }; + }; + + config = lib.mkIf cfg.enable { + systemd.services.restic = { + description = "Backups to GleSYS"; + + script = "${pkgs.restic}/bin/restic backup ${lib.concatStringsSep " " cfg.paths}"; + + environment = { + RESTIC_REPOSITORY = "s3:${cfg.bucketEndpoint}/${cfg.bucketName}/${cfg.repository}"; + AWS_SHARED_CREDENTIALS_FILE = cfg.bucketCredentials; + RESTIC_PASSWORD_FILE = "/var/backup/restic/secret"; + RESTIC_CACHE_DIR = "/var/backup/restic/cache"; + + RESTIC_EXCLUDE_FILE = + builtins.toFile "exclude-files" (lib.concatStringsSep "\n" cfg.exclude); + }; + }; + + systemd.timers.restic = { + wantedBy = [ "multi-user.target" ]; + timerConfig.OnCalendar = cfg.interval; + }; + + environment.systemPackages = [ pkgs.restic ]; + }; +} diff --git a/ops/modules/smtprelay.nix b/ops/modules/smtprelay.nix new file mode 100644 index 000000000000..cfb185ecd107 --- /dev/null +++ b/ops/modules/smtprelay.nix @@ -0,0 +1,61 @@ +# NixOS module for configuring the simple SMTP relay. +{ depot, pkgs, config, lib, ... }: + +let + inherit (builtins) attrValues mapAttrs; + inherit (lib) + concatStringsSep + mkEnableOption + mkIf + mkOption + types + ; + + cfg = config.services.depot.smtprelay; + description = "Simple SMTP relay"; + + # Configuration values that are always overridden. + # + # - logging is pinned to stdout for journald compatibility + # - secret config is loaded through systemd's credential loading facility + overrideArgs = { + logfile = ""; + config = "$CREDENTIALS_DIRECTORY/secrets"; + }; + + # Creates the command line argument string for the service. + prepareArgs = args: + concatStringsSep " " + (attrValues (mapAttrs (key: value: "-${key} \"${toString value}\"") + (args // overrideArgs))); +in +{ + options.services.depot.smtprelay = { + enable = mkEnableOption description; + + args = mkOption { + type = types.attrsOf types.str; + description = "Key value pairs for command line arguments"; + }; + + secretsFile = mkOption { + type = types.str; + default = "/run/agenix/smtprelay"; + }; + }; + + config = mkIf cfg.enable { + systemd.services.smtprelay = { + inherit description; + script = "${depot.third_party.smtprelay}/bin/smtprelay ${prepareArgs cfg.args}"; + wantedBy = [ "multi-user.target" ]; + + serviceConfig = { + Restart = "always"; + StateDirectory = "smtprelay"; + DynamicUser = true; + LoadCredential = "secrets:${cfg.secretsFile}"; + }; + }; + }; +} diff --git a/ops/modules/sourcegraph.nix b/ops/modules/sourcegraph.nix new file mode 100644 index 000000000000..5311b42dd1db --- /dev/null +++ b/ops/modules/sourcegraph.nix @@ -0,0 +1,60 @@ +# Run sourcegraph, including its entire machinery, in a container. +# Running it outside of a container is a futile endeavour for now. +{ depot, config, pkgs, lib, ... }: + +let + cfg = config.services.depot.sourcegraph; +in +{ + options.services.depot.sourcegraph = with lib; { + enable = mkEnableOption "SourceGraph code search engine"; + + port = mkOption { + description = "Port on which SourceGraph should listen"; + type = types.int; + default = 3463; + }; + + cheddarPort = mkOption { + description = "Port on which cheddar should listen"; + type = types.int; + default = 4238; + }; + }; + + config = lib.mkIf cfg.enable { + # Run a cheddar syntax highlighting server + systemd.services.cheddar-server = { + wantedBy = [ "multi-user.target" ]; + script = "${depot.tools.cheddar}/bin/cheddar --listen 0.0.0.0:${toString cfg.cheddarPort} --sourcegraph-server"; + + serviceConfig = { + DynamicUser = true; + Restart = "always"; + }; + }; + + virtualisation.oci-containers.containers.sourcegraph = { + image = "sourcegraph/server:3.31.2"; + + ports = [ + "127.0.0.1:${toString cfg.port}:7080" + ]; + + volumes = [ + "/var/lib/sourcegraph/etc:/etc/sourcegraph" + "/var/lib/sourcegraph/data:/var/opt/sourcegraph" + ]; + + # TODO(tazjin): Figure out what changed in the protocol. + # environment.SRC_SYNTECT_SERVER = "http://172.17.0.1:${toString cfg.cheddarPort}"; + + # Sourcegraph needs a higher nofile limit, it logs warnings + # otherwise (unclear whether it actually affects the service). + extraOptions = [ + "--ulimit" + "nofile=10000:10000" + ]; + }; + }; +} diff --git a/ops/modules/tvl-buildkite.nix b/ops/modules/tvl-buildkite.nix new file mode 100644 index 000000000000..a6e7372a250a --- /dev/null +++ b/ops/modules/tvl-buildkite.nix @@ -0,0 +1,76 @@ +# Configuration for the TVL buildkite agents. +{ config, depot, pkgs, lib, ... }: + +let + cfg = config.services.depot.buildkite; + agents = lib.range 1 cfg.agentCount; + description = "Buildkite agents for TVL"; + + besadiiWithConfig = name: pkgs.writeShellScript "besadii-whitby" '' + export BESADII_CONFIG=/run/agenix/buildkite-besadii-config + exec -a ${name} ${depot.ops.besadii}/bin/besadii "$@" + ''; + + # All Buildkite hooks are actually besadii, but it's being invoked + # with different names. + buildkiteHooks = pkgs.runCommandNoCC "buildkite-hooks" { } '' + mkdir -p $out/bin + ln -s ${besadiiWithConfig "post-command"} $out/bin/post-command + ''; + + credentialHelper = pkgs.writeShellScriptBin "git-credential-gerrit-creds" '' + echo 'username=buildkite' + echo "password=$(jq -r '.gerritPassword' /run/agenix/buildkite-besadii-config)" + ''; +in +{ + options.services.depot.buildkite = { + enable = lib.mkEnableOption description; + agentCount = lib.mkOption { + type = lib.types.int; + description = "Number of Buildkite agents to launch"; + }; + }; + + config = lib.mkIf cfg.enable { + # Run the Buildkite agents using the default upstream module. + services.buildkite-agents = builtins.listToAttrs (map + (n: rec { + name = "whitby-${toString n}"; + value = { + inherit name; + enable = true; + tokenPath = "/run/agenix/buildkite-agent-token"; + hooks.post-command = "${buildkiteHooks}/bin/post-command"; + + runtimePackages = with pkgs; [ + bash + coreutils + credentialHelper + curl + git + gnutar + gzip + jq + nix + ]; + }; + }) + agents); + + # Set up a group for all Buildkite agent users + users = { + groups.buildkite-agents = { }; + users = builtins.listToAttrs (map + (n: rec { + name = "buildkite-agent-whitby-${toString n}"; + value = { + isSystemUser = true; + group = lib.mkForce "buildkite-agents"; + extraGroups = [ name "docker" ]; + }; + }) + agents); + }; + }; +} diff --git a/ops/modules/tvl-cache.nix b/ops/modules/tvl-cache.nix new file mode 100644 index 000000000000..4d574821df44 --- /dev/null +++ b/ops/modules/tvl-cache.nix @@ -0,0 +1,19 @@ +{ config, lib, pkgs, ... }: + +{ + options = { + tvl.cache.enable = lib.mkEnableOption "the TVL binary cache"; + }; + + config = lib.mkIf config.tvl.cache.enable { + nix = { + binaryCachePublicKeys = [ + "cache.tvl.su:kjc6KOMupXc1vHVufJUoDUYeLzbwSr9abcAKdn/U1Jk=" + ]; + + binaryCaches = [ + "https://cache.tvl.su" + ]; + }; + }; +} diff --git a/ops/modules/tvl-slapd/default.nix b/ops/modules/tvl-slapd/default.nix new file mode 100644 index 000000000000..d0d6616e224b --- /dev/null +++ b/ops/modules/tvl-slapd/default.nix @@ -0,0 +1,81 @@ +# Configures an OpenLDAP instance for TVL +# +# TODO(tazjin): Configure ldaps:// +{ depot, lib, pkgs, ... }: + +with depot.nix.yants; + +let + user = struct { + username = string; + email = string; + password = string; + displayName = option string; + }; + + toLdif = defun [ user string ] (u: '' + dn: cn=${u.username},ou=users,dc=tvl,dc=fyi + objectClass: organizationalPerson + objectClass: inetOrgPerson + sn: ${u.username} + cn: ${u.username} + displayName: ${u.displayName or u.username} + mail: ${u.email} + userPassword: ${u.password} + ''); + + inherit (depot.ops) users; + +in +{ + services.openldap = { + enable = true; + + settings.children = { + "olcDatabase={1}mdb".attrs = { + objectClass = [ "olcDatabaseConfig" "olcMdbConfig" ]; + olcDatabase = "{1}mdb"; + olcDbDirectory = "/var/lib/openldap"; + olcSuffix = "dc=tvl,dc=fyi"; + olcAccess = "to * by * read"; + olcRootDN = "cn=admin,dc=tvl,dc=fyi"; + olcRootPW = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$OfcgkOQ96VQ3aJj7NfA9vQ$oS6HQOkYl/bUYg4SejpltQYy7kvqx/RUxvoR4zo1vXU"; + }; + + "cn=module{0}".attrs = { + objectClass = "olcModuleList"; + olcModuleLoad = "pw-argon2"; + }; + + "cn=schema".includes = + map (schema: "${pkgs.openldap}/etc/schema/${schema}.ldif") + [ "core" "cosine" "inetorgperson" "nis" ]; + }; + + # Contents are immutable at runtime, and adding user accounts etc. + # is done statically in the LDIF-formatted contents in this folder. + declarativeContents."dc=tvl,dc=fyi" = '' + dn: dc=tvl,dc=fyi + dc: tvl + o: TVL LDAP server + description: Root entry for tvl.fyi + objectClass: top + objectClass: dcObject + objectClass: organization + + dn: ou=users,dc=tvl,dc=fyi + ou: users + description: All users in TVL + objectClass: top + objectClass: organizationalUnit + + dn: ou=groups,dc=tvl,dc=fyi + ou: groups + description: All groups in TVL + objectClass: top + objectClass: organizationalUnit + + ${lib.concatStringsSep "\n" (map toLdif users)} + ''; + }; +} diff --git a/ops/modules/tvl-users.nix b/ops/modules/tvl-users.nix new file mode 100644 index 000000000000..988b9eed8af6 --- /dev/null +++ b/ops/modules/tvl-users.nix @@ -0,0 +1,94 @@ +# Standard NixOS users for TVL machines, as well as configuration that +# should following along when they are added to a machine. +{ depot, pkgs, ... }: + +{ + users = { + users.tazjin = { + isNormalUser = true; + extraGroups = [ "git" "wheel" ]; + shell = pkgs.fish; + openssh.authorizedKeys.keys = depot.users.tazjin.keys.all; + }; + + users.lukegb = { + isNormalUser = true; + extraGroups = [ "git" "wheel" ]; + openssh.authorizedKeys.keys = depot.users.lukegb.keys.all; + }; + + users.grfn = { + isNormalUser = true; + extraGroups = [ "git" "wheel" ]; + openssh.authorizedKeys.keys = [ + depot.users.grfn.keys.whitby + ]; + }; + + users.edef = { + isNormalUser = true; + extraGroups = [ "git" ]; + openssh.authorizedKeys.keys = depot.users.edef.keys.all; + }; + + users.qyliss = { + isNormalUser = true; + extraGroups = [ "git" ]; + openssh.authorizedKeys.keys = depot.users.qyliss.keys.all; + }; + + users.eta = { + isNormalUser = true; + extraGroups = [ "git" ]; + openssh.authorizedKeys.keys = depot.users.eta.keys.whitby; + }; + + users.cynthia = { + isNormalUser = true; # I'm normal OwO :3 + extraGroups = [ "git" ]; + openssh.authorizedKeys.keys = depot.users.cynthia.keys.all; + }; + + users.firefly = { + isNormalUser = true; + extraGroups = [ "git" ]; + openssh.authorizedKeys.keys = depot.users.firefly.keys.whitby; + }; + + users.sterni = { + isNormalUser = true; + extraGroups = [ "git" "wheel" ]; + openssh.authorizedKeys.keys = depot.users.sterni.keys.all; + }; + + users.flokli = { + isNormalUser = true; + extraGroups = [ "git" ]; + openssh.authorizedKeys.keys = depot.users.flokli.keys.all; + }; + + # Temporarily disabled (inactive) users. + users.isomer = { + isNormalUser = true; + extraGroups = [ "git" ]; + shell = "${pkgs.shadow}/bin/nologin"; + openssh.authorizedKeys.keys = depot.users.isomer.keys.all; + }; + + users.riking = { + isNormalUser = true; + extraGroups = [ "git" ]; + shell = "${pkgs.shadow}/bin/nologin"; + openssh.authorizedKeys.keys = depot.users.riking.keys.u2f ++ depot.users.riking.keys.passworded; + }; + }; + + environment.systemPackages = with pkgs; [ + alacritty.terminfo + foot.terminfo + rxvt_unicode.terminfo + + # TODO(sterni): re-enable when the kitty build is fixed upstreams + # kitty.terminfo + ]; +} diff --git a/ops/modules/v4l2loopback.nix b/ops/modules/v4l2loopback.nix new file mode 100644 index 000000000000..636b2ff6cf27 --- /dev/null +++ b/ops/modules/v4l2loopback.nix @@ -0,0 +1,12 @@ +{ config, lib, pkgs, ... }: + +{ + boot = { + extraModulePackages = [ config.boot.kernelPackages.v4l2loopback ]; + kernelModules = [ "v4l2loopback" ]; + extraModprobeConfig = '' + options v4l2loopback exclusive_caps=1 + ''; + }; +} + diff --git a/ops/modules/www/atward.tvl.fyi.nix b/ops/modules/www/atward.tvl.fyi.nix new file mode 100644 index 000000000000..6b3672dd75cb --- /dev/null +++ b/ops/modules/www/atward.tvl.fyi.nix @@ -0,0 +1,33 @@ +# Serve atward, the query redirection ... thing. +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + # Short link support (i.e. plain http://at) for users with a + # configured tvl.fyi/tvl.su search domain. + services.nginx.virtualHosts."at-shortlink" = { + serverName = "at"; + extraConfig = "return 302 https://atward.tvl.fyi$request_uri;"; + }; + + services.nginx.virtualHosts."atward" = { + serverName = "atward.tvl.fyi"; + enableACME = true; + forceSSL = true; + + serverAliases = [ + "atward.tvl.su" + "at.tvl.fyi" + "at.tvl.su" + ]; + + locations."/" = { + proxyPass = "http://localhost:${toString config.services.depot.atward.port}"; + }; + }; + }; +} diff --git a/ops/modules/www/auth.tvl.fyi.nix b/ops/modules/www/auth.tvl.fyi.nix new file mode 100644 index 000000000000..e0c031bf700c --- /dev/null +++ b/ops/modules/www/auth.tvl.fyi.nix @@ -0,0 +1,24 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."auth.tvl.fyi" = { + serverName = "auth.tvl.fyi"; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location / { + proxy_pass http://localhost:${config.services.keycloak.httpPort}; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto https; + proxy_set_header Host $host; + } + ''; + }; + }; +} diff --git a/ops/modules/www/b.tvl.fyi.nix b/ops/modules/www/b.tvl.fyi.nix new file mode 100644 index 000000000000..45f6c6ed5141 --- /dev/null +++ b/ops/modules/www/b.tvl.fyi.nix @@ -0,0 +1,32 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."b-shortlink" = { + serverName = "b"; + extraConfig = "return 302 https://b.tvl.fyi$request_uri;"; + }; + + services.nginx.virtualHosts."b.tvl.fyi" = { + serverName = "b.tvl.fyi"; + serverAliases = [ "b.tvl.su" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + # Forward short links to issues to the issue itself (b/32) + location ~ ^/(\d+)$ { + return 302 https://b.tvl.fyi/issues$request_uri; + } + + location / { + proxy_pass http://localhost:${toString config.services.depot.panettone.port}; + } + ''; + }; + }; +} diff --git a/ops/modules/www/base.nix b/ops/modules/www/base.nix new file mode 100644 index 000000000000..50fceff0fa40 --- /dev/null +++ b/ops/modules/www/base.nix @@ -0,0 +1,41 @@ +{ config, pkgs, ... }: + +{ + config = { + security.acme = { + acceptTerms = true; + defaults.email = "letsencrypt@tvl.su"; + }; + + services.nginx = { + enable = true; + enableReload = true; + + recommendedTlsSettings = true; + recommendedGzipSettings = true; + recommendedProxySettings = true; + + commonHttpConfig = '' + log_format json_combined escape=json + '{' + '"remote_addr":"$remote_addr",' + '"method":"$request_method",' + '"host":"$host",' + '"uri":"$request_uri",' + '"status":$status,' + '"request_size":$request_length,' + '"response_size":$body_bytes_sent,' + '"response_time":$request_time,' + '"referrer":"$http_referer",' + '"user_agent":"$http_user_agent"' + '}'; + + access_log syslog:server=unix:/dev/log,nohostname json_combined; + ''; + + appendHttpConfig = '' + add_header Permissions-Policy "interest-cohort=()"; + ''; + }; + }; +} diff --git a/ops/modules/www/cache.tvl.su.nix b/ops/modules/www/cache.tvl.su.nix new file mode 100644 index 000000000000..99bc008cd6a5 --- /dev/null +++ b/ops/modules/www/cache.tvl.su.nix @@ -0,0 +1,31 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."cache.tvl.su" = { + serverName = "cache.tvl.su"; + serverAliases = [ "cache.tvl.fyi" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location = /cache-key.pub { + alias /run/agenix/nix-cache-pub; + } + + location = /nix-cache-info { + add_header Content-Type text/plain; + return 200 "StoreDir: /nix/store\nWantMassQuery: 1\nPriority: 50\n"; + } + + location / { + proxy_pass http://localhost:${toString config.services.nix-serve.port}; + } + ''; + }; + }; +} diff --git a/ops/modules/www/cl.tvl.fyi.nix b/ops/modules/www/cl.tvl.fyi.nix new file mode 100644 index 000000000000..470122c395ea --- /dev/null +++ b/ops/modules/www/cl.tvl.fyi.nix @@ -0,0 +1,30 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."cl-shortlink" = { + serverName = "cl"; + extraConfig = "return 302 https://cl.tvl.fyi$request_uri;"; + }; + + services.nginx.virtualHosts.gerrit = { + serverName = "cl.tvl.fyi"; + serverAliases = [ "cl.tvl.su" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location / { + proxy_pass http://localhost:4778; + proxy_set_header X-Forwarded-For $remote_addr; + # The :443 suffix is a workaround for https://b.tvl.fyi/issues/88. + proxy_set_header Host $host:443; + } + ''; + }; + }; +} diff --git a/ops/modules/www/code.tvl.fyi.nix b/ops/modules/www/code.tvl.fyi.nix new file mode 100644 index 000000000000..3f34a9422cb1 --- /dev/null +++ b/ops/modules/www/code.tvl.fyi.nix @@ -0,0 +1,45 @@ +{ depot, config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts.cgit = { + serverName = "code.tvl.fyi"; + serverAliases = [ "code.tvl.su" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + # Serve the rendered Tvix component SVG. + # + # TODO(tazjin): Implement a way of serving this dynamically + location = /about/tvix/docs/component-flow.svg { + alias ${depot.tvix.docs.svg}/component-flow.svg; + } + + # Git operations on depot.git hit josh + location /depot.git { + proxy_pass http://localhost:${toString config.services.depot.josh.port}; + } + + # Git clone operations on '/' should be redirected to josh now. + location = /info/refs { + return 302 https://code.tvl.fyi/depot.git/info/refs$is_args$args; + } + + # Static assets must always hit the root. + location ~ ^/(favicon\.ico|cgit\.(css|png))$ { + proxy_pass http://localhost:2448; + } + + # Everything else is forwarded to cgit for the web view + location / { + proxy_pass http://localhost:2448/cgit.cgi/depot/; + } + ''; + }; + }; +} diff --git a/ops/modules/www/cs.tvl.fyi.nix b/ops/modules/www/cs.tvl.fyi.nix new file mode 100644 index 000000000000..fac814baf064 --- /dev/null +++ b/ops/modules/www/cs.tvl.fyi.nix @@ -0,0 +1,31 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."cs.tvl.fyi" = { + serverName = "cs.tvl.fyi"; + serverAliases = [ "cs.tvl.su" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location = / { + return 301 https://cs.tvl.fyi/depot; + } + + location / { + proxy_set_header X-Sg-Auth "Anonymous"; + proxy_pass http://localhost:${toString config.services.depot.sourcegraph.port}; + } + + location /users/Anonymous/settings { + return 301 https://cs.tvl.fyi; + } + ''; + }; + }; +} diff --git a/ops/modules/www/deploys.tvl.fyi.nix b/ops/modules/www/deploys.tvl.fyi.nix new file mode 100644 index 000000000000..ffbe225b58a3 --- /dev/null +++ b/ops/modules/www/deploys.tvl.fyi.nix @@ -0,0 +1,22 @@ +{ pkgs, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + # Ensure the directory for deployment diffs exists. + systemd.tmpfiles.rules = [ + "d /var/html/deploys.tvl.fyi/diff 0755 nginx nginx -" + ]; + + services.nginx.virtualHosts."deploys.tvl.fyi" = { + enableACME = true; + forceSSL = true; + root = "/var/html/deploys.tvl.fyi"; + }; + + services.depot.restic.paths = [ "/var/html/deploys.tvl.fyi" ]; + }; +} diff --git a/ops/modules/www/images.tvl.fyi.nix b/ops/modules/www/images.tvl.fyi.nix new file mode 100644 index 000000000000..7d027b2991ab --- /dev/null +++ b/ops/modules/www/images.tvl.fyi.nix @@ -0,0 +1,22 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."images.tvl.fyi" = { + serverName = "images.tvl.fyi"; + serverAliases = [ "images.tvl.su" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location / { + proxy_pass http://localhost:${toString config.services.depot.nixery.port}; + } + ''; + }; + }; +} diff --git a/ops/modules/www/nixery.dev.nix b/ops/modules/www/nixery.dev.nix new file mode 100644 index 000000000000..05dc88c66a07 --- /dev/null +++ b/ops/modules/www/nixery.dev.nix @@ -0,0 +1,21 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."nixery.dev" = { + serverName = "nixery.dev"; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location / { + proxy_pass http://localhost:${toString config.services.depot.nixery.port}; + } + ''; + }; + }; +} diff --git a/ops/modules/www/self-redirect.nix b/ops/modules/www/self-redirect.nix new file mode 100644 index 000000000000..5bf1627be99a --- /dev/null +++ b/ops/modules/www/self-redirect.nix @@ -0,0 +1,27 @@ +# Redirect the hostname of a machine to its configuration in a web +# browser. +# +# Works by convention, assuming that the machine has its configuration +# at //ops/machines/${hostname}. +{ config, ... }: + +let + host = "${config.networking.hostName}.${config.networking.domain}"; +in +{ + imports = [ + ./base.nix + ]; + + config.services.nginx.virtualHosts."${host}" = { + serverName = host; + addSSL = true; # SSL is not forced on these redirects + enableACME = true; + + extraConfig = '' + location = / { + return 302 https://at.tvl.fyi/?q=%2F%2Fops%2Fmachines%2F${config.networking.hostName}; + } + ''; + }; +} diff --git a/ops/modules/www/static.tvl.fyi.nix b/ops/modules/www/static.tvl.fyi.nix new file mode 100644 index 000000000000..7312f78ecf42 --- /dev/null +++ b/ops/modules/www/static.tvl.fyi.nix @@ -0,0 +1,42 @@ +# Host the static assets at static.tvl.fyi +# +# All assets are served from $base/$drvhash/$file, but can also be +# included with `latest/` which will return a (non-permanent!) +# redirect to the real location. +# +# For all purposes within depot, using the drvhash of web.static is +# recommended. +{ depot, pkgs, ... }: + +let staticHash = depot.web.static.drvHash; +in { + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."static.tvl.fyi" = { + serverAliases = [ "static.tvl.su" ]; + enableACME = true; + forceSSL = true; + + extraConfig = '' + location = / { + add_header Content-Type text/plain; + return 200 "looking for tvl.fyi or tvl.su?"; + } + + location /latest { + rewrite ^/latest/(.*) /${staticHash}/$1 redirect; + } + + location /${staticHash}/ { + alias ${depot.web.static}/; + expires max; + add_header Access-Control-Allow-Origin "*"; + add_header Cache-Control "public"; + } + ''; + }; + }; +} diff --git a/ops/modules/www/status.tvl.su.nix b/ops/modules/www/status.tvl.su.nix new file mode 100644 index 000000000000..2bb6093c1472 --- /dev/null +++ b/ops/modules/www/status.tvl.su.nix @@ -0,0 +1,25 @@ +{ config, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."status-fyi" = { + serverName = "status.tvl.fyi"; + enableACME = true; + extraConfig = "return 302 https://status.tvl.su$request_uri;"; + }; + + services.nginx.virtualHosts.grafana = { + serverName = "status.tvl.su"; + enableACME = true; + forceSSL = true; + + locations."/" = { + proxyPass = "http://localhost:${toString config.services.grafana.port}"; + }; + }; + }; +} diff --git a/ops/modules/www/tazj.in.nix b/ops/modules/www/tazj.in.nix new file mode 100644 index 000000000000..7d658a5ec4c1 --- /dev/null +++ b/ops/modules/www/tazj.in.nix @@ -0,0 +1,40 @@ +# serve tazjin's website & blog +{ depot, config, lib, pkgs, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."tazj.in" = { + enableACME = true; + forceSSL = true; + root = depot.users.tazjin.homepage; + + extraConfig = '' + ${depot.users.tazjin.blog.oldRedirects} + location /blog/ { + alias ${depot.users.tazjin.blog.rendered}/; + + if ($request_uri ~ ^/(.*)\.html$) { + return 302 /$1; + } + + try_files $uri $uri.html $uri/ =404; + } + + # Temporary place for serving static files. + location /blobs/ { + alias /var/lib/tazjins-blobs/; + } + ''; + }; + + services.nginx.virtualHosts."git.tazj.in" = { + enableACME = true; + forceSSL = true; + extraConfig = "return 301 https://code.tvl.fyi$request_uri;"; + }; + }; +} diff --git a/ops/modules/www/todo.tvl.fyi.nix b/ops/modules/www/todo.tvl.fyi.nix new file mode 100644 index 000000000000..b53f5437e7ab --- /dev/null +++ b/ops/modules/www/todo.tvl.fyi.nix @@ -0,0 +1,25 @@ +{ depot, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."todo.tvl.fyi" = { + serverName = "todo.tvl.fyi"; + serverAliases = [ "todo.tvl.su" ]; + root = depot.web.todolist; + enableACME = true; + forceSSL = true; + + extraConfig = '' + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + + location ~* \.(webp|woff2)$ { + add_header Cache-Control "public, max-age=31536000"; + } + ''; + }; + }; +} diff --git a/ops/modules/www/tvl.fyi.nix b/ops/modules/www/tvl.fyi.nix new file mode 100644 index 000000000000..59ee1bc27f1a --- /dev/null +++ b/ops/modules/www/tvl.fyi.nix @@ -0,0 +1,47 @@ +{ depot, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."tvl.fyi" = { + serverName = "tvl.fyi"; + root = depot.web.tvl; + enableACME = true; + forceSSL = true; + + extraConfig = '' + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + + rewrite ^/builds/?$ https://buildkite.com/tvl/depot/ last; + + rewrite ^/monorepo-doc/?$ https://docs.google.com/document/d/1nnyByXcH0F6GOmEezNOUa2RFelpeRpDToBLYD_CtjWE/edit?usp=sharing last; + + rewrite ^/irc/?$ ircs://irc.hackint.org:6697/#tvl last; + rewrite ^/webchat/?$ https://webirc.hackint.org/#ircs://irc.hackint.org/#tvl last; + + location ~* \.(webp|woff2)$ { + add_header Cache-Control "public, max-age=31536000"; + } + + location /blog { + if ($request_uri ~ ^/(.*)\.html$) { + return 302 /$1; + } + + try_files $uri $uri.html $uri/ =404; + } + + location = /blog { + return 302 /#blog; + } + + location = /blog/ { + return 302 /#blog; + } + ''; + }; + }; +} diff --git a/ops/modules/www/tvl.su.nix b/ops/modules/www/tvl.su.nix new file mode 100644 index 000000000000..a7c4f6a21721 --- /dev/null +++ b/ops/modules/www/tvl.su.nix @@ -0,0 +1,20 @@ +{ depot, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."tvl.su" = { + serverName = "tvl.su"; + root = depot.corp.website; + enableACME = true; + forceSSL = true; + + extraConfig = '' + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + ''; + }; + }; +} diff --git a/ops/modules/www/wigglydonke.rs.nix b/ops/modules/www/wigglydonke.rs.nix new file mode 100644 index 000000000000..3d85e4eb9843 --- /dev/null +++ b/ops/modules/www/wigglydonke.rs.nix @@ -0,0 +1,15 @@ +{ depot, lib, pkgs, ... }: + +{ + imports = [ + ./base.nix + ]; + + config = { + services.nginx.virtualHosts."wigglydonke.rs" = { + enableACME = true; + forceSSL = true; + root = "${depot.path + "/users/grfn/wigglydonke.rs"}"; + }; + }; +} diff --git a/ops/mq_cli/.gitignore b/ops/mq_cli/.gitignore new file mode 100644 index 000000000000..5bd19a47c3b3 --- /dev/null +++ b/ops/mq_cli/.gitignore @@ -0,0 +1,4 @@ +/target/ +**/*.rs.bk +.idea/ +*.iml diff --git a/ops/mq_cli/CODE_OF_CONDUCT.md b/ops/mq_cli/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..c4013ac13ebc --- /dev/null +++ b/ops/mq_cli/CODE_OF_CONDUCT.md @@ -0,0 +1,20 @@ +A SERMON ON ETHICS AND LOVE +=========================== + +One day Mal-2 asked the messenger spirit Saint Gulik to approach the Goddess and request Her presence for some desperate advice. Shortly afterwards the radio came on by itself, and an ethereal female Voice said **YES?** + +"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord! Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a heavy burden from my heart!" + +**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.** + +"I am filled with fear and tormented with terrible visions of pain. Everywhere people are hurting one another, the planet is rampant with injustices, whole societies plunder groups of their own people, mothers imprison sons, children perish while brothers war. O, woe." + +**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?** + +"But nobody Wants it! Everybody hates it." + +**OH. WELL, THEN *STOP*.** + +At which moment She turned herself into an aspirin commercial and left The Polyfather stranded alone with his species. + +SINISTER DEXTER HAS A BROKEN SPIROMETER. diff --git a/ops/mq_cli/Cargo.lock b/ops/mq_cli/Cargo.lock new file mode 100644 index 000000000000..18fed3621d4d --- /dev/null +++ b/ops/mq_cli/Cargo.lock @@ -0,0 +1,168 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "ansi_term" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" +dependencies = [ + "winapi", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "cc" +version = "1.0.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22a9137b95ea06864e018375b72adfb7db6e6f68cfc8df5a04d00288050485ee" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "2.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" +dependencies = [ + "ansi_term", + "atty", + "bitflags", + "strsim", + "textwrap", + "unicode-width", + "vec_map", +] + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "libc" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e74d72e0f9b65b5b4ca49a346af3976df0f9c61d550727f349ecd559f251a26c" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mq_cli" +version = "3773.0.0" +dependencies = [ + "clap", + "libc", + "nix", + "posix_mq", +] + +[[package]] +name = "nix" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6" +dependencies = [ + "bitflags", + "cc", + "cfg-if", + "libc", + "memoffset", +] + +[[package]] +name = "posix_mq" +version = "3771.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f462ad79a99ea13f3ef76d9c271956e924183f5aeb67a8649c8c2b6bdd079da8" +dependencies = [ + "libc", + "nix", +] + +[[package]] +name = "strsim" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" + +[[package]] +name = "textwrap" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "unicode-width" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" + +[[package]] +name = "vec_map" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/ops/mq_cli/Cargo.toml b/ops/mq_cli/Cargo.toml new file mode 100644 index 000000000000..816a37075977 --- /dev/null +++ b/ops/mq_cli/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "mq_cli" +description = "CLI tool for accessing POSIX message queues (mq_overview(7))" +license = "MIT" +version = "3773.0.0" +authors = ["Vincent Ambo <tazjin@tvl.su>"] +homepage = "https://cs.tvl.fyi/depot/-/tree/ops/mq_cli" +repository = "https://code.tvl.fyi/depot.git:/ops/mq_cli.git" + +[dependencies] +clap = "2.34" +libc = "0.2" +nix = "0.23" +posix_mq = "3771.0.0" diff --git a/ops/mq_cli/LICENSE b/ops/mq_cli/LICENSE new file mode 100644 index 000000000000..e289cbab81e0 --- /dev/null +++ b/ops/mq_cli/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2017-2018 Langler AS +Copyright (c) 2019-2020 Vincent Ambo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ops/mq_cli/README.md b/ops/mq_cli/README.md new file mode 100644 index 000000000000..1045de896b02 --- /dev/null +++ b/ops/mq_cli/README.md @@ -0,0 +1,42 @@ +mq-cli +====== + +This project provides a very simple CLI interface to [POSIX message queues][]. + +It can be used to create and inspect queues, as well as send and +receive messages from them. + +``` +1.0.0 +Administrate and inspect POSIX message queues + +USAGE: + mq <SUBCOMMAND> + +FLAGS: + -h, --help Prints help information + -V, --version Prints version information + +SUBCOMMANDS: + create Create a new queue + help Prints this message or the help of the given subcommand(s) + inspect inspect details about a queue + ls list message queues + receive Receive a message from a queue + rlimit Get the message queue rlimit + send Send a message to a queue +``` + +## Development + +Development happens in the [TVL +monorepo](https://cs.tvl.fyi/depot/-/tree/ops/mq_cli). + +Starting from version `3773.0.0`, the version numbers correspond to +_revisions_ of the TVL repository, available as git refs (e.g. +`refs/r/3773`). + +See the TVL documentation for more information about how to contribute +to the codebase. + +[POSIX message queues]: https://linux.die.net/man/7/mq_overview diff --git a/ops/mq_cli/default.nix b/ops/mq_cli/default.nix new file mode 100644 index 000000000000..6b0e32009a66 --- /dev/null +++ b/ops/mq_cli/default.nix @@ -0,0 +1,3 @@ +{ depot, ... }: + +depot.third_party.naersk.buildPackage ./. diff --git a/ops/mq_cli/src/main.rs b/ops/mq_cli/src/main.rs new file mode 100644 index 000000000000..927993b486ad --- /dev/null +++ b/ops/mq_cli/src/main.rs @@ -0,0 +1,235 @@ +extern crate clap; +extern crate libc; +extern crate nix; +extern crate posix_mq; + +use clap::{App, AppSettings, Arg, ArgMatches, SubCommand}; +use posix_mq::{Message, Name, Queue}; +use std::fs::{read_dir, File}; +use std::io::{self, Read, Write}; +use std::process::exit; + +fn run_ls() { + let mqueues = read_dir("/dev/mqueue").expect("Could not read message queues"); + + for queue in mqueues { + let path = queue.unwrap().path(); + let status = { + let mut file = File::open(&path).expect("Could not open queue file"); + + let mut content = String::new(); + file.read_to_string(&mut content) + .expect("Could not read queue file"); + + content + }; + + let queue_name = path + .components() + .last() + .unwrap() + .as_os_str() + .to_string_lossy(); + + println!("/{}: {}", queue_name, status) + } +} + +fn run_inspect(queue_name: &str) { + let name = Name::new(queue_name).expect("Invalid queue name"); + let queue = Queue::open(name).expect("Could not open queue"); + + println!("Queue {}:\n", queue_name); + println!("Max. message size: {} bytes", queue.max_size()); + println!("Max. # of pending messages: {}", queue.max_pending()); +} + +fn run_create(cmd: &ArgMatches) { + if let Some(rlimit) = cmd.value_of("rlimit") { + set_rlimit(rlimit.parse().expect("Invalid rlimit value")); + } + + let name = Name::new(cmd.value_of("queue").unwrap()).expect("Invalid queue name"); + + let max_pending: i64 = cmd.value_of("max-pending").unwrap().parse().unwrap(); + let max_size: i64 = cmd.value_of("max-size").unwrap().parse().unwrap(); + + let queue = Queue::create(name, max_pending, max_size * 1024); + + match queue { + Ok(_) => println!("Queue created successfully"), + Err(e) => { + writeln!(io::stderr(), "Could not create queue: {}", e).ok(); + exit(1); + } + }; +} + +fn run_receive(queue_name: &str) { + let name = Name::new(queue_name).expect("Invalid queue name"); + let queue = Queue::open(name).expect("Could not open queue"); + + let message = match queue.receive() { + Ok(msg) => msg, + Err(e) => { + writeln!(io::stderr(), "Failed to receive message: {}", e).ok(); + exit(1); + } + }; + + // Attempt to write the message out as a string, but write out raw bytes if it turns out to not + // be UTF-8 encoded data. + match String::from_utf8(message.data.clone()) { + Ok(string) => println!("{}", string), + Err(_) => { + writeln!(io::stderr(), "Message not UTF-8 encoded!").ok(); + io::stdout().write(message.data.as_ref()).ok(); + } + }; +} + +fn run_send(queue_name: &str, content: &str) { + let name = Name::new(queue_name).expect("Invalid queue name"); + let queue = Queue::open(name).expect("Could not open queue"); + + let message = Message { + data: content.as_bytes().to_vec(), + priority: 0, + }; + + match queue.send(&message) { + Ok(_) => (), + Err(e) => { + writeln!(io::stderr(), "Could not send message: {}", e).ok(); + exit(1); + } + } +} + +fn run_rlimit() { + let mut rlimit = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + + let mut errno = 0; + unsafe { + let res = libc::getrlimit(libc::RLIMIT_MSGQUEUE, &mut rlimit); + if res != 0 { + errno = nix::errno::errno(); + } + }; + + if errno != 0 { + writeln!( + io::stderr(), + "Could not get message queue rlimit: {}", + errno + ) + .ok(); + } else { + println!("Message queue rlimit:"); + println!("Current limit: {}", rlimit.rlim_cur); + println!("Maximum limit: {}", rlimit.rlim_max); + } +} + +fn set_rlimit(new_limit: u64) { + let rlimit = libc::rlimit { + rlim_cur: new_limit, + rlim_max: new_limit, + }; + + let mut errno: i32 = 0; + unsafe { + let res = libc::setrlimit(libc::RLIMIT_MSGQUEUE, &rlimit); + if res != 0 { + errno = nix::errno::errno(); + } + } + + match errno { + 0 => println!("Set RLIMIT_MSGQUEUE hard limit to {}", new_limit), + _ => { + // Not mapping these error codes to messages for now, the user can + // look up the meaning in setrlimit(2). + panic!("Could not set hard limit: {}", errno); + } + }; +} + +fn main() { + let ls = SubCommand::with_name("ls").about("list message queues"); + + let queue_arg = Arg::with_name("queue").required(true).takes_value(true); + + let rlimit_arg = Arg::with_name("rlimit") + .help("RLIMIT_MSGQUEUE to set for this command") + .long("rlimit") + .takes_value(true); + + let inspect = SubCommand::with_name("inspect") + .about("inspect details about a queue") + .arg(&queue_arg); + + let create = SubCommand::with_name("create") + .about("Create a new queue") + .arg(&queue_arg) + .arg(&rlimit_arg) + .arg( + Arg::with_name("max-size") + .help("maximum message size (in kB)") + .long("max-size") + .required(true) + .takes_value(true), + ) + .arg( + Arg::with_name("max-pending") + .help("maximum # of pending messages") + .long("max-pending") + .required(true) + .takes_value(true), + ); + + let receive = SubCommand::with_name("receive") + .about("Receive a message from a queue") + .arg(&queue_arg); + + let send = SubCommand::with_name("send") + .about("Send a message to a queue") + .arg(&queue_arg) + .arg( + Arg::with_name("message") + .help("the message to send") + .required(true), + ); + + let rlimit = SubCommand::with_name("rlimit") + .about("Get the message queue rlimit") + .setting(AppSettings::SubcommandRequiredElseHelp); + + let matches = App::new("mq") + .setting(AppSettings::SubcommandRequiredElseHelp) + .version("1.0.0") + .about("Administrate and inspect POSIX message queues") + .subcommand(ls) + .subcommand(inspect) + .subcommand(create) + .subcommand(receive) + .subcommand(send) + .subcommand(rlimit) + .get_matches(); + + match matches.subcommand() { + ("ls", _) => run_ls(), + ("inspect", Some(cmd)) => run_inspect(cmd.value_of("queue").unwrap()), + ("create", Some(cmd)) => run_create(cmd), + ("receive", Some(cmd)) => run_receive(cmd.value_of("queue").unwrap()), + ("send", Some(cmd)) => run_send( + cmd.value_of("queue").unwrap(), + cmd.value_of("message").unwrap(), + ), + ("rlimit", _) => run_rlimit(), + _ => unimplemented!(), + } +} diff --git a/ops/nixos.nix b/ops/nixos.nix new file mode 100644 index 000000000000..291413c5b587 --- /dev/null +++ b/ops/nixos.nix @@ -0,0 +1,55 @@ +# Helper functions for instantiating depot-compatible NixOS machines. +{ depot, lib, pkgs, ... }@args: + +let inherit (lib) findFirst isAttrs; +in rec { + # This provides our standard set of arguments to all NixOS modules. + baseModule = { ... }: { + # Ensure that pkgs == third_party.nix + nixpkgs.pkgs = depot.third_party.nixpkgs; + nix.nixPath = [ + "nixos=${pkgs.path}" + "nixpkgs=${pkgs.path}" + ]; + }; + + nixosFor = configuration: (depot.third_party.nixos { + configuration = { ... }: { + imports = [ + baseModule + configuration + ]; + }; + + specialArgs = { + inherit (args) depot; + }; + }); + + findSystem = hostname: + (findFirst + (system: system.config.networking.hostName == hostname) + (throw "${hostname} is not a known NixOS host") + (map nixosFor depot.ops.machines.all-systems)); + + rebuild-system = rebuildSystemWith depot.path; + + rebuildSystemWith = depotPath: pkgs.writeShellScriptBin "rebuild-system" '' + set -ue + if [[ $EUID -ne 0 ]]; then + echo "Oh no! Only root is allowed to rebuild the system!" >&2 + exit 1 + fi + + echo "Rebuilding NixOS for $HOSTNAME" + system=$(${pkgs.nix}/bin/nix-build -E "((import ${depotPath} {}).ops.nixos.findSystem \"$HOSTNAME\").system" --no-out-link --show-trace) + + ${pkgs.nix}/bin/nix-env -p /nix/var/nix/profiles/system --set $system + $system/bin/switch-to-configuration switch + ''; + + # Systems that should be built in CI + whitbySystem = (nixosFor depot.ops.machines.whitby).system; + sandunySystem = (nixosFor depot.ops.machines.sanduny).system; + meta.ci.targets = [ "sandunySystem" "whitbySystem" ]; +} diff --git a/ops/pipelines/README.md b/ops/pipelines/README.md new file mode 100644 index 000000000000..a3f94fd23143 --- /dev/null +++ b/ops/pipelines/README.md @@ -0,0 +1,5 @@ +This folder contains the dynamic configuration for our [Buildkite CI +setup](https://tvl.fyi/builds). + +The configuration is built and dynamically loaded by Buildkite at the start of +each CI pipeline. diff --git a/ops/pipelines/depot.nix b/ops/pipelines/depot.nix new file mode 100644 index 000000000000..6d9e625e04be --- /dev/null +++ b/ops/pipelines/depot.nix @@ -0,0 +1,49 @@ +# This file configures the primary build pipeline used for the +# top-level list of depot targets. +{ depot, pkgs, externalArgs, ... }: + +let + # Protobuf check step which validates that changes to .proto files + # between revisions don't cause backwards-incompatible or otherwise + # flawed changes. + protoCheck = { + command = "${depot.nix.bufCheck}/bin/ci-buf-check"; + label = ":water_buffalo:"; + }; + + pipeline = depot.nix.buildkite.mkPipeline { + headBranch = "refs/heads/canon"; + drvTargets = depot.ci.targets; + additionalSteps = [ protoCheck ]; + + parentTargetMap = + if (externalArgs ? parentTargetMap) + then builtins.fromJSON (builtins.readFile externalArgs.parentTargetMap) + else { }; + + postBuildSteps = [ + # After successful builds, create a gcroot for builds on canon. + # + # This anchors *most* of the depot, in practice it's unimportant + # if there is a build race and we get +-1 of the targets. + # + # Unfortunately this requires a third evaluation of the graph, but + # since it happens after :duck: it should not affect the timing of + # status reporting back to Gerrit. + { + label = ":anchor:"; + branches = "refs/heads/canon"; + command = '' + nix-build -A ci.gcroot --out-link /nix/var/nix/gcroots/depot/canon + ''; + } + ]; + }; + + drvmap = depot.nix.buildkite.mkDrvmap depot.ci.targets; +in +pkgs.runCommandNoCC "depot-pipeline" { } '' + mkdir $out + cp -r ${pipeline}/* $out + cp ${drvmap} $out/drvmap.json +'' diff --git a/ops/pipelines/static-pipeline.yaml b/ops/pipelines/static-pipeline.yaml new file mode 100644 index 000000000000..2936f56d2c61 --- /dev/null +++ b/ops/pipelines/static-pipeline.yaml @@ -0,0 +1,113 @@ +# This file defines the static Buildkite pipeline which attempts to +# create the dynamic pipeline of all depot targets. +# +# If something fails during the creation of the pipeline, the fallback +# is executed instead which will simply report an error to Gerrit. +--- +env: + BUILDKITE_TOKEN_PATH: /run/agenix/buildkite-graphql-token +steps: + # Run pipeline for tvl-kit when new commits arrive on canon. Since + # it is not part of the depot build tree, this is a useful + # verification to ensure we don't break external things (too much). + - trigger: "tvl-kit" + async: true + label: ":fork:" + branches: "refs/heads/canon" + build: + message: "Verification triggered by ${BUILDKITE_COMMIT}" + + # Create a revision number for the current commit for builds on + # canon. + # + # This writes data back to Gerrit using the Buildkite agent + # credentials injected through a git credentials helper. + # + # Revision numbers are defined as the number of commits in the + # lineage of HEAD, following only the first parent of merges. + - label: ":git:" + branches: "refs/heads/canon" + command: | + git -c 'credential.helper=gerrit-creds' \ + push origin "HEAD:refs/r/$(git rev-list --count --first-parent HEAD)" + + # Generate & upload dynamic build steps + - label: ":llama:" + key: "pipeline-gen" + command: | + set -ue + + if test -n "$${GERRIT_CHANGE_URL-}"; then + echo "This is a build of [cl/$$GERRIT_CHANGE_ID]($$GERRIT_CHANGE_URL) (at patchset #$$GERRIT_PATCHSET)" | \ + buildkite-agent annotate + fi + + # Attempt to fetch a target map from a parent commit on canon, + # except on builds of canon itself. + [ "${BUILDKITE_BRANCH}" != "refs/heads/canon" ] && \ + nix/buildkite/fetch-parent-targets.sh + + PIPELINE_ARGS="" + if [[ -f tmp/parent-target-map.json ]]; then + PIPELINE_ARGS="--arg parentTargetMap tmp/parent-target-map.json" + fi + + nix-build -A ops.pipelines.depot -o pipeline --show-trace $$PIPELINE_ARGS + + # Steps need to be uploaded in reverse order because pipeline + # upload prepends instead of appending. + ls pipeline/build-chunk-*.json | tac | while read chunk; do + buildkite-agent pipeline upload $$chunk + done + + buildkite-agent artifact upload "pipeline/*" + + # Wait for all previous steps to complete. + - wait: null + continue_on_failure: true + + # Exit with success or failure depending on whether any other steps + # failed. + # + # This information is checked by querying the Buildkite GraphQL API + # and fetching the count of failed steps. + # + # This step must be :duck: (yes, really!) because the post-command + # hook will inspect this name. + # + # Note that this step has requirements for the agent environment, which + # are enforced in our NixOS configuration: + # + # * curl and jq must be on the $PATH of build agents + # * besadii configuration must be readable to the build agents + - label: ":duck:" + key: ":duck:" + command: | + set -ueo pipefail + + readonly FAILED_JOBS=$(curl 'https://graphql.buildkite.com/v1' \ + --silent \ + -H "Authorization: Bearer $(cat ${BUILDKITE_TOKEN_PATH})" \ + -d "{\"query\": \"query BuildStatusQuery { build(uuid: \\\"$BUILDKITE_BUILD_ID\\\") { jobs(passed: false) { count } } }\"}" | \ + jq -r '.data.build.jobs.count') + + echo "$$FAILED_JOBS build jobs failed." + + if (( $$FAILED_JOBS > 0 )); then + exit 1 + fi + + # After duck, on success, upload and run any post-build steps that + # were output by the dynamic pipeline. + - label: ":arrow_heading_down:" + depends_on: + - step: ":duck:" + allow_failure: false + command: | + set -ueo pipefail + + buildkite-agent artifact download "pipeline/*" . + + find ./pipeline -name 'post-chunk-*.json' | tac | while read chunk; do + buildkite-agent pipeline upload $$chunk + done diff --git a/ops/posix_mq.rs/.gitignore b/ops/posix_mq.rs/.gitignore new file mode 100644 index 000000000000..e5b6fdb28e32 --- /dev/null +++ b/ops/posix_mq.rs/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +.idea/ diff --git a/ops/posix_mq.rs/CODE_OF_CONDUCT.md b/ops/posix_mq.rs/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..c4013ac13ebc --- /dev/null +++ b/ops/posix_mq.rs/CODE_OF_CONDUCT.md @@ -0,0 +1,20 @@ +A SERMON ON ETHICS AND LOVE +=========================== + +One day Mal-2 asked the messenger spirit Saint Gulik to approach the Goddess and request Her presence for some desperate advice. Shortly afterwards the radio came on by itself, and an ethereal female Voice said **YES?** + +"O! Eris! Blessed Mother of Man! Queen of Chaos! Daughter of Discord! Concubine of Confusion! O! Exquisite Lady, I beseech You to lift a heavy burden from my heart!" + +**WHAT BOTHERS YOU, MAL? YOU DON'T SOUND WELL.** + +"I am filled with fear and tormented with terrible visions of pain. Everywhere people are hurting one another, the planet is rampant with injustices, whole societies plunder groups of their own people, mothers imprison sons, children perish while brothers war. O, woe." + +**WHAT IS THE MATTER WITH THAT, IF IT IS WHAT YOU WANT TO DO?** + +"But nobody Wants it! Everybody hates it." + +**OH. WELL, THEN *STOP*.** + +At which moment She turned herself into an aspirin commercial and left The Polyfather stranded alone with his species. + +SINISTER DEXTER HAS A BROKEN SPIROMETER. diff --git a/ops/posix_mq.rs/Cargo.lock b/ops/posix_mq.rs/Cargo.lock new file mode 100644 index 000000000000..dc344613d052 --- /dev/null +++ b/ops/posix_mq.rs/Cargo.lock @@ -0,0 +1,63 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "autocfg" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" + +[[package]] +name = "bitflags" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" + +[[package]] +name = "cc" +version = "1.0.50" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95e28fa049fda1c330bcf9d723be7663a899c4679724b34c81e9f5a326aab8cd" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "libc" +version = "0.2.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e74d72e0f9b65b5b4ca49a346af3976df0f9c61d550727f349ecd559f251a26c" + +[[package]] +name = "memoffset" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" +dependencies = [ + "autocfg", +] + +[[package]] +name = "nix" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6" +dependencies = [ + "bitflags", + "cc", + "cfg-if", + "libc", + "memoffset", +] + +[[package]] +name = "posix_mq" +version = "3771.0.0" +dependencies = [ + "libc", + "nix", +] diff --git a/ops/posix_mq.rs/Cargo.toml b/ops/posix_mq.rs/Cargo.toml new file mode 100644 index 000000000000..8390b80b86f0 --- /dev/null +++ b/ops/posix_mq.rs/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "posix_mq" +version = "3771.0.0" +authors = ["Vincent Ambo <tazjin@tvl.su>"] +description = "(Higher-level) Rust bindings to POSIX message queues" +license = "MIT" +homepage = "https://cs.tvl.fyi/depot/-/tree/ops/posix_mq.rs" +repository = "https://code.tvl.fyi/depot.git:/ops/posix_mq.rs.git" + +[dependencies] +nix = "0.23" +libc = "0.2" diff --git a/ops/posix_mq.rs/LICENSE b/ops/posix_mq.rs/LICENSE new file mode 100644 index 000000000000..2389546b1383 --- /dev/null +++ b/ops/posix_mq.rs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-2020 Vincent Ambo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/ops/posix_mq.rs/README.md b/ops/posix_mq.rs/README.md new file mode 100644 index 000000000000..800d2221e492 --- /dev/null +++ b/ops/posix_mq.rs/README.md @@ -0,0 +1,44 @@ +posix_mq +======== + +[![crates.io](https://img.shields.io/crates/v/posix_mq.svg)](https://crates.io/crates/posix_mq) + +This is a simple, relatively high-level library for the POSIX [message queue API][]. It wraps the lower-level API in a +simpler interface with more robust error handling. + +Check out this project's [sister library][] in Kotlin. + +Usage example: + +```rust +// Values that need to undergo validation are wrapped in safe types: +let name = Name::new("/test-queue").unwrap(); + +// Queue creation with system defaults is simple: +let queue = Queue::open_or_create(name).expect("Opening queue failed"); + +// Sending a message: +let message = Message { + data: "test-message".as_bytes().to_vec(), + priority: 0, +}; +queue.send(&message).expect("message sending failed"); + +// ... and receiving it! +let result = queue.receive().expect("message receiving failed"); +``` + +## Development + +Development happens in the [TVL +monorepo](https://cs.tvl.fyi/depot/-/tree/ops/posix_mq.rs). + +Starting from version `3771.0.0`, the version numbers correspond to +_revisions_ of the TVL repository, available as git refs (e.g. +`refs/r/3771`). + +See the TVL documentation for more information about how to contribute +to the codebase. + +[message queue API]: https://linux.die.net/man/7/mq_overview +[sister library]: https://github.com/aprilabank/posix_mq.kt diff --git a/ops/posix_mq.rs/default.nix b/ops/posix_mq.rs/default.nix new file mode 100644 index 000000000000..6b0e32009a66 --- /dev/null +++ b/ops/posix_mq.rs/default.nix @@ -0,0 +1,3 @@ +{ depot, ... }: + +depot.third_party.naersk.buildPackage ./. diff --git a/ops/posix_mq.rs/src/error.rs b/ops/posix_mq.rs/src/error.rs new file mode 100644 index 000000000000..bacd2aeb39e0 --- /dev/null +++ b/ops/posix_mq.rs/src/error.rs @@ -0,0 +1,122 @@ +use nix; +use std::{error, fmt, io, num}; + +/// This module implements a simple error type to match the errors that can be thrown from the C +/// functions as well as some extra errors resulting from internal validations. +/// +/// As this crate exposes an opinionated API to the POSIX queues certain errors have been +/// ignored: +/// +/// * ETIMEDOUT: The low-level timed functions are not exported and this error can not occur. +/// * EAGAIN: Non-blocking queue calls are not supported. +/// * EINVAL: Same reason as ETIMEDOUT +/// * EMSGSIZE: The message size is immutable after queue creation and this crate checks it. +/// * ENAMETOOLONG: This crate performs name validation +/// +/// If an unexpected error is encountered it will be wrapped appropriately and should be reported +/// as a bug on https://b.tvl.fyi + +#[derive(Debug)] +pub enum Error { + // These errors are raised inside of the library + InvalidQueueName(&'static str), + ValueReadingError(io::Error), + MessageSizeExceeded(), + MaximumMessageSizeExceeded(), + MaximumMessageCountExceeded(), + + // These errors match what is described in the man pages (from mq_overview(7) onwards). + PermissionDenied(), + InvalidQueueDescriptor(), + QueueCallInterrupted(), + QueueAlreadyExists(), + QueueNotFound(), + InsufficientMemory(), + InsufficientSpace(), + + // These two are (hopefully) unlikely in modern systems + ProcessFileDescriptorLimitReached(), + SystemFileDescriptorLimitReached(), + + // If an unhandled / unknown / unexpected error occurs this error will be used. + // In those cases bug reports would be welcome! + UnknownForeignError(nix::errno::Errno), + + // Some other unexpected / unknown error occured. This is probably an error from + // the nix crate. Bug reports also welcome for this! + UnknownInternalError(), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use Error::*; + f.write_str(match *self { + // This error contains more sensible description strings already + InvalidQueueName(e) => e, + ValueReadingError(_) => "error reading system configuration for message queues", + MessageSizeExceeded() => "message is larger than maximum size for specified queue", + MaximumMessageSizeExceeded() => "specified queue message size exceeds system maximum", + MaximumMessageCountExceeded() => "specified queue message count exceeds system maximum", + PermissionDenied() => "permission to the specified queue was denied", + InvalidQueueDescriptor() => "the internal queue descriptor was invalid", + QueueCallInterrupted() => "queue method interrupted by signal", + QueueAlreadyExists() => "the specified queue already exists", + QueueNotFound() => "the specified queue could not be found", + InsufficientMemory() => "insufficient memory to call queue method", + InsufficientSpace() => "insufficient space to call queue method", + ProcessFileDescriptorLimitReached() => { + "maximum number of process file descriptors reached" + } + SystemFileDescriptorLimitReached() => { + "maximum number of system file descriptors reached" + } + UnknownForeignError(_) => "unknown foreign error occured: please report a bug!", + UnknownInternalError() => "unknown internal error occured: please report a bug!", + }) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + match self { + Error::ValueReadingError(e) => Some(e), + Error::UnknownForeignError(e) => Some(e), + _ => None, + } + } +} + +/// This from implementation is used to translate errors from the lower-level +/// C-calls into sensible Rust errors. +impl From<nix::errno::Errno> for Error { + fn from(err: nix::Error) -> Self { + use nix::errno::Errno::*; + match err { + EACCES => Error::PermissionDenied(), + EBADF => Error::InvalidQueueDescriptor(), + EINTR => Error::QueueCallInterrupted(), + EEXIST => Error::QueueAlreadyExists(), + EMFILE => Error::ProcessFileDescriptorLimitReached(), + ENFILE => Error::SystemFileDescriptorLimitReached(), + ENOENT => Error::QueueNotFound(), + ENOMEM => Error::InsufficientMemory(), + ENOSPC => Error::InsufficientSpace(), + _ => Error::UnknownForeignError(err), + } + } +} + +// This implementation is used when reading system queue settings. +impl From<io::Error> for Error { + fn from(e: io::Error) -> Self { + Error::ValueReadingError(e) + } +} + +// This implementation is used when parsing system queue settings. The unknown error is returned +// here because the system is probably seriously broken if those files don't contain numbers. +impl From<num::ParseIntError> for Error { + fn from(_: num::ParseIntError) -> Self { + Error::UnknownInternalError() + } +} diff --git a/ops/posix_mq.rs/src/lib.rs b/ops/posix_mq.rs/src/lib.rs new file mode 100644 index 000000000000..ed35fb03be82 --- /dev/null +++ b/ops/posix_mq.rs/src/lib.rs @@ -0,0 +1,247 @@ +extern crate libc; +extern crate nix; + +use error::Error; +use libc::mqd_t; +use nix::mqueue; +use nix::sys::stat; +use std::ffi::CString; +use std::fs::File; +use std::io::Read; +use std::ops::Drop; +use std::string::ToString; + +pub mod error; + +#[cfg(test)] +mod tests; + +/// Wrapper type for queue names that performs basic validation of queue names before calling +/// out to C code. +#[derive(Debug, Clone, PartialEq)] +pub struct Name(CString); + +impl Name { + pub fn new<S: ToString>(s: S) -> Result<Self, Error> { + let string = s.to_string(); + + if !string.starts_with('/') { + return Err(Error::InvalidQueueName("Queue name must start with '/'")); + } + + // The C library has a special error return for this case, so I assume people must actually + // have tried just using '/' as a queue name. + if string.len() == 1 { + return Err(Error::InvalidQueueName( + "Queue name must be a slash followed by one or more characters", + )); + } + + if string.len() > 255 { + return Err(Error::InvalidQueueName( + "Queue name must not exceed 255 characters", + )); + } + + if string.matches('/').count() > 1 { + return Err(Error::InvalidQueueName( + "Queue name can not contain more than one slash", + )); + } + + // TODO: What error is being thrown away here? Is it possible? + Ok(Name(CString::new(string).unwrap())) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Message { + pub data: Vec<u8>, + pub priority: u32, +} + +/// Represents an open queue descriptor to a POSIX message queue. This carries information +/// about the queue's limitations (i.e. maximum message size and maximum message count). +#[derive(Debug)] +pub struct Queue { + name: Name, + + /// Internal file/queue descriptor. + queue_descriptor: mqd_t, + + /// Maximum number of pending messages in this queue. + max_pending: i64, + + /// Maximum size of this queue. + max_size: usize, +} + +impl Queue { + /// Creates a new queue and fails if it already exists. + /// By default the queue will be read/writable by the current user with no access for other + /// users. + /// Linux users can change this setting themselves by modifying the queue file in /dev/mqueue. + pub fn create(name: Name, max_pending: i64, max_size: i64) -> Result<Queue, Error> { + if max_pending > read_i64_from_file(MSG_MAX)? { + return Err(Error::MaximumMessageCountExceeded()); + } + + if max_size > read_i64_from_file(MSGSIZE_MAX)? { + return Err(Error::MaximumMessageSizeExceeded()); + } + + let oflags = { + let mut flags = mqueue::MQ_OFlag::empty(); + // Put queue in r/w mode + flags.toggle(mqueue::MQ_OFlag::O_RDWR); + // Enable queue creation + flags.toggle(mqueue::MQ_OFlag::O_CREAT); + // Fail if queue exists already + flags.toggle(mqueue::MQ_OFlag::O_EXCL); + flags + }; + + let attr = mqueue::MqAttr::new(0, max_pending, max_size, 0); + + let queue_descriptor = mqueue::mq_open(&name.0, oflags, default_mode(), Some(&attr))?; + + Ok(Queue { + name, + queue_descriptor, + max_pending, + max_size: max_size as usize, + }) + } + + /// Opens an existing queue. + pub fn open(name: Name) -> Result<Queue, Error> { + // No extra flags need to be constructed as the default is to open and fail if the + // queue does not exist yet - which is what we want here. + let oflags = mqueue::MQ_OFlag::O_RDWR; + let queue_descriptor = mqueue::mq_open(&name.0, oflags, default_mode(), None)?; + + let attr = mq_getattr(queue_descriptor)?; + + Ok(Queue { + name, + queue_descriptor, + max_pending: attr.mq_maxmsg, + max_size: attr.mq_msgsize as usize, + }) + } + + /// Opens an existing queue or creates a new queue with the OS default settings. + pub fn open_or_create(name: Name) -> Result<Queue, Error> { + let oflags = { + let mut flags = mqueue::MQ_OFlag::empty(); + // Put queue in r/w mode + flags.toggle(mqueue::MQ_OFlag::O_RDWR); + // Enable queue creation + flags.toggle(mqueue::MQ_OFlag::O_CREAT); + flags + }; + + let default_pending = read_i64_from_file(MSG_DEFAULT)?; + let default_size = read_i64_from_file(MSGSIZE_DEFAULT)?; + let attr = mqueue::MqAttr::new(0, default_pending, default_size, 0); + + let queue_descriptor = mqueue::mq_open(&name.0, oflags, default_mode(), Some(&attr))?; + + let actual_attr = mq_getattr(queue_descriptor)?; + + Ok(Queue { + name, + queue_descriptor, + max_pending: actual_attr.mq_maxmsg, + max_size: actual_attr.mq_msgsize as usize, + }) + } + + /// Delete a message queue from the system. This method will make the queue unavailable for + /// other processes after their current queue descriptors have been closed. + pub fn delete(self) -> Result<(), Error> { + mqueue::mq_unlink(&self.name.0)?; + drop(self); + Ok(()) + } + + /// Send a message to the message queue. + /// If the queue is full this call will block until a message has been consumed. + pub fn send(&self, msg: &Message) -> Result<(), Error> { + if msg.data.len() > self.max_size as usize { + return Err(Error::MessageSizeExceeded()); + } + + mqueue::mq_send(self.queue_descriptor, msg.data.as_ref(), msg.priority) + .map_err(|e| e.into()) + } + + /// Receive a message from the message queue. + /// If the queue is empty this call will block until a message arrives. + pub fn receive(&self) -> Result<Message, Error> { + let mut data: Vec<u8> = vec![0; self.max_size as usize]; + let mut priority: u32 = 0; + + let msg_size = mqueue::mq_receive(self.queue_descriptor, data.as_mut(), &mut priority)?; + + data.truncate(msg_size); + Ok(Message { data, priority }) + } + + pub fn max_pending(&self) -> i64 { + self.max_pending + } + + pub fn max_size(&self) -> usize { + self.max_size + } +} + +impl Drop for Queue { + fn drop(&mut self) { + // Attempt to close the queue descriptor and discard any possible errors. + // The only error thrown in the C-code is EINVAL, which would mean that the + // descriptor has already been closed. + mqueue::mq_close(self.queue_descriptor).ok(); + } +} + +// Creates the default queue mode (0600). +fn default_mode() -> stat::Mode { + let mut mode = stat::Mode::empty(); + mode.toggle(stat::Mode::S_IRUSR); + mode.toggle(stat::Mode::S_IWUSR); + mode +} + +/// This file defines the default number of maximum pending messages in a queue. +const MSG_DEFAULT: &'static str = "/proc/sys/fs/mqueue/msg_default"; + +/// This file defines the system maximum number of pending messages in a queue. +const MSG_MAX: &'static str = "/proc/sys/fs/mqueue/msg_max"; + +/// This file defines the default maximum size of messages in a queue. +const MSGSIZE_DEFAULT: &'static str = "/proc/sys/fs/mqueue/msgsize_default"; + +/// This file defines the system maximum size for messages in a queue. +const MSGSIZE_MAX: &'static str = "/proc/sys/fs/mqueue/msgsize_max"; + +/// This method is used in combination with the above constants to find system limits. +fn read_i64_from_file(name: &str) -> Result<i64, Error> { + let mut file = File::open(name.to_string())?; + let mut content = String::new(); + file.read_to_string(&mut content)?; + Ok(content.trim().parse()?) +} + +/// The mq_getattr implementation in the nix crate hides the maximum message size and count, which +/// is very impractical. +/// To work around it, this method calls the C-function directly. +fn mq_getattr(mqd: mqd_t) -> Result<libc::mq_attr, Error> { + use std::mem; + let mut attr = mem::MaybeUninit::<libc::mq_attr>::uninit(); + let res = unsafe { libc::mq_getattr(mqd, attr.as_mut_ptr()) }; + nix::errno::Errno::result(res) + .map(|_| unsafe { attr.assume_init() }) + .map_err(|e| e.into()) +} diff --git a/ops/posix_mq.rs/src/tests.rs b/ops/posix_mq.rs/src/tests.rs new file mode 100644 index 000000000000..1f4ea9a58da6 --- /dev/null +++ b/ops/posix_mq.rs/src/tests.rs @@ -0,0 +1,21 @@ +use super::*; + +#[test] +fn test_open_delete() { + // Simple test with default queue settings + let name = Name::new("/test-queue").unwrap(); + let queue = Queue::open_or_create(name).expect("Opening queue failed"); + + let message = Message { + data: "test-message".as_bytes().to_vec(), + priority: 0, + }; + + queue.send(&message).expect("message sending failed"); + + let result = queue.receive().expect("message receiving failed"); + + assert_eq!(message, result); + + queue.delete().expect("deleting queue failed"); +} diff --git a/ops/secrets/.skip-subtree b/ops/secrets/.skip-subtree new file mode 100644 index 000000000000..80f63816f5ba --- /dev/null +++ b/ops/secrets/.skip-subtree @@ -0,0 +1,2 @@ +The Nix configuration in here is read by agenix and not compatible +with readTree. diff --git a/ops/secrets/README.md b/ops/secrets/README.md new file mode 100644 index 000000000000..e59b86541335 --- /dev/null +++ b/ops/secrets/README.md @@ -0,0 +1 @@ +TVL's deployment secrets, encrypted with [agenix](https://github.com/ryantm/agenix/commits/main) diff --git a/ops/secrets/besadii.age b/ops/secrets/besadii.age new file mode 100644 index 000000000000..cfbe27b972b4 --- /dev/null +++ b/ops/secrets/besadii.age @@ -0,0 +1,19 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw WLrxQqBE+I1Z5BUcjAK+YfuRFlmmFYu+nwF4Z6eGZWI +ADFyrki3ojHKjthCQ0MliiwEoCqYFVPFmSDbnbesIFU +-> ssh-ed25519 zcCuhA j4NiKfnxBQlsthKUNUQMFJsazo9cL5R7RghHaFEGxAw +lJNgCMjP7+2zDG/hJ++6Q7tBbsdVbzRZIbZZsfIwMSQ +-> ssh-ed25519 CpJBgQ pVYsbcpywPaHDfnJQcnSZmNGw9Ppv5Un/xunzUG/KBg +5uFarYtHRrXi6tEYWzbS7ZVsOEn3U0FoURcbx0OHPhU +-> ssh-ed25519 aXKGcg dz+OWTc3c+odvXbaZR3lOq9t0EFu/t5qfhWOJp/tZxI +j/z4v0C+Cy+fNuGVMspJfqoOqwkynhQXMK8fPC362PY +-> ssh-ed25519 OkGqLg UQIzISNwV3+d3CEfeNcImttt+gPOyMuw1rbZ/TIsglo +cHu007ebLhPE4+ayCjvOcINmG58FYukadAcimcMeTXI +-> lP{m-grease +yVvZbJopVdBDfLsbOqhss3DJZNU7ZcSWQP409nTzyy/iV4XwrE85Yj9SsDNRDtTp +zoPwqQ +--- O6W1Z0ixSR5N2A7KdPxl5HUKWXDvy/Wcb2fiUzxPK64 +g#lEŋ2~t+CQs1RǠM' ^2PJxsPhU ܂gg3v95$(b57WMpc Ƨfe*'"],8|7$0qٷ5۳dwƲF^}!"|O|e +Ձ>D4G~NiLސ@md|*빽၄Ӫa)G2\X3G\d~o{O;LRe]֏^v +/jHV!UT})[mveX0@;]Z${mF i< +Z(SyƨC8AM6ATB˨9ϩ+~:Qo^n.lsJy;peL'LYv&0*0>J$vt \ No newline at end of file diff --git a/ops/secrets/buildkite-agent-token.age b/ops/secrets/buildkite-agent-token.age new file mode 100644 index 000000000000..aef7b142b68e --- /dev/null +++ b/ops/secrets/buildkite-agent-token.age Binary files differdiff --git a/ops/secrets/buildkite-graphql-token.age b/ops/secrets/buildkite-graphql-token.age new file mode 100644 index 000000000000..e656a6e04dc0 --- /dev/null +++ b/ops/secrets/buildkite-graphql-token.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw L31em0JneG6XJikTp2LlYLSMDfsbDWjrNgQPQimIqWk +3CJid3K/8RsE4cYEeZpqqaTmggMKH12GCDyalQMaK8s +-> ssh-ed25519 zcCuhA LKq27N4Hx8OQ3eu0TDdBiXO0BcOdSfRZO0YNNG1Y8xE +PQjl1SErWej6e7jwsddoj06TWQQwp2J/m8zvxR1pRhg +-> ssh-ed25519 CpJBgQ dRMHEzXCpKPppncOBF4AmOYDZOSxZn+ta0o2H0zyAT0 +qNQFHL0QFxGlm7ZYnJ0H22iyVN3Ya7KYO596j2mN03Y +-> ssh-ed25519 aXKGcg z31fIwcokphDOcPLNfBZB3ZN9nzG71pMmC68R60nWnU +3U32x1lxd7brCQj9V8eglSzQ1lCwraxDnjLl68EIR18 +-> ssh-ed25519 OkGqLg 2jyx2iccmCeaXxs7pajP1WkRswZRwxrwVhNUKs1HzxE +LjScnNDoWArkBXKWtSlJKnIlbnv0892nwn5aRyrF+sA +-> 8Y8-grease \ObI# /"xHCp uyu Gn&q +mLNOU8cvH8SB5PCkgKkBmxTb/cgwiQEBUbPI6GmMxvXy/8EMg5K1h3kpKSawW849 +jtLtHeLrM8FLeNtwZyIWpG4 +--- wnNSrutHnL4Trg5hNkuIHPguKl3JYjfEiJVCH4ScnVo +:-$mY:yOLVLGdQgMbJÄ:O!6O5ɪOZ8*sA \ No newline at end of file diff --git a/ops/secrets/clbot-ssh.age b/ops/secrets/clbot-ssh.age new file mode 100644 index 000000000000..a5019e7b87c3 --- /dev/null +++ b/ops/secrets/clbot-ssh.age Binary files differdiff --git a/ops/secrets/clbot.age b/ops/secrets/clbot.age new file mode 100644 index 000000000000..d5d5ae2f08c3 --- /dev/null +++ b/ops/secrets/clbot.age @@ -0,0 +1,15 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw aKWeIQEoQpPT9lPUsV7tK/ySf/0WmFWw7xr7ic4RDFM +OLRVTC6qVuhNhkYbGQwrxq4sQnqmuQEclKeQ9VPJrOw +-> ssh-ed25519 zcCuhA j3JAw3UyZHR/x3O7pOTNkytbk5bTGnfBtsM030NolQk +nt+9a3tJkO7j2nGI9C6S5YlYWYOCMqNOETU77PI4b10 +-> ssh-ed25519 CpJBgQ ScLyIj1cdn0wAwgaOSVGsusx/y3PD5/rDy7+OvjGIiU +5tYuoEfVn0i1RtZ5XP+1HgyTSWkkRN4m36u6Fj3PkC4 +-> ssh-ed25519 aXKGcg 9p2LQFtV1X7jzG7n//GRUGmHGAsbGSCz6Q6SyBOZWwY +wdOPCOHYkplGEoUOOTs99Kgde15xuJq8uzkZxudUo24 +-> ssh-ed25519 OkGqLg oLEc1KdRriCWobe5DF9OKVwDqQaW9RyjWDft1h5M4x8 +i/UEbhITzk3IOYme/xKuTfdbNMFNhLgRHbiiCAgKFBI +-> %-grease 0 \^g* +8aTar8xKZk24swVi7NVE0UN19BrexqAGcMWOeovRmQ +--- N/kNOLE5d+yk7fAPRZmj8E1qMggLha56uKb9oj0/uHQ +- >I1f9NF wKlx055OZz~ys!gQtՇl1Wf9\sΰp.n \ No newline at end of file diff --git a/ops/secrets/default.nix b/ops/secrets/default.nix new file mode 100644 index 000000000000..43f2a738bb6b --- /dev/null +++ b/ops/secrets/default.nix @@ -0,0 +1,3 @@ +args: +let mkSecrets = import ./mkSecrets.nix args; in +mkSecrets ./. (import ./secrets.nix) // { inherit mkSecrets; } diff --git a/ops/secrets/gerrit-queue.age b/ops/secrets/gerrit-queue.age new file mode 100644 index 000000000000..eb9828847cbe --- /dev/null +++ b/ops/secrets/gerrit-queue.age @@ -0,0 +1,17 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw qywg/yigMgYkhxORSqfuVsggQUMmQSPp6T9BjlEogGk ++vVPOuG9MqK/K5lkn/dTjd2RLJYL9F3uYnsK3I2r6nk +-> ssh-ed25519 zcCuhA w1iPgVkUx3U/r64ooH4UhUMnrHC+Kqs5oooDIL+pbyA +zUDp/32Hj3pEEXeL/8BJ0J5qQLqCOjpzbmQdsXGA9qk +-> ssh-ed25519 CpJBgQ kRl0KlOJtcHsnNyJfyWlm9cW6ZQMrzmhgKaT+zYr03A +lTprX0AfgP68w5towNfJw/YO3LoZFZYm0Y26Lb2La50 +-> ssh-ed25519 aXKGcg 4T+HCfrAPXDQORxNFm3lR9qJBfd4WcCQ/ny7bBs4mT8 +zKu2W42LJl6jUS6vYFJj30x+SaQQarx7OALCJ7fUTac +-> ssh-ed25519 OkGqLg EEpq+VV3LC55VErd92bKnj7KqEzQqS6S60EZuCgb5Co +XiyO6rELbfgj+2S3SQDu4Csz0Bw1NIGos69ixDPIEMU +-> GY`K*hZ-grease VW)6 t.El^< @P +dS5BLWUWe5RDzdf4uWzEOwW7lLrWtD8hqISTSWzFOFGnQgWX6cqZhtUlCmciRlCq +RLXx5Nu3sSIEBX6FZR30PjmjyDQ7qArxc/Up0pkJ+ntG1d2lobyeB3qXsn8femUU +Ku76 +--- 7KKYqquKMip1Qht63i2YH/9lGTv+MMso2YtIzF+6eis +b>w~IRjW=ͳ?1:ZMJgJ2*nzEּwgq[3.^8i%!#|ub2darn=/TI-MTE¸˕N'0\Kd~-kɜf) \ No newline at end of file diff --git a/ops/secrets/gerrit-secrets.age b/ops/secrets/gerrit-secrets.age new file mode 100644 index 000000000000..9869b0d46ab7 --- /dev/null +++ b/ops/secrets/gerrit-secrets.age @@ -0,0 +1,15 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw UCZDSCgRCFAE07NoKG/fuyEE1k4wmNE0Dlg4APH/Exk +VEnLQHoxfRgBqu3A0FTQ5KMo3w2pPSzr/dG0jT06xq0 +-> ssh-ed25519 zcCuhA fdZUx8wTyxVYd7DCngcLKligArm5mlYGTqCUKYsSflI +hO8Hx6qJ3GRZipYDWseJmbGJEQ/FyU0/eMqsO9Sc9DM +-> ssh-ed25519 CpJBgQ NCz9xhb6O5+XQxQSGTdJanwj68kg/mnhRm35/4L3+Sc +kxZ6+NOd5b2VK/VjPKpbRNTmCW8wdNZV5IgY5OT2zEk +-> ssh-ed25519 aXKGcg ZCfSQV7NUBsDLgb5sk0wRG3Zvhb8St98odNS7TmPu0c +b3AqqM9bcNPI8G+in9a/ZPg0CiqXOYNMXMTrR42xr0k +-> ssh-ed25519 OkGqLg SgctN3C54OmcYTCSrN0pA4+E7D1ry3byKebqV7Tjbg4 +Yk/2xD6lD69vhZH4+GQZh07hOOcOc0AKRq2zmkCrrjk +-> ax~swz;-grease ++jjWRJAR+9n7HqxifiYbIvk2tFX9H/1H9O329yzf +--- oZTj6wdxzeIDNWtZxBB5zo2DM4W1OcWPsTMqWJqYLSk +ri-CT }29K|CTQ$Im#xdň3>Dd{FSmaçZuaOeu:rϦ d</,-Su?)Jo#RMv*xYMß[l℟Փaй?rrgrOi,ca$m3QEx(Dܯ{8|`2 \ No newline at end of file diff --git a/ops/secrets/grafana.age b/ops/secrets/grafana.age new file mode 100644 index 000000000000..d6022b4ea541 --- /dev/null +++ b/ops/secrets/grafana.age @@ -0,0 +1,17 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw FAneL6Ra+ipVGA37rsEOIbObsDK5L93n1tk6vsDiq08 +HcEABCYv388oK0Fk3zcCXdnpi+arLHvYWjqS+vMwlWg +-> ssh-ed25519 zcCuhA n0FaAavgxFkJ1Lbd7bdDihV3m0aQ6IrD30G4N0NsNXU +YumH3OYrbM/r/vgTFzJ8vEEWd7I/2yYdk6uBF4FLzG0 +-> ssh-ed25519 CpJBgQ +80Q06PTyeX+lnPZf1o5v4jBDoSfuIudOD49c72i5gc +gNXrdBhVicCa0j7uGmvFrbZFMgN+4NQ5wxyojQUI8JE +-> ssh-ed25519 aXKGcg cB4hgrcG47MEbgdvRQdJLBgQtGpyAw7rZTHQnE8mF2U +vF46NzfPXjodk081WEd9D8LHMwB33Emswx65k2xiiQw +-> ssh-ed25519 OkGqLg H4abrPcW2U+0h9ChEANdCoaYgIXW/2GMOfaPXc142lk +OYQyK4tSDsyRIbqLhXxWc6ZgnS4/9YS8FD/M3N8ctG8 +-> 2UpS,n-grease 2@ A F$+@#Lk\ C4|Pa +WKOTNBDihEkbp8U9elitxCVbpwa+RUXIUkWDKDdcLalK7no6DtfJVMyPAyPPymWg +QOXPnkx1mw16wzj6elS86QU +--- vEbbqmuObg1gVHyfCb+6CN3bkeNyyWam3r7uG5KiHec +m26NR69.l@(_ώYUMD'Nq%y%(2yJ% Co )m + \ No newline at end of file diff --git a/ops/secrets/irccat.age b/ops/secrets/irccat.age new file mode 100644 index 000000000000..b70abf636cad --- /dev/null +++ b/ops/secrets/irccat.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw fiDNJcoEINRGGnkyaUN9j2bkXfFszU6Auje59dkfDRY +vbwn4fQP8PQ5ZFLLah4kgxcV5MN4Zbr6ncjJYtZx6mw +-> ssh-ed25519 zcCuhA GwygU+Rh3BADW/+WVL5QBb/LGEQ46HtZRWi8Ez5gdGI +qwV4L6q9LZ5UondrZ8lZiFCqyVyNj41v15yzb/9Ha0o +-> ssh-ed25519 CpJBgQ pBgC0bUHKNiB+NqHA7G2mJtTsWohDlDEVYZzZg1S3hA +Zr8h2M1lz+kENM/H6fiWr6zsz1pRCE+0FcS+8epFIDM +-> ssh-ed25519 aXKGcg Kuz7+ZHdExz4sbeOVK7MOjtldakqpuiUoCXa5BzBrlM +lhOZVOKxSjZi/GUu2zDM5HTrbKTcxyk92JZHccJlAig +-> ssh-ed25519 OkGqLg NJg2CK0q37agzqgqsLTlSIm8rhfaPwEIEPm+7eBp2So +kB4p46ar71gLlbRBC1VdnHtGsA7oM8hBOqEo4X8ixNA +-> VSn<1?+[-grease N=4\Egxn P:d\gl Ye-lT|k0 +v4W8MII8drZm1Eryx4Wzasc9WjargNyCe4R5Q+umIsuUNZebjQpvcmg1SlasTfi/ +oAdY1SZLaOJH0LmkP2v9ztz0MDsvOx9y5NZd/qw/NswgrI9FJmVh +--- m4VHPIp1FsrSWHAdKwliymn9kdmFFrfo2SncDua+MEY +{-`2k|K$>TzF6<K|cm5B)Ob5V@{03WE&<E Dj \ No newline at end of file diff --git a/ops/secrets/journaldriver.age b/ops/secrets/journaldriver.age new file mode 100644 index 000000000000..823b5278809a --- /dev/null +++ b/ops/secrets/journaldriver.age Binary files differdiff --git a/ops/secrets/keycloak-db.age b/ops/secrets/keycloak-db.age new file mode 100644 index 000000000000..185f79da8b75 --- /dev/null +++ b/ops/secrets/keycloak-db.age @@ -0,0 +1,15 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw rG0ThGyx3bkL/WOz1K1iP3CmrKORLjsUrLNJbtb1WB0 +xbkyt7EUb1BhBKUYt3hh93kEU1avcqlCLKfHc3x+BEU +-> ssh-ed25519 zcCuhA mwSN0urAXmA4vPCWIkzvCuDoE/LcA3eWpXr24Qab/lY +Esa4Rfn55KYpIdYxsxGhBpPs40o28PJHbn8AEDn1n78 +-> ssh-ed25519 CpJBgQ ODm3P+PymrXBxEejSDi2YUTEadBVzJiIt6vYHpzH1C4 +nC9FY8yilVG65HXmRTtpvjKj2awE9SI1qp8duskNP7M +-> ssh-ed25519 aXKGcg cdO7r0WCOktOmldIqvjVogyCximfA9sWd2Vq+bBgF2U +1INC04f5PDwQgSQVeDpJomL5iZmyQfTwzHVu7BG+UUw +-> ssh-ed25519 OkGqLg D6x2fkkNeoZToQrOhNVh69Y3kWN5NqZzXkUc2556nBY +ZC4asUqTT6ZnQdnYV9Xn0yqTgLFt14Vo+3RncxWingU +-> R^R|CZso-grease xq76HV<! +MQSwHZCAIj24PlpplrTWjrZPAe5I31NC3xnWU80Q7Gk7FHUavAw +--- NG3cBfD3zeP6McHAXxhPuWZVrC9au95/+r6fMi01Gjs +`$|mR_!z[|伭2s"h0ž*0(-& \ No newline at end of file diff --git a/ops/secrets/mkSecrets.nix b/ops/secrets/mkSecrets.nix new file mode 100644 index 000000000000..c99130835f15 --- /dev/null +++ b/ops/secrets/mkSecrets.nix @@ -0,0 +1,27 @@ +# Expose secrets as part of the tree, making it possible to validate +# their paths at eval time. +# +# Note that encrypted secrets end up in the Nix store, but this is +# fine since they're publicly available anyways. +{ depot, lib, ... }: + +let + inherit (depot.nix.yants) + attrs + any + defun + list + path + restrict + string + struct + ; + ssh-pubkey = restrict "SSH pubkey" (lib.hasPrefix "ssh-") string; + agenixSecret = struct "agenixSecret" { publicKeys = list ssh-pubkey; }; +in + +defun [ path (attrs agenixSecret) (attrs any) ] + (path: secrets: + depot.nix.readTree.drvTargets + # Import each secret into the Nix store + (builtins.mapAttrs (name: _: "${path}/${name}") secrets)) diff --git a/ops/secrets/nix-cache-priv.age b/ops/secrets/nix-cache-priv.age new file mode 100644 index 000000000000..cc8513071ad9 --- /dev/null +++ b/ops/secrets/nix-cache-priv.age Binary files differdiff --git a/ops/secrets/nix-cache-pub.age b/ops/secrets/nix-cache-pub.age new file mode 100644 index 000000000000..f628f2bbe4fd --- /dev/null +++ b/ops/secrets/nix-cache-pub.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw j+RSQPvmBUL+/tJpoZqbMyh//yPYelDkS8rGMBDeYBg +w9XLo36I+Fh8yCgL9aL1V2dHA5PFIhA/mi+inpA0vO0 +-> ssh-ed25519 zcCuhA KTfCgCjc38/NRthB4ttrQV7aXbBgvs0Bgxitspo1TTo +Zj7ZcjNxdiXgasq0pACRL6E3PvRsjsYsZeHFbX1mNYY +-> ssh-ed25519 CpJBgQ 4nH14KX8d5AYlQOYpAq77Oz6QLLcqh+We7WT0yXx3EA +YCIc6wFk++uaankNET+SATIRMPXh1C2NemJssGUexXA +-> ssh-ed25519 aXKGcg x2izNmR+I9+2sRoHye4YUXU/6EZA8ZicIKUbjARVR28 +AV28t/cAwP6Js4lfYedJ88dCyAuKLq7RJU9SlhBx1FA +-> ssh-ed25519 OkGqLg PpKqeVlQ015Qv2zvvrR8kTj+7kDHirLz4Zk8f32NoTA +huaUh3Q3uJmsi9yWyuJgnEhgmsVjspfpR+IN6uT8FgA +-> R2aR1C?^-grease +7rumeWTufR7m6GRBOwKKVfzmMG8QRHzmt103vQfgmylhzGa2r6z2L3qSfFTqCW7T +gMdbpgVvvTO+5aROt+iieBz9KFkHD3l/NXAhyZf8ydWRQlmDXcomY7QmSC3jLAE +--- RX4Cux3g3rn4jdCZMpP8XenZ45uol6W4+wBk8jofI0E +=[ބ$֘Klmdhe&*ERtΟD:;-=;W$0 \ No newline at end of file diff --git a/ops/secrets/oauth2_proxy.age b/ops/secrets/oauth2_proxy.age new file mode 100644 index 000000000000..816944684a37 --- /dev/null +++ b/ops/secrets/oauth2_proxy.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw pkxciQfQ/yrexMq/Djpq1KNLFYBRTnJSi3fo4iQ0MDk +FAlEvIgT+h/7Lcj5E0BeEbaWlZAg1THoiqsQg6Sy1oI +-> ssh-ed25519 zcCuhA sey8T2EXLHh5TF726U0DSn+MfXYYjimQxdsE67iflTc +lPWYa9jrmwkac8KkCUypfZ5D3GCZwtdQPaXQRiM5xMo +-> ssh-ed25519 CpJBgQ 6EzBbhxLD1Cjy1LRWnfum+tFvPRzxMoPT6P2HDN7qBs +BPWNJiFIrAPdcOOK0um+RzclUGgrS7yJwCjx8X0pYTk +-> ssh-ed25519 aXKGcg kMVeXntSlq3E5hbuNtu7e+iKoJpQDRR4isbx/WCYc0g +fWvCPlcnjunuQ2LB02eQ51gr6SK2leaNuHttQOjJOyw +-> ssh-ed25519 OkGqLg QFU47rj1sU5JuQtehbxyymEOpZYl0bWY6dRo81KrQxE +5TXNy6e2sM5b+K5lSXEkLdJ8F4ZDJfYEetJ7/jsxAIY +-> `!"O*HV-grease 1YD XwG${5; #Pr \7G +CD72odW0Q4DMW6SGY+cUpBPhFePtjebkf1rpZJz0Twl8YrzbrXQfIgWv+tCUbr2d +PKZKtlc9u0F+B6BKfVpZn0s0PD4/XGQ1PNLL/ZajxvYSB/w+UWbE67s +--- U0nGetyOZONCTw7TQJ5QNUScp6v2noSVkrWCMJeROH8 +zsͮ~=H'Q|dL_Bx0;7Cg *B3kp8{P+a%ؽ)EmF'`AUvUDzcLWox7PT( n~a \ No newline at end of file diff --git a/ops/secrets/owothia.age b/ops/secrets/owothia.age new file mode 100644 index 000000000000..c3ad07d2324c --- /dev/null +++ b/ops/secrets/owothia.age Binary files differdiff --git a/ops/secrets/panettone.age b/ops/secrets/panettone.age new file mode 100644 index 000000000000..4738d329e2d9 --- /dev/null +++ b/ops/secrets/panettone.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw Hq0RWzSQoxe0fJpLo/TFHAKDb3WRctz70xaEJl3ea3Q +ehsVvpDrzuKg2T4X8N0vOEhrFMIHZj0mrv3SK7ZC0H0 +-> ssh-ed25519 zcCuhA q6xJ97+gO5D31gADdHn0rmqIE8GQJDBzQfYg2GNvd2I +wNWaPvYHmrt/+KF7BhJcums5uMeUQcka4IfNDISESFI +-> ssh-ed25519 CpJBgQ E3jeeA/VRjaO8Y0UtX0QX1oYKKWUYT2UWt/7HlXpf3E +DNwyN1glgi8cHQpe/Wyn/BixPM7kzxL12E1epXkErDI +-> ssh-ed25519 aXKGcg YQzj3iHJ06uN4r5ZBZBmynlGH6jW1LLR62yfejTGJ1k +lWawUFQp5DGV+7sOTHk5hA1BVdzE0oZ1VBHvDvOSVPA +-> ssh-ed25519 OkGqLg j8xHnG4Khp2haDqPzUucIX1kcR4mSk4q0VfZSTrJfCU +4bViy1sovQO7aEQ7jocoRCJm98Q8O3uZTnrZjdb2S7E +-> *C|-grease +dSE4eFdJtd5Vw+xEd3CBWtkIASoep80Ps5ar2CDO1OoS1+X7+me5SDn8lFV2Uskx +5qNuqIGdo7OizxculYgPylG9iNPEb5ZM0OXZUCFG +--- //wRLTro4ZXGej8Bv5uwQoQ6qP7MRuu0EpY8d7QqDrs +%Do32wiwkI4p;81<V3&Gl.FLxyиu鹜9:a$wxހ"y7|*Q @&e)$^T%z605>b'Ox/;cmSgJ@q/ \ No newline at end of file diff --git a/ops/secrets/secrets.nix b/ops/secrets/secrets.nix new file mode 100644 index 000000000000..aec22f7b06bd --- /dev/null +++ b/ops/secrets/secrets.nix @@ -0,0 +1,45 @@ +let + tazjin = [ + # tverskoy + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIM1fGWz/gsq+ZeZXjvUrV+pBlanw1c3zJ9kLTax9FWQy" + + # zamalek + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDBRXeb8EuecLHP0bW4zuebXp4KRnXgJTZfeVWXQ1n1R" + ]; + + grfn = [ + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMcBGBoWd5pPIIQQP52rcFOQN3wAY0J/+K2fuU6SffjA " + ]; + + sterni = [ + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJk+KvgvI2oJTppMASNUfMcMkA2G5ZNt+HnWDzaXKLlo" + ]; + + sanduny = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOag0XhylaTVhmT6HB8EN2Fv5Ymrc4ZfypOXONUkykTX"; + whitby = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILNh/w4BSKov0jdz3gKBc98tpoLta5bb87fQXWBhAl2I"; + + whitbyDefault.publicKeys = tazjin ++ grfn ++ sterni ++ [ whitby ]; + allDefault.publicKeys = tazjin ++ grfn ++ sterni ++ [ sanduny whitby ]; +in +{ + "besadii.age" = whitbyDefault; + "buildkite-agent-token.age" = whitbyDefault; + "buildkite-graphql-token.age" = whitbyDefault; + "clbot-ssh.age" = whitbyDefault; + "clbot.age" = whitbyDefault; + "gerrit-queue.age" = whitbyDefault; + "gerrit-secrets.age" = whitbyDefault; + "grafana.age" = whitbyDefault; + "irccat.age" = whitbyDefault; + "journaldriver.age" = allDefault; + "keycloak-db.age" = whitbyDefault; + "nix-cache-priv.age" = whitbyDefault; + "nix-cache-pub.age" = whitbyDefault; + "oauth2_proxy.age" = whitbyDefault; + "owothia.age" = whitbyDefault; + "panettone.age" = whitbyDefault; + "smtprelay.age" = whitbyDefault; + "tf-glesys.age" = whitbyDefault; + "tf-keycloak.age" = whitbyDefault; + "tvl-alerts-bot-telegram-token.age" = whitbyDefault; +} diff --git a/ops/secrets/smtprelay.age b/ops/secrets/smtprelay.age new file mode 100644 index 000000000000..3904107261d9 --- /dev/null +++ b/ops/secrets/smtprelay.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw mqDmOqzDl7BY8xj7TuCHcIGrkiqURHK4Y4NkmUesyQE +sfNvq6kuQUWuza3B6feUQtcWYhYh/aiN89fTOHdhHSY +-> ssh-ed25519 zcCuhA rBlPiVmj7dSYHljc4/fhL7a9GSeCp/8FqG1R2f1kPgw +o6Za8zm3n2LBnj9jQAU7Xtvt5ULIUesdiTi11DeRMY8 +-> ssh-ed25519 CpJBgQ vM3qI0XMQJY/ExxE3a0mmHhc5hY9rPDBzdJ4v9oZBlY +lLHtL9j8ltx86eWwlPkyblcWjRd2iMjimwMXZptsRAc +-> ssh-ed25519 aXKGcg +6heNooQufYnntQ1PJHlW/8aG4vijzY/CfXHUGPKMQE +T95bxZSRC9Cdx9ZTaTnHWdeq0wKOkRL9mQxNo8j9SfA +-> ssh-ed25519 OkGqLg HvpZmHz0DZIqWHiXvUsJ/OILlRhptl4WMDDiVF6dxko +FoTSc84FRFnBh0rOYFX3M7t9p/hvn4DZMHZfU9jy0zo +-> $<0F{v-grease +blva6tBLrd967p8hOMGy0JT6Y19zWNdgowASEEBpoFzsmNlyKdbaYyMbxKTuqmCy +8Wy5TpBj99pcUsEB +--- DTMNC/wQr8xtJKIPPKjx90PmAZ15eimydKbYGnEa7Jc +Զ"RA!]* ) 2)7ꗞ3AjӤʏL5EN"1:4tp.܋jpqG2(\mqߑF@1aŌ% \ No newline at end of file diff --git a/ops/secrets/tf-glesys.age b/ops/secrets/tf-glesys.age new file mode 100644 index 000000000000..caeac0b1ee1e --- /dev/null +++ b/ops/secrets/tf-glesys.age Binary files differdiff --git a/ops/secrets/tf-keycloak.age b/ops/secrets/tf-keycloak.age new file mode 100644 index 000000000000..b450e84fb069 --- /dev/null +++ b/ops/secrets/tf-keycloak.age Binary files differdiff --git a/ops/secrets/tvl-alerts-bot-telegram-token.age b/ops/secrets/tvl-alerts-bot-telegram-token.age new file mode 100644 index 000000000000..d9562ce924ab --- /dev/null +++ b/ops/secrets/tvl-alerts-bot-telegram-token.age @@ -0,0 +1,16 @@ +age-encryption.org/v1 +-> ssh-ed25519 dcsaLw 14nPZssvAKQSzPdL+1iyz0BVA1DOdFDafdCyRfcmSWo ++ENcKRKyUN3G9+kd/Y9IpQbO3rIZdYiznqGO1cfVNZE +-> ssh-ed25519 zcCuhA i/ag/HD84XrTpYigStOfwnWBLjOSypCnVuIYjtdVc2o +T+dN0nl3H6J6OaMyLNHLgy99H8YJtSjgintxogJkWjo +-> ssh-ed25519 CpJBgQ bbyerpmjpTkMmSaLnV5OuMQzqqtGao4eqE4kiFzm+Dw +0Hskm4/Cks4Eu/Jr4Eh6302jWo64rdInvvJH6XJFyBk +-> ssh-ed25519 aXKGcg sqdfN/2YLFmdhEWgn5Z/OAsmXwMORX/dPrmD4O7MlCE +h/ej9LjZHn04rkEbvIaGAcLT3dMs9RdL3vFA+Rgdp3g +-> ssh-ed25519 OkGqLg fK2cPxfOupCIfC1giMj2CFg/K/+4XX+fLpkqUmQHzDY +uXTHT30ytEvliNAvmwlPyaySsYDVLarZgouV9Tfo6qo +-> Me?Ykt-grease 4S m!3LR ^/)u#tFR +1A +--- UP4D68fCAMJC+1T1zbIiGCah3Ph+pJf7Z6wv2YJaOCQ +js]U-Jγ6Y#^ +$$L1pwa:qwgq3Ԓb0zH%f!.0ΐ'֘! \ No newline at end of file diff --git a/ops/users/default.nix b/ops/users/default.nix new file mode 100644 index 000000000000..4f88e75b653f --- /dev/null +++ b/ops/users/default.nix @@ -0,0 +1,162 @@ +{ ... }: + +[ + { + username = "adisbladis"; + email = "adisbladis@gmail.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$wdgoLRrUgZuz0Kin9YiNgQ$E40VIgzgpMpylZqkfByTKiWQnerupfuf7LDgOsU8tJA"; + } + { + username = "andi"; + email = "andi@notmuch.email"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$8lefg7+8UPAEh9Ott8zH0A$7YuLRraTC1IgxTNTxFJF03AWmqBS3GX2+vfD4XVTrb0"; + } + { + username = "cschilling"; + email = "christian.schilling.de@gmail.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$9VN3IS6ViW5FFbVKWOZI6Q$gZxuYAYk0Opq4E5i8cbcNjfznCQNc+RiP7Xv1CUnrQU"; + } + { + username = "cynthia"; + email = "me@cynthia.re"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=4,p=1$TxjbMGenhEmkyYLrg5uGhbr60THB86YeRZg5bPdiTJo$k9gbRlAPjmxwdUwzbavvsAVkckgQZ0jS2oTtvZBPysk"; + } + { + username = "edef"; + email = "edef@edef.eu"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$OORx4ERbkgvTmuYCJA8cIw$i5qaBzHkRVw7Tl+wZsTFTDqJwF0vuZqhW3VpknMYMc0"; + } + { + username = "ericvolp12"; + email = "ericvolp12@gmail.com"; + password = "{SSHA}pSepaQ+/5KBLfJtRR5rfxGU8goAsXgvk"; + } + { + username = "eta"; + email = "tvl@eta.st"; + password = "{SSHA}sOR5xzi7Lfv376XGQA8Hf6jyhTvo0XYc"; + } + { + username = "etu"; + email = "etu@failar.nu"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$RUrW8C9mWAkBSlkwSTH5dw$n3FXTeu41nDQfvJPI7TT3tcgwPmPJl8hPtaZ58qLq9A"; + } + { + username = "firefly"; + email = "firefly@firefly.nu"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$RYVVkFoi3A1yYkI8J2zUwg$GUERvgHvU8SGjQmilDJGZu50hYRAHw+ejtuL+Skygs8"; + } + { + username = "flokli"; + email = "flokli@flokli.de"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$TrezbwIY5TKLnJiii0wafQ$K0S2p9I8tiqP907nkgoK6IbG9ia4IuDiylTcIs5pesw"; + } + { + username = "grfn"; + email = "grfn@gws.fyi"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$5NEYPJ19nDITK5sGr4bzhQ$Xzpzth6y4w+HGvioHiYgzqFiwMDx0B7HAh+PVbkRuuk"; + } + { + username = "htbf"; + email = "h-tvl@htbf.dev"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$2iVXQQfd26icaIguHJg/CQ$hA9ziqn7kQ06AV6uQxJCGXoG8f+LWmH+nVlk00a1n/c"; + } + { + username = "isomer"; + email = "isomer@tvl.fyi"; + password = "{SSHA}OhWQkPJgH1rRJqYIaMUbbKC4iLEzvCev"; + } + { + username = "kn"; + email = "klemens@posteo.de"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$CoRZInysud4sduDoMjVOCw$/bdvAvyPO2DPxOcHlBiG2+rbTGF9XAcHUhPurxiIpZM"; + } + { + username = "lukegb"; + email = "lukegb@tvl.fyi"; + password = "{SSHA}7a85VNhpFElFw+N5xcjgGmt4HnBsaGp4"; + } + { + username = "nyanotech"; + email = "nyanotechnology@gmail.com"; + password = "{SSHA}NIJ2RCRb1+Q4Bs63cyE91VZyiN47DG6y"; + } + { + username = "Profpatsch"; + email = "mail@profpatsch.de"; + password = "{SSHA}jcFXxRplMFxH4gpa0X5VdUzW64T95TwQ"; + } + { + username = "sterni"; + email = "sternenseemann@systemli.org"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$+NbF1izPMGqN5bASCBDV9g$aqBVplHwiyDpflZUmLtjkLWzKhxi7hwjm5fOwfbKohU"; + } + { + username = "qyliss"; + displayName = "Alyssa Ross"; + email = "hi@alyssa.is"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$+uTpAKrN452D8wa7OFqPnw$GYi9/zns5iJCXDp1VuTPPsa35M5vkD6+rC8riT8cEHI"; + } + { + username = "riking"; + displayName = "kanepyork"; + email = "rikingcoding@gmail.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$o2OcfhfKOry+UrcmODyQCw$qloaQgoIRDESwaA3yqPxxy8sgLk3mrjYFBbF41elVrM"; + } + { + username = "tazjin"; + email = "tazjin@tvl.su"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$wOPEl9D3kSke//oLtbvqrg$j0npwwXgaXQ/emefKUwL59tH8hdmtzbgH2rQzWSmE2Y"; + } + { + username = "implr"; + email = "implr@hackerspace.pl"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$SHRFps5sVgyUXYdmqGPw9g$tEx9DwKK1RjWlw52GLwOZ/iHep+QJboaZE83f1pXSwQ"; + } + { + username = "ben"; + email = "tvl@benjojo.co.uk"; + password = "{SSHA}Zi48mSPsRMEPhff44w4RHi0SjjyhjWk1"; + } + { + username = "jamie"; + email = "jamie@kwiius.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$OkAMHVAfQ3nJhBffYJwk7Q$JV3DrF9eOU+4VL6I+nkaMUUOMqWuNzdp7N7U5Xwa3fg"; + } + { + username = "milan"; + email = "milan@petabyte.dev"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$VQAHgOqYVr7mzjEr8IAMdQ$eAXvy58eRkjg+96RKBCwUoRDpNyGDdes4rVtxoQbaeI"; + } + { + username = "ezemtsov"; + email = "eugene.zemtsov@gmail.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$eAEjTm0+JD0+p0o/GA8JmQ$uRtHCT+B/DBNr1rlOcLlROrkYsMj2T9ns/E9Ep3gJ1A"; + } + { + username = "mdjnsn"; + email = "mdj@mikejohnson.xyz"; + displayName = "Mike Johnson"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$77+f5DFbuzs5myyIUN2nHg$xyXkRhIHFVaPMZUhxPk1uxMpLeEmU3BeyQjDsNPlJVw"; + } + { + username = "smitop"; + email = "me@smitop.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$H78rQtmhlzrPEifbXPoCVw$IBg7ePTm/u+e8r2A8aJ4iaaQBzMUw1isS9YJAZ8aT3o"; + } + { + username = "asmundo"; + email = "asmundo@gmail.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$oQvNAAGjshz5Cl8XW5i31A$eurlL9a7e5Ttw5JpTY9tOjSZyivWQsr1iCdTqshdfQU"; + } + { + username = "wpcarro"; + email = "wpcarro@gmail.com"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$NQdBVPNwh2ioDq9zWfMusA$2cABJGI8cU2JZirnVU5E5C28sTiePkiOPEAaqNUp/Fk"; + } + { + username = "zseri"; + email = "zseri.devel@ytrizja.de"; + password = "{ARGON2}$argon2id$v=19$m=65536,t=2,p=1$wVNkImXloXIkCycnecdFeA$ECAdGdNzUUEq9sFGsIl0jb7AALGsHE+ndWRn6ilSmdE"; + } +] |