diff options
Diffstat (limited to 'ops')
100 files changed, 7039 insertions, 0 deletions
diff --git a/ops/infra/.skip-subtree b/ops/infra/.skip-subtree new file mode 100644 index 000000000000..cee24b75793c --- /dev/null +++ b/ops/infra/.skip-subtree @@ -0,0 +1,2 @@ +Code under //ops/infra is mostly configuration for other tools, not +Nix derivations to be built. diff --git a/ops/infra/dns/import b/ops/infra/dns/import new file mode 100755 index 000000000000..e79e426b5553 --- /dev/null +++ b/ops/infra/dns/import @@ -0,0 +1,11 @@ +#!/bin/sh +set -ue + +# Imports a zone file into a Google Cloud DNS zone of the same name +readonly ZONE="${1}" + +gcloud dns record-sets import "${ZONE}" \ + --project composite-watch-759 \ + --zone-file-format \ + --delete-all-existing \ + --zone "${ZONE}" diff --git a/ops/infra/dns/kontemplate-works b/ops/infra/dns/kontemplate-works new file mode 100644 index 000000000000..326a129d2105 --- /dev/null +++ b/ops/infra/dns/kontemplate-works @@ -0,0 +1,15 @@ +;; -*- mode: zone; -*- +;; Do not delete these +kontemplate.works. 21600 IN NS ns-cloud-d1.googledomains.com. +kontemplate.works. 21600 IN NS ns-cloud-d2.googledomains.com. +kontemplate.works. 21600 IN NS ns-cloud-d3.googledomains.com. +kontemplate.works. 21600 IN NS ns-cloud-d4.googledomains.com. +kontemplate.works. 21600 IN SOA ns-cloud-d1.googledomains.com. cloud-dns-hostmaster.google.com. 4 21600 3600 259200 300 + +;; Github site setup +kontemplate.works. 60 IN A 185.199.108.153 +kontemplate.works. 60 IN A 185.199.109.153 +kontemplate.works. 60 IN A 185.199.110.153 +kontemplate.works. 60 IN A 185.199.111.153 + +www.kontemplate.works. 60 IN CNAME tazjin.github.io. diff --git a/ops/infra/dns/oslo-pub b/ops/infra/dns/oslo-pub new file mode 100644 index 000000000000..674687484b90 --- /dev/null +++ b/ops/infra/dns/oslo-pub @@ -0,0 +1,8 @@ +;; Do not delete these +oslo.pub. 21600 IN NS ns-cloud-c1.googledomains.com. +oslo.pub. 21600 IN NS ns-cloud-c2.googledomains.com. +oslo.pub. 21600 IN NS ns-cloud-c3.googledomains.com. +oslo.pub. 21600 IN NS ns-cloud-c4.googledomains.com. +oslo.pub. 21600 IN SOA ns-cloud-c1.googledomains.com. cloud-dns-hostmaster.google.com. 4 21600 3600 1209600 300 + +oslo.pub. 60 IN A 46.21.106.241 diff --git a/ops/infra/dns/root-tazj-in b/ops/infra/dns/root-tazj-in new file mode 100644 index 000000000000..43db5834a0ca --- /dev/null +++ b/ops/infra/dns/root-tazj-in @@ -0,0 +1,33 @@ +;; -*- mode: zone; -*- +;; Do not delete these +tazj.in. 21600 IN NS ns-cloud-a1.googledomains.com. +tazj.in. 21600 IN NS ns-cloud-a2.googledomains.com. +tazj.in. 21600 IN NS ns-cloud-a3.googledomains.com. +tazj.in. 21600 IN NS ns-cloud-a4.googledomains.com. +tazj.in. 21600 IN SOA ns-cloud-a1.googledomains.com. cloud-dns-hostmaster.google.com. 123 21600 3600 1209600 300 + +;; Email setup +tazj.in. 300 IN MX 1 aspmx.l.google.com. +tazj.in. 300 IN MX 5 alt1.aspmx.l.google.com. +tazj.in. 300 IN MX 5 alt2.aspmx.l.google.com. +tazj.in. 300 IN MX 10 alt3.aspmx.l.google.com. +tazj.in. 300 IN MX 10 alt4.aspmx.l.google.com. +tazj.in. 300 IN TXT "v=spf1 include:_spf.google.com ~all" +google._domainkey.tazj.in. 21600 IN TXT "v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA9AphX/WJf8zVXQB5Jk0Ry1MI6ARa6vEyAoJtpjpt9Nbm7XU4qVWFRJm+L0VFd5EZ5YDPJTIZ90lJE3/B8vae2ipnoGbJbj8LaVSzzIPMbWmhPhX3fkLJFdkv7xRDMDn730iYXRlfkgv6GsqbS8vZt7mzxx4mpnePTI323yjRVkwRW8nGVbsmB25ZoG1/0985" "kg4mSYxzWeJ2ozCPFhT4sfMtZMXe/4QEkJz/zkod29KZfFJmLgEaf73WLdBX8kdwbhuh2PYXt/PwzUrRzF5ujVCsSaTZwdRVPErcf+yo4NvedelTjjs8rFVfoJiaDD1q2bQ3w0gDEBWPdC2VP7k9zwIDAQAB" + +;; Site verifications +tazj.in. 3600 IN TXT "keybase-site-verification=gC4kzEmnLzY7F669PjN-pw2Cf__xHqcxQ08Gb-W9dhE" +tazj.in. 300 IN TXT "google-site-verification=d3_MI1OwD6q2OT42Vvh0I9w2u3Q5KFBu-PieNUE1Fig" +www.tazj.in. 3600 IN TXT "keybase-site-verification=ER8m_byyqAhzeIy9TyzkAU1H2p2yHtpvImuB_XrRF2U" + +;; Blog "storage engine" +blog.tazj.in. 21600 IN NS ns-cloud-c1.googledomains.com. +blog.tazj.in. 21600 IN NS ns-cloud-c2.googledomains.com. +blog.tazj.in. 21600 IN NS ns-cloud-c3.googledomains.com. +blog.tazj.in. 21600 IN NS ns-cloud-c4.googledomains.com. + +;; Webpage records setup +tazj.in. 300 IN A 34.98.120.189 +www.tazj.in. 300 IN A 34.98.120.189 +git.tazj.in. 300 IN A 34.98.120.189 +files.tazj.in. 300 IN CNAME c.storage.googleapis.com. diff --git a/ops/infra/gcp/.gitignore b/ops/infra/gcp/.gitignore new file mode 100644 index 000000000000..96c7538dda8a --- /dev/null +++ b/ops/infra/gcp/.gitignore @@ -0,0 +1,3 @@ +.terraform +*.tfstate +*.tfstate.backup diff --git a/ops/infra/gcp/default.tf b/ops/infra/gcp/default.tf new file mode 100644 index 000000000000..2cb57836fa6d --- /dev/null +++ b/ops/infra/gcp/default.tf @@ -0,0 +1,111 @@ +# Terraform configuration for the GCP project 'tazjins-infrastructure' + +provider "google" { + project = "tazjins-infrastructure" + region = "europe-north1" +} + +# Configure a storage bucket in which to keep Terraform state and +# other data, such as Nixery's layers. +resource "google_storage_bucket" "tazjins-data" { + name = "tazjins-data" + location = "EU" +} + +terraform { + backend "gcs" { + bucket = "tazjins-data" + prefix = "terraform" + } +} + +# Configure enabled APIs +resource "google_project_services" "primary" { + project = "tazjins-infrastructure" + services = [ + "bigquery-json.googleapis.com", + "bigquerystorage.googleapis.com", + "cloudapis.googleapis.com", + "clouddebugger.googleapis.com", + "cloudfunctions.googleapis.com", + "cloudkms.googleapis.com", + "cloudtrace.googleapis.com", + "compute.googleapis.com", + "container.googleapis.com", + "containerregistry.googleapis.com", + "datastore.googleapis.com", + "dns.googleapis.com", + "iam.googleapis.com", + "iamcredentials.googleapis.com", + "logging.googleapis.com", + "monitoring.googleapis.com", + "oslogin.googleapis.com", + "pubsub.googleapis.com", + "run.googleapis.com", + "servicemanagement.googleapis.com", + "serviceusage.googleapis.com", + "sourcerepo.googleapis.com", + "sql-component.googleapis.com", + "storage-api.googleapis.com", + "storage-component.googleapis.com", + ] +} + + +# Configure the main Kubernetes cluster in which services are deployed +resource "google_container_cluster" "primary" { + name = "tazjin-cluster" + location = "europe-north1" + + remove_default_node_pool = true + initial_node_count = 1 +} + +resource "google_container_node_pool" "primary_nodes" { + name = "primary-nodes" + location = "europe-north1" + cluster = google_container_cluster.primary.name + node_count = 1 + + node_config { + preemptible = true + machine_type = "n1-standard-2" + + oauth_scopes = [ + "storage-rw", + "logging-write", + "monitoring", + "https://www.googleapis.com/auth/source.read_only", + ] + } +} + +# Configure a service account for which GCS URL signing keys can be created. +resource "google_service_account" "nixery" { + account_id = "nixery" + display_name = "Nixery service account" +} + +# Configure Cloud KMS for secret encryption +resource "google_kms_key_ring" "tazjins_keys" { + name = "tazjins-keys" + location = "europe-north1" + + lifecycle { + prevent_destroy = true + } +} + +resource "google_kms_crypto_key" "kontemplate_key" { + name = "kontemplate-key" + key_ring = google_kms_key_ring.tazjins_keys.id + + lifecycle { + prevent_destroy = true + } +} + +# Configure the git repository that contains everything. +resource "google_sourcerepo_repository" "depot" { + name = "depot" +} diff --git a/ops/infra/kubernetes/cgit/config.yaml b/ops/infra/kubernetes/cgit/config.yaml new file mode 100644 index 000000000000..43bfe9d7fb45 --- /dev/null +++ b/ops/infra/kubernetes/cgit/config.yaml @@ -0,0 +1,73 @@ +--- +apiVersion: v1 +kind: Secret +metadata: + name: gcsr-secrets +type: Opaque +data: + username: "Z2l0LXRhemppbi5nbWFpbC5jb20=" + # This credential is a GCSR 'gitcookie' token. + password: '{{ passLookup "gcsr-tazjin-password" | b64enc }}' +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: cgit + labels: + app: cgit +spec: + replicas: 2 + selector: + matchLabels: + app: cgit + template: + metadata: + labels: + app: cgit + spec: + securityContext: + runAsUser: 1000 + runAsGroup: 1000 + fsGroup: 1000 + containers: + - name: cgit + image: nixery.local/shell/web.cgit-taz:{{ gitHEAD }} + command: [ "cgit-launch" ] + env: + - name: HOME + value: /git + volumeMounts: + - name: git-volume + mountPath: /git + - name: sync-gcsr + image: nixery.local/shell/ops.sync-gcsr:{{ gitHEAD }} + command: [ "sync-gcsr" ] + env: + - name: SYNC_USER + valueFrom: + secretKeyRef: + name: gcsr-secrets + key: username + - name: SYNC_PASS + valueFrom: + secretKeyRef: + name: gcsr-secrets + key: password + volumeMounts: + - name: git-volume + mountPath: /git + volumes: + - name: git-volume + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: cgit +spec: + selector: + app: cgit + ports: + - protocol: TCP + port: 80 + targetPort: 8080 diff --git a/ops/infra/kubernetes/gemma/config.lisp b/ops/infra/kubernetes/gemma/config.lisp new file mode 100644 index 000000000000..517a658cf150 --- /dev/null +++ b/ops/infra/kubernetes/gemma/config.lisp @@ -0,0 +1,19 @@ +(config :port 4242 + :data-dir "/var/lib/gemma/") + +(deftask bathroom/wipe-mirror 7) +(deftask bathroom/wipe-counter 7) + +;; Bedroom tasks +(deftask bedroom/change-sheets 7) +(deftask bedroom/vacuum 10) + +;; Kitchen tasks +(deftask kitchen/normal-trash 3) +(deftask kitchen/green-trash 5) +(deftask kitchen/blue-trash 5) +(deftask kitchen/wipe-counters 3) +(deftask kitchen/vacuum 5 "Kitchen has more crumbs and such!") + +;; Entire place +(deftask clean-windows 60) diff --git a/ops/infra/kubernetes/https-cert/cert.yaml b/ops/infra/kubernetes/https-cert/cert.yaml new file mode 100644 index 000000000000..c7a85275ae67 --- /dev/null +++ b/ops/infra/kubernetes/https-cert/cert.yaml @@ -0,0 +1,8 @@ +--- +apiVersion: networking.gke.io/v1beta1 +kind: ManagedCertificate +metadata: + name: {{ .domain | replace "." "-" }} +spec: + domains: + - {{ .domain }} diff --git a/ops/infra/kubernetes/https-lb/ingress.yaml b/ops/infra/kubernetes/https-lb/ingress.yaml new file mode 100644 index 000000000000..069771a4217f --- /dev/null +++ b/ops/infra/kubernetes/https-lb/ingress.yaml @@ -0,0 +1,35 @@ +# This resource configures the HTTPS load balancer that is used as the +# entrypoint to all HTTPS services running in the cluster. +--- +apiVersion: extensions/v1beta1 +kind: Ingress +metadata: + name: https-ingress + annotations: + networking.gke.io/managed-certificates: tazj-in, git-tazj-in, www-tazj-in, oslo-pub +spec: + rules: + # Route blog to the blog ... + - host: tazj.in + http: + paths: + - path: /* + backend: + serviceName: tazblog + servicePort: 8000 + # Route git.tazj.in to the cgit pods + - host: git.tazj.in + http: + paths: + - path: /* + backend: + serviceName: nginx + servicePort: 6756 + # Route oslo.pub to the nginx instance which serves redirects + - host: oslo.pub + http: + paths: + - path: / + backend: + serviceName: nginx + servicePort: 6756 diff --git a/ops/infra/kubernetes/nginx/nginx.conf b/ops/infra/kubernetes/nginx/nginx.conf new file mode 100644 index 000000000000..918aa6067806 --- /dev/null +++ b/ops/infra/kubernetes/nginx/nginx.conf @@ -0,0 +1,59 @@ +daemon off; +worker_processes 1; +error_log stderr; +pid /run/nginx.pid; + +events { + worker_connections 1024; +} + +http { + log_format json_combined escape=json + '{' + '"time_local":"$time_local",' + '"remote_addr":"$remote_addr",' + '"remote_user":"$remote_user",' + '"request":"$request",' + '"status": "$status",' + '"body_bytes_sent":"$body_bytes_sent",' + '"request_time":"$request_time",' + '"http_referrer":"$http_referer",' + '"http_user_agent":"$http_user_agent"' + '}'; + + access_log /dev/stdout json_combined; + + sendfile on; + keepalive_timeout 65; + + server { + listen 80 default_server; + location / { + return 200 "ok"; + } + } + + server { + listen 80; + server_name oslo.pub; + + location / { + return 302 https://www.google.com/maps/d/viewer?mid=1pJIYY9cuEdt9DuMTbb4etBVq7hs; + } + } + + server { + listen 80; + server_name git.tazj.in; + + # Static assets must always hit the root. + location ~ ^/(favicon\.ico|cgit\.(css|png))$ { + proxy_pass http://cgit; + } + + # Everything else hits the depot directly. + location / { + proxy_pass http://cgit/cgit.cgi/depot/; + } + } +} diff --git a/ops/infra/kubernetes/nginx/nginx.yaml b/ops/infra/kubernetes/nginx/nginx.yaml new file mode 100644 index 000000000000..983b265bafab --- /dev/null +++ b/ops/infra/kubernetes/nginx/nginx.yaml @@ -0,0 +1,60 @@ +# Deploy an nginx instance which serves ... redirects. +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: nginx-conf +data: + nginx.conf: {{ insertFile "nginx.conf" | toJson }} +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nginx + labels: + app: nginx +spec: + replicas: 2 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + config: {{ insertFile "nginx.conf" | sha1sum }} + spec: + containers: + - name: tazblog + image: nixery.local/shell/third_party.nginx:{{ .version }} + command: ["/bin/bash", "-c"] + args: + - | + cd /run + echo 'nogroup:x:30000:nobody' >> /etc/group + echo 'nobody:x:30000:30000:nobody:/tmp:/bin/bash' >> /etc/passwd + exec nginx -c /etc/nginx/nginx.conf + volumeMounts: + - name: nginx-conf + mountPath: /etc/nginx + - name: nginx-rundir + mountPath: /run + volumes: + - name: nginx-conf + configMap: + name: nginx-conf + - name: nginx-rundir + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: nginx +spec: + type: NodePort + selector: + app: nginx + ports: + - protocol: TCP + port: 6756 + targetPort: 80 diff --git a/ops/infra/kubernetes/nixery/config.yaml b/ops/infra/kubernetes/nixery/config.yaml new file mode 100644 index 000000000000..0775e79b5843 --- /dev/null +++ b/ops/infra/kubernetes/nixery/config.yaml @@ -0,0 +1,67 @@ +# Deploys an instance of Nixery into the cluster. +# +# The service via which Nixery is exposed has a private DNS entry +# pointing to it, which makes it possible to resolve `nixery.local` +# in-cluster without things getting nasty. +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nixery + namespace: kube-public + labels: + app: nixery +spec: + replicas: 1 + selector: + matchLabels: + app: nixery + template: + metadata: + labels: + app: nixery + spec: + containers: + - name: nixery + image: eu.gcr.io/tazjins-infrastructure/nixery:{{ .version }} + volumeMounts: + - name: nixery-secrets + mountPath: /var/nixery + env: + - name: BUCKET + value: {{ .bucket}} + - name: PORT + value: "{{ .port }}" + - name: GOOGLE_APPLICATION_CREDENTIALS + value: /var/nixery/gcs-key.json + - name: GCS_SIGNING_KEY + value: /var/nixery/gcs-key.pem + - name: GCS_SIGNING_ACCOUNT + value: {{ .account }} + - name: GIT_SSH_COMMAND + value: 'ssh -F /var/nixery/ssh_config' + - name: NIXERY_PKGS_REPO + value: {{ .repo }} + - name: NIX_POPULARITY_URL + value: 'https://storage.googleapis.com/nixery-layers/popularity/{{ .popularity }}' + volumes: + - name: nixery-secrets + secret: + secretName: nixery-secrets + defaultMode: 256 +--- +apiVersion: v1 +kind: Service +metadata: + name: nixery + namespace: kube-public + annotations: + cloud.google.com/load-balancer-type: "Internal" +spec: + selector: + app: nixery + type: LoadBalancer + ports: + - protocol: TCP + port: 80 + targetPort: 8080 diff --git a/ops/infra/kubernetes/nixery/id_nixery.pub b/ops/infra/kubernetes/nixery/id_nixery.pub new file mode 100644 index 000000000000..dc3fd617d0a1 --- /dev/null +++ b/ops/infra/kubernetes/nixery/id_nixery.pub @@ -0,0 +1 @@ +ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCzBM6ydst77jDHNcTFWKD9Fw4SReqyNEEp2MtQBk2wt94U4yLp8MQIuNeOEn1GaDEX4RGCxqai/2UVF1w9ZNdU+v2fXcKWfkKuGQH2XcNfXor2cVNObd40H78++iZiv3nmM/NaEdkTbTBbi925cRy9u5FgItDgsJlyKNRglCb0fr6KlgpvWjL20dp/eeZ8a/gLniHK8PnEsgERQSvJnsyFpxxVhxtoUiyLWpXDl4npf/rQr0eRDf4Q5sN/nbTwksapPHfze8dKcaoA7A2NqT3bJ6DPGrwVCzGRtGw/SXJwFwmmtAl9O6BklpeReyiknSxc+KOtrjDW6O0r6yvymD5Z nixery diff --git a/ops/infra/kubernetes/nixery/known_hosts b/ops/infra/kubernetes/nixery/known_hosts new file mode 100644 index 000000000000..6a2f84b5fb60 --- /dev/null +++ b/ops/infra/kubernetes/nixery/known_hosts @@ -0,0 +1,2 @@ +github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ== +140.82.118.4 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ== diff --git a/ops/infra/kubernetes/nixery/secrets.yaml b/ops/infra/kubernetes/nixery/secrets.yaml new file mode 100644 index 000000000000..d9a674d2c9fc --- /dev/null +++ b/ops/infra/kubernetes/nixery/secrets.yaml @@ -0,0 +1,18 @@ +# The secrets below are encrypted using keys stored in Cloud KMS and +# templated in by kontemplate when deploying. +# +# Not all of the values are actually secret (see the matching) +--- +apiVersion: v1 +kind: Secret +metadata: + name: nixery-secrets + namespace: kube-public +type: Opaque +data: + gcs-key.json: {{ passLookup "nixery-gcs-json" | b64enc }} + gcs-key.pem: {{ passLookup "nixery-gcs-pem" | b64enc }} + id_nixery: {{ printf "%s\n" (passLookup "nixery-ssh-private") | b64enc }} + id_nixery.pub: {{ insertFile "id_nixery.pub" | b64enc }} + known_hosts: {{ insertFile "known_hosts" | b64enc }} + ssh_config: {{ insertFile "ssh_config" | b64enc }} diff --git a/ops/infra/kubernetes/nixery/ssh_config b/ops/infra/kubernetes/nixery/ssh_config new file mode 100644 index 000000000000..78afbb0b039d --- /dev/null +++ b/ops/infra/kubernetes/nixery/ssh_config @@ -0,0 +1,4 @@ +Match host * + User tazjin@google.com + IdentityFile /var/nixery/id_nixery + UserKnownHostsFile /var/nixery/known_hosts diff --git a/ops/infra/kubernetes/primary-cluster.yaml b/ops/infra/kubernetes/primary-cluster.yaml new file mode 100644 index 000000000000..1d5d33e0bb26 --- /dev/null +++ b/ops/infra/kubernetes/primary-cluster.yaml @@ -0,0 +1,38 @@ +# Kontemplate configuration for the primary GKE cluster in the project +# 'tazjins-infrastructure'. +--- +context: gke_tazjins-infrastructure_europe-north1_tazjin-cluster +include: + # SSL certificates (provisioned by Google) + - name: tazj-in-cert + path: https-cert + values: + domain: tazj.in + - name: www-tazj-in-cert + path: https-cert + values: + domain: www.tazj.in + - name: git-tazj-in-cert + path: https-cert + values: + domain: git.tazj.in + - name: oslo-pub-cert + path: https-cert + values: + domain: oslo.pub + + # Services + - name: nixery + values: + port: 8080 + version: xkm36vrbcnzxdccybzdrx4qzfcfqfrhg + bucket: tazjins-data + account: nixery@tazjins-infrastructure.iam.gserviceaccount.com + repo: ssh://tazjin@gmail.com@source.developers.google.com:2022/p/tazjins-infrastructure/r/depot + popularity: 'popularity-nixos-unstable-3140fa89c51233397f496f49014f6b23216667c2.json' + - name: tazblog + - name: cgit + - name: https-lb + - name: nginx + values: + version: a349d5e9145ae9a6c89f62ec631f01fb180de546 diff --git a/ops/infra/kubernetes/tazblog/config.yaml b/ops/infra/kubernetes/tazblog/config.yaml new file mode 100644 index 000000000000..dc63ce8e4b38 --- /dev/null +++ b/ops/infra/kubernetes/tazblog/config.yaml @@ -0,0 +1,34 @@ +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: tazblog + labels: + app: tazblog +spec: + replicas: 2 + selector: + matchLabels: + app: tazblog + template: + metadata: + labels: + app: tazblog + spec: + containers: + - name: tazblog + image: nixery.local/shell/web.tazblog:{{ gitHEAD }} + command: [ "tazblog" ] +--- +apiVersion: v1 +kind: Service +metadata: + name: tazblog +spec: + type: NodePort + selector: + app: tazblog + ports: + - protocol: TCP + port: 8000 + targetPort: 8000 diff --git a/ops/infra/nixos/.gitignore b/ops/infra/nixos/.gitignore new file mode 100644 index 000000000000..773fa1667019 --- /dev/null +++ b/ops/infra/nixos/.gitignore @@ -0,0 +1,3 @@ +hardware-configuration.nix +local-configuration.nix +result diff --git a/ops/infra/nixos/README.md b/ops/infra/nixos/README.md new file mode 100644 index 000000000000..4f2e870f9025 --- /dev/null +++ b/ops/infra/nixos/README.md @@ -0,0 +1,23 @@ +NixOS configuration +=================== + +My NixOS configuration! It configures most of the packages I require +on my systems, sets up Emacs the way I need and does a bunch of other +interesting things. + +In contrast with earlier versions of this configuration, the Nix +channel versions are now pinned in Nix (see the beginning of +[packages.nix][]). + +Machine-local configuration is kept in files with the naming scheme +`$hostname-configuration.nix` and **must** be symlinked to +`local-configuration.nix` before the first configuration run. + +I'm publishing this repository (and my [emacs configuration][]) as a +convenience for myself, but also as a resource that people looking for +example Nix or Emacs configurations can browse through. + +Feel free to ping me with any questions you might have. + +[packages.nix]: packages.nix +[emacs configuration]: https://github.com/tazjin/emacs.d diff --git a/ops/infra/nixos/adho-configuration.nix b/ops/infra/nixos/adho-configuration.nix new file mode 100644 index 000000000000..11c5a97df59e --- /dev/null +++ b/ops/infra/nixos/adho-configuration.nix @@ -0,0 +1,200 @@ +# Local configuration for 'adho' (Thinkpad T470s) +{ config, pkgs, ...}: + +{ + boot.initrd.luks.devices.adho.device = "/dev/disk/by-uuid/722006b0-9654-4ea1-8703-e0cf9ac1905e"; + boot.kernelModules = [ "kvm-intel" ]; + + services.xserver.libinput.enable = true; + services.xserver.videoDrivers = [ "intel" ]; + programs.light.enable = true; + + # Office printer configuration + services.printing.enable = true; + services.printing.drivers = [ pkgs.hplip ]; + services.avahi.enable = true; + services.avahi.nssmdns = true; + + # Enable VirtualBox to update Beatstep Pro firmware: + virtualisation.virtualbox.host.enable = true; + virtualisation.virtualbox.host.enableExtensionPack = true; + + # Enable LXC/LXD for Nixini work + virtualisation.lxd.enable = true; + + # Give me more entropy: + services.haveged.enable = true; + + # Disable sandbox to let work-builds function: + nix.useSandbox = false; + + # Yubikey related: + services.pcscd.enable = true; + environment.systemPackages = with pkgs; [ + cfssl + libp11 + opensc + yubico-piv-tool + ]; + + networking = { + hostName = "adho"; + wireless.enable = true; + wireless.userControlled.enable = true; + + wireless.networks = { + # Welcome to roast club! + "How do I computer?" = { + psk = "washyourface"; + }; + + # On the go! + "Rumpetroll" = { + psk = "fisk1234"; + # If this network exists, chances are that I want it: + priority = 10; + }; + + # Public places in Oslo: + "Abelone" = { + psk = "speakeasy"; + }; + + "Wurst" = { + psk = "wurst2015"; + }; + + "postkontoret" = { + psk = "postkontoret"; + }; + + # Eugene's apartment: + "GET_5G_4FD250" = { + psk = "62636342"; + }; + + # FSCONS 2017 + "uioguest" = {}; + + # Hackeriet! + "hackeriet.no" = { + psk = "hackeriet.no"; + }; + + # Cafe Sara + "Sara Nett" = { + psk = "sarabar1989"; + }; + + # The Dubliner + "DubGjest" = { + # of course + psk = "Guinness"; + }; + + "MAGNAT Guest" = { + psk = "elmolino021"; + }; + + "BrewDog" = { + psk = "welovebeer"; + }; + + # Dima's + "What's a Bad Idea?" = { + psk = "DQDxzrzIvy0YtDwH"; + }; + + # Loke's + "VMC28F76E" = { + psk = "d2ftQnr6xppw"; + }; + + "SafetyWiFi - Teknologihuset" = { + psk = "tech4ever"; + }; + + "Selvaag Pluss" = { + psk = "detlilleekstra"; + }; + + "Langler" = { + psk = "Oslo2018"; + }; + + # Pils & Programmering + "BEKKguest" = { + psk = "guest7890"; + }; + + "Homan-Gjest" = { + psk = "haveaniceday"; + }; + + # Røverstaden + "Roverstaden" = { + psk = "r0verstaden2018"; + }; + + "The Brew Dock" = { + psk = "realbeer"; + }; + + "econ-guest" = { + psk = "Finance2010"; + }; + + "KabelBox-2FD0" = { + psk = "92433048597489095671"; + }; + + "TheKasbah" = { + psk = "couscous"; + }; + + # Kitty's misspelled network. + "How do I Computer?" = { + psk = "herpderpponies"; + }; + + # NixCon 2018 + "Coin Street Community Builders " = { + psk = "3vents2016"; + }; + + "KH2 Gjest" = { + psk = "haenfindag"; + }; + + # Forest & Brown + "Forest Guest" = { + psk = "437B99AC5B"; + }; + + "Gatwick FREE Wi-Fi" = {}; + "mycloud" = {}; + "Norwegian Internet Access" = {}; + "NSB_INTERAKTIV" = {}; + "The Thief" = {}; + "espressohouse" = {}; + "Gotanet Open" = {}; + "wifi.flytoget.no" = {}; + "AIRPORT" = {}; + "ilcaffelovesyou" = {}; + "WIFIonICE" = {}; + "Lorry Gjest" = {}; + "Amundsengjest" = {}; + "Beer Palace Gjest" = {}; + "ibis" = {}; + "GoogleGuest" = {}; + }; + }; + + hardware.bluetooth.enable = true; + + # Configure POSIX queue limits (for work) + systemd.tmpfiles.rules = let mqueue = "/proc/sys/fs/mqueue"; in [ + "w ${mqueue}/msgsize_max - - - - ${toString (64 * 1024)}" + "w ${mqueue}/msg_max - - - - 50" + ]; +} diff --git a/ops/infra/nixos/configuration.nix b/ops/infra/nixos/configuration.nix new file mode 100644 index 000000000000..57f5c56dc798 --- /dev/null +++ b/ops/infra/nixos/configuration.nix @@ -0,0 +1,102 @@ +# Edit this configuration file to define what should be installed on +# your system. Help is available in the configuration.nix(5) man page +# and in the NixOS manual (accessible by running ‘nixos-help’). + +{ config, lib, pkgs, ... }: + +{ + imports = + [ + ./desktop.nix + ./dotfiles.nix + ./hardware-configuration.nix + ./local-configuration.nix + ./mail.nix + ./packages.nix + ]; + + # Use the systemd-boot EFI boot loader. + boot.loader.systemd-boot.enable = true; + boot.loader.efi.canTouchEfiVariables = true; + boot.cleanTmpDir = true; + hardware.pulseaudio.enable = true; + time.timeZone = "Europe/Oslo"; + + # Configure audio setup for JACK + Overtone + boot.kernelModules = [ "snd-seq" "snd-rawmidi" ]; + hardware.pulseaudio.package = pkgs.pulseaudioFull; + + # Update Intel microcode on boot (both machines have Intel CPUs): + hardware.cpu.intel.updateMicrocode = true; + + networking = { + # Don't use ISP's DNS servers: + nameservers = [ + "1.1.1.1" + "1.0.0.1" + ]; + + # Open Chromecast-related ports & servedir + firewall.allowedTCPPorts = [ 3000 5556 5558 ]; + }; + + # Generate an immutable /etc/resolv.conf from the nameserver settings + # above (otherwise DHCP overwrites it): + environment.etc."resolv.conf" = with lib; with pkgs; { + source = writeText "resolv.conf" '' + ${concatStringsSep "\n" (map (ns: "nameserver ${ns}") config.networking.nameservers)} + options edns0 + ''; + }; + + # Configure emacs: + # (actually, that's a lie, this only installs emacs!) + services.emacs = { + install = true; + defaultEditor = true; + package = import ./emacs.nix { inherit pkgs; }; + }; + + services.openssh.enable = true; + + # Enable GNOME keyring (required for Evolution) + services.gnome3.gnome-keyring.enable = true; + + virtualisation = { + # Configure Docker (with socket activation): + # Side note: ... why is this in virtualisation? ... + docker.enable = true; + docker.autoPrune.enable = true; + }; + + # Configure various other applications: + programs = { + java.enable = true; + java.package = pkgs.openjdk; + + fish.enable = true; + ssh.startAgent = true; + }; + + services.postgresql.enable = true; + + # Configure user account + users.defaultUserShell = pkgs.fish; + users.extraUsers.vincent = { + extraGroups = [ "wheel" "docker" "vboxusers" "lxd" ]; + isNormalUser = true; + uid = 1000; + shell = pkgs.fish; + }; + + security.sudo = { + enable = true; + extraConfig = "wheel ALL=(ALL:ALL) SETENV: ALL"; + }; + + # This value determines the NixOS release with which your system is to be + # compatible, in order to avoid breaking some software such as database + # servers. You should change this only after NixOS release notes say you + # should. + system.stateVersion = "18.03"; # Did you read the comment? +} diff --git a/ops/infra/nixos/default.nix b/ops/infra/nixos/default.nix new file mode 100644 index 000000000000..42594f6f5859 --- /dev/null +++ b/ops/infra/nixos/default.nix @@ -0,0 +1,6 @@ +{ ... }: + +builtins.throw '' + The Nix derivations at infra/nixos are not meant to be evaluated + like a derivation as they represent NixOS configuration. +'' diff --git a/ops/infra/nixos/desktop.nix b/ops/infra/nixos/desktop.nix new file mode 100644 index 000000000000..07a6274a568c --- /dev/null +++ b/ops/infra/nixos/desktop.nix @@ -0,0 +1,82 @@ +# Configuration for the desktop environment + +{ config, lib, pkgs, ... }: + +let emacs = import ./emacs.nix { inherit pkgs; }; +screenLock = pkgs.writeShellScriptBin "screen-lock" '' + find ${pkgs.wallpapers} -name "*.png" | shuf -n1 | xargs i3lock -f -t -i +''; +in { + # Configure basic X-server stuff: + services.xserver = { + enable = true; + layout = "us,no"; + xkbOptions = "caps:super, grp:shifts_toggle, parens:swap_brackets"; + exportConfiguration = true; + + # Give EXWM permission to control the session. + displayManager.sessionCommands = "${pkgs.xorg.xhost}/bin/xhost +SI:localuser:$USER"; + + # Use the pre 18.09 default display manager (slim) + displayManager.slim.enable = true; + }; + + # Add a shell script with random screen lock wallpaper selection + environment.systemPackages = [ screenLock ]; + + # Apparently when you have house guests they complain about your screen tearing! + services.compton.enable = true; + services.compton.backend = "xrender"; + + # Configure desktop environment: + services.xserver.windowManager.session = lib.singleton { + name = "exwm"; + start = '' + ${emacs}/bin/emacs --eval '(progn (server-start) (exwm-enable))' + ''; + }; + + # Configure Redshift for Oslo + services.redshift = { + enable = true; + latitude = "59.911491"; + longitude = "10.757933"; + }; + + # Configure fonts + fonts = { + fonts = with pkgs; [ + corefonts + font-awesome-ttf + input-fonts + noto-fonts-cjk + noto-fonts-emoji + powerline-fonts + helvetica-neue-lt-std + ]; + }; + + # Configure random setting of wallpapers + systemd.user.services.feh-wp = { + description = "Randomly set wallpaper via feh"; + serviceConfig = { + Type = "oneshot"; + WorkingDirectory = "${pkgs.wallpapers}/share/wallpapers"; + + # Manually shuffle because feh's --randomize option can't be restricted to + # just certain file types. + ExecStart = "${pkgs.bash}/bin/bash -c '${pkgs.fd}/bin/fd -atf | shuf | head -n1 | ${pkgs.findutils}/bin/xargs ${pkgs.feh}/bin/feh --bg-fill'"; + }; + }; + + systemd.user.timers.feh-wp = { + description = "Set a random wallpaper every hour"; + wantedBy = [ "graphical-session.target" ]; + partOf = [ "graphical-session.target" ]; + + timerConfig = { + OnActiveSec = "1second"; + OnUnitActiveSec = "1hour"; + }; + }; +} diff --git a/ops/infra/nixos/dotfiles.nix b/ops/infra/nixos/dotfiles.nix new file mode 100644 index 000000000000..2e952207d47d --- /dev/null +++ b/ops/infra/nixos/dotfiles.nix @@ -0,0 +1,27 @@ +# Bundle configuration files into a derivation. +# I call this derivation dotfiles despite that not technically being true +# anymore ... + +{ config, pkgs, ...}: + +let dotfiles = pkgs.stdenv.mkDerivation { + name = "tazjins-dotfiles"; + + srcs = [ + ./dotfiles + ]; + + installPhase = '' + mkdir -p $out + cp ./* $out/ + ''; +}; +in { + # /etc/ is a special place in NixOS! + # Symlinks that need to be created there must be specified explicitly. + environment.etc = { + "alacritty.yml".source = "${dotfiles}/alacritty.yml"; + "fish/config.fish".source = "${dotfiles}/config.fish"; + "tmux.conf".source = "${dotfiles}/tmux.conf"; + }; +} diff --git a/ops/infra/nixos/dotfiles/alacritty.yml b/ops/infra/nixos/dotfiles/alacritty.yml new file mode 100644 index 000000000000..d229fbdde67f --- /dev/null +++ b/ops/infra/nixos/dotfiles/alacritty.yml @@ -0,0 +1,203 @@ +# Configuration for Alacritty, the GPU enhanced terminal emulator + +# Any items in the `env` entry below will be added as +# environment variables. Some entries may override variables +# set by alacritty it self. +env: + TERM: xterm-256color + +window: + # TODO + decorations: full + +scrolling: + history: 10000 + multiplier: 3 + faux_multiplier: 3 + auto_scroll: true # TODO + +# Display tabs using this many cells (changes require restart) +tabspaces: 4 + +# When true, bold text is drawn using the bright variant of colors. +draw_bold_text_with_bright_colors: true + +# Font configuration (changes require restart) +font: + # The normal (roman) font face to use. + normal: + family: Input Mono + bold: + family: Input Mono + italic: + family: Input Mono + + # Point size of the font + size: 12.0 + + # Scale the font size based on the monitor's DPI. + scale_with_dpi: false + +# Use custom cursor colors. If true, display the cursor in the cursor.foreground +# and cursor.background colors, otherwise invert the colors of the cursor. +custom_cursor_colors: false + +# Colors (Gruber Darker) +colors: + # Default colors + primary: + background: '0x181818' + foreground: '0xe4e4ef' + + # Colors the cursor will use if `custom_cursor_colors` is true + cursor: + text: '0x000000' + cursor: '0xf5f5f5' + + # Normal colors + normal: + black: '0x282828' + red: '0xf43841' + green: '0x73c936' + yellow: '0xffdd33' + blue: '0x96a6c8' + magenta: '0x9e95c7' + cyan: '0x1fad83' + white: '0xf5f5f5' + + # Bright colors + bright: + black: '0x484848' + red: '0xff4f58' + green: '0x73c936' + yellow: '0xffdd33' + blue: '0x5f627f' + magenta: '0x9e95c7' + cyan: '0x1fad83' + white: '0xffffff' + +# Background opacity +# Key bindings +# +# Each binding is defined as an object with some properties. Most of the +# properties are optional. All of the alphabetical keys should have a letter for +# the `key` value such as `V`. Function keys are probably what you would expect +# as well (F1, F2, ..). The number keys above the main keyboard are encoded as +# `Key1`, `Key2`, etc. Keys on the number pad are encoded `Number1`, `Number2`, +# etc. These all match the glutin::VirtualKeyCode variants. +# +# Possible values for `mods` +# `Command`, `Super` refer to the super/command/windows key +# `Control` for the control key +# `Shift` for the Shift key +# `Alt` and `Option` refer to alt/option +# +# mods may be combined with a `|`. For example, requiring control and shift +# looks like: +# +# mods: Control|Shift +# +# The parser is currently quite sensitive to whitespace and capitalization - +# capitalization must match exactly, and piped items must not have whitespace +# around them. +# +# Either an `action`, `chars`, or `command` field must be present. +# `action` must be one of `Paste`, `PasteSelection`, `Copy`, or `Quit`. +# `chars` writes the specified string every time that binding is activated. +# These should generally be escape sequences, but they can be configured to +# send arbitrary strings of bytes. +# `command` must be a map containing a `program` string, and `args` array of +# strings. For example: +# - { ... , command: { program: "alacritty", args: ["-e", "vttest"] } } +# +# Want to add a binding (e.g. "PageUp") but are unsure what the X sequence +# (e.g. "\x1b[5~") is? Open another terminal (like xterm) without tmux, +# then run `showkey -a` to get the sequence associated to a key combination. +key_bindings: + - { key: V, mods: Control|Shift, action: Paste } + - { key: C, mods: Control|Shift, action: Copy } + - { key: Q, mods: Command, action: Quit } + - { key: W, mods: Command, action: Quit } + - { key: Insert, mods: Shift, action: PasteSelection } + - { key: Home, chars: "\x1bOH", mode: AppCursor } + - { key: Home, chars: "\x1b[H", mode: ~AppCursor } + - { key: End, chars: "\x1bOF", mode: AppCursor } + - { key: End, chars: "\x1b[F", mode: ~AppCursor } + - { key: PageUp, mods: Shift, chars: "\x1b[5;2~" } + - { key: PageUp, mods: Control, chars: "\x1b[5;5~" } + - { key: PageUp, chars: "\x1b[5~" } + - { key: PageDown, mods: Shift, chars: "\x1b[6;2~" } + - { key: PageDown, mods: Control, chars: "\x1b[6;5~" } + - { key: PageDown, chars: "\x1b[6~" } + - { key: Left, mods: Shift, chars: "\x1b[1;2D" } + - { key: Left, mods: Control, chars: "\x1b[1;5D" } + - { key: Left, mods: Alt, chars: "\x1b[1;3D" } + - { key: Left, chars: "\x1b[D", mode: ~AppCursor } + - { key: Left, chars: "\x1bOD", mode: AppCursor } + - { key: Right, mods: Shift, chars: "\x1b[1;2C" } + - { key: Right, mods: Control, chars: "\x1b[1;5C" } + - { key: Right, mods: Alt, chars: "\x1b[1;3C" } + - { key: Right, chars: "\x1b[C", mode: ~AppCursor } + - { key: Right, chars: "\x1bOC", mode: AppCursor } + - { key: Up, mods: Shift, chars: "\x1b[1;2A" } + - { key: Up, mods: Control, chars: "\x1b[1;5A" } + - { key: Up, mods: Alt, chars: "\x1b[1;3A" } + - { key: Up, chars: "\x1b[A", mode: ~AppCursor } + - { key: Up, chars: "\x1bOA", mode: AppCursor } + - { key: Down, mods: Shift, chars: "\x1b[1;2B" } + - { key: Down, mods: Control, chars: "\x1b[1;5B" } + - { key: Down, mods: Alt, chars: "\x1b[1;3B" } + - { key: Down, chars: "\x1b[B", mode: ~AppCursor } + - { key: Down, chars: "\x1bOB", mode: AppCursor } + - { key: Tab, mods: Shift, chars: "\x1b[Z" } + - { key: F1, chars: "\x1bOP" } + - { key: F2, chars: "\x1bOQ" } + - { key: F3, chars: "\x1bOR" } + - { key: F4, chars: "\x1bOS" } + - { key: F5, chars: "\x1b[15~" } + - { key: F6, chars: "\x1b[17~" } + - { key: F7, chars: "\x1b[18~" } + - { key: F8, chars: "\x1b[19~" } + - { key: F9, chars: "\x1b[20~" } + - { key: F10, chars: "\x1b[21~" } + - { key: F11, chars: "\x1b[23~" } + - { key: F12, chars: "\x1b[24~" } + - { key: Back, chars: "\x7f" } + - { key: Back, mods: Alt, chars: "\x1b\x7f" } + - { key: Insert, chars: "\x1b[2~" } + - { key: Delete, chars: "\x1b[3~" } + +# Mouse bindings +# +# Currently doesn't support modifiers. Both the `mouse` and `action` fields must +# be specified. +# +# Values for `mouse`: +# - Middle +# - Left +# - Right +# - Numeric identifier such as `5` +# +# Values for `action`: +# - Paste +# - PasteSelection +# - Copy (TODO) +mouse_bindings: + - { mouse: Middle, action: PasteSelection } + +mouse: + double_click: { threshold: 300 } + triple_click: { threshold: 300 } + +selection: + semantic_escape_chars: ",│`|:\"' ()[]{}<>" +background_opacity: 1.0 + +hide_cursor_when_typing: false + +# Live config reload (changes require restart) +live_config_reload: true + +# Disable visual bell +visual_bell: + duration: 0 diff --git a/ops/infra/nixos/dotfiles/config.fish b/ops/infra/nixos/dotfiles/config.fish new file mode 100644 index 000000000000..de2c99ae6007 --- /dev/null +++ b/ops/infra/nixos/dotfiles/config.fish @@ -0,0 +1,40 @@ +# Configure classic prompt +set fish_color_user --bold blue +set fish_color_cwd --bold white + +# Enable colour hints in VCS prompt: +set __fish_git_prompt_showcolorhints yes +set __fish_git_prompt_color_prefix purple +set __fish_git_prompt_color_suffix purple + +# Fish configuration +set fish_greeting "" +set PATH $HOME/.local/bin $HOME/.cargo/bin $PATH + +# Editor configuration +set -gx EDITOR "emacsclient" +set -gx ALTERNATE_EDITOR "emacs -q -nw" +set -gx VISUAL "emacsclient" + +# Miscellaneous +eval (direnv hook fish) + +# Useful command aliases +alias gpr 'git pull --rebase' +alias gco 'git checkout' +alias gf 'git fetch' +alias gap 'git add -p' +alias pbcopy 'xclip -selection clipboard' +alias edit 'emacsclient -n' +alias servedir 'nix-shell -p haskellPackages.wai-app-static --run warp' + +# Old habits die hard (also ls is just easier to type): +alias ls 'exa' + +# Fix up nix-env & friends for Nix 2.0 +export NIX_REMOTE=daemon + +# Fix display of fish in emacs' term-mode: +function fish_title + true +end diff --git a/ops/infra/nixos/dotfiles/msmtprc b/ops/infra/nixos/dotfiles/msmtprc new file mode 100644 index 000000000000..624b6a77fc4b --- /dev/null +++ b/ops/infra/nixos/dotfiles/msmtprc @@ -0,0 +1,16 @@ +defaults + +port 587 +tls on +tls_trust_file /etc/ssl/certs/ca-certificates.crt + +# Runbox mail +account runbox +from mail@tazj.in +host mail.runbox.com +auth on +user mail@tazj.in +passwordeval pass show general/runbox-tazjin + +# Use Runbox as default +account default : runbox diff --git a/ops/infra/nixos/dotfiles/notmuch-config b/ops/infra/nixos/dotfiles/notmuch-config new file mode 100644 index 000000000000..a490774e635f --- /dev/null +++ b/ops/infra/nixos/dotfiles/notmuch-config @@ -0,0 +1,21 @@ +# .notmuch-config - Configuration file for the notmuch mail system +# +# For more information about notmuch, see https://notmuchmail.org + +[database] +path=/home/vincent/mail + +[user] +name=Vincent Ambo +primary_email=mail@tazj.in +other_email=tazjin@gmail.com; + +[new] +tags=unread;inbox; +ignore= + +[search] +exclude_tags=deleted;spam;draft; + +[maildir] +synchronize_flags=true diff --git a/ops/infra/nixos/dotfiles/offlineimaprc b/ops/infra/nixos/dotfiles/offlineimaprc new file mode 100644 index 000000000000..78315447e4bd --- /dev/null +++ b/ops/infra/nixos/dotfiles/offlineimaprc @@ -0,0 +1,39 @@ +[general] +accounts = tazjin, gmail + +[DEFAULT] +ssl = yes +sslcacertfile = /etc/ssl/certs/ca-certificates.crt + +# Private GMail account (old): +[Account gmail] +maxage = 90 +localrepository = gmail-local +remoterepository = gmail-remote +synclabels = yes + +[Repository gmail-local] +type = GmailMaildir +localfolders = ~/mail/gmail + +[Repository gmail-remote] +type = Gmail +remoteuser = tazjin@gmail.com +remotepassfile = ~/.config/mail/gmail-pass +folderfilter = lambda folder: folder == 'INBOX' + +# Main private account: +[Account tazjin] +localrepository = tazjin-local +remoterepository = tazjin-remote + +[Repository tazjin-local] +type = Maildir +localfolders = ~/mail/tazjin + +[Repository tazjin-remote] +type = IMAP +remotehost = mail.runbox.com +remoteuser = mail@tazj.in +remotepassfile = ~/.config/mail/tazjin-pass +auth_mechanisms = LOGIN diff --git a/ops/infra/nixos/dotfiles/tmux.conf b/ops/infra/nixos/dotfiles/tmux.conf new file mode 100644 index 000000000000..6c20ae0370b2 --- /dev/null +++ b/ops/infra/nixos/dotfiles/tmux.conf @@ -0,0 +1,14 @@ +set -g status off +set -gw mode-keys emacs +setw -g mouse on + +# Correctly set window titles +set -g set-titles on +set -g set-titles-string "#W (#T)" + +# List of plugins +set -g @plugin 'tmux-plugins/tpm' +set -g @plugin 'tmux-plugins/tmux-yank' + +# Initialize TMUX plugin manager (keep this line at the very bottom of tmux.conf) +run '~/.tmux/plugins/tpm/tpm' diff --git a/ops/infra/nixos/home.nix b/ops/infra/nixos/home.nix new file mode 100644 index 000000000000..236091cb019d --- /dev/null +++ b/ops/infra/nixos/home.nix @@ -0,0 +1,75 @@ +# home-manager configuration used on ChromeOS systems + +{ config, pkgs, ... }: + +{ + # Allow non-free software (fonts, IDEA, etc.): + nixpkgs.config.allowUnfree = true; + + # Install various useful packages: + home.packages = with pkgs; [ + bat + exa + gnupg + google-cloud-sdk + htop + pass + ripgrep + tdesktop + transmission + tree + + # Fonts to make available in X11 applications: + input-fonts + + # Emacs configuration stays in the normal ~/.emacs.d location (for + # now), hence this package is not installed via `programs.emacs`. + (import ./emacs.nix { inherit pkgs; }) + ]; + + programs.git = { + enable = true; + userEmail = "mail@tazj.in"; + userName = "Vincent Ambo"; + }; + + services.gpg-agent = { + enable = true; + extraConfig = '' + pinentry-program ${pkgs.pinentry}/bin/pinentry-gtk-2 + allow-emacs-pinentry + ''; + }; + + # Let Home Manager install and manage itself. + programs.home-manager.enable = true; + manual.html.enable = true; + + # Shell configuration + # + # There are some differences between the ChromeOS / NixOS + # configurations, so instead of fixing up the dotfile to support + # both I opted for keeping the configuration here. + programs.fish = { + enable = true; + interactiveShellInit = '' + # Configure classic prompt + set fish_color_user --bold blue + set fish_color_cwd --bold white + + # Enable colour hints in VCS prompt: + set __fish_git_prompt_showcolorhints yes + set __fish_git_prompt_color_prefix purple + set __fish_git_prompt_color_suffix purple + + # Fish configuration + set fish_greeting "" + + # Fix up nix-env & friends for Nix 2.0 + export NIX_REMOTE=daemon + ''; + }; + + # Ensure fonts installed via Nix are picked up. + fonts.fontconfig.enableProfileFonts = true; +} diff --git a/ops/infra/nixos/mail.nix b/ops/infra/nixos/mail.nix new file mode 100644 index 000000000000..ba4ebfa06026 --- /dev/null +++ b/ops/infra/nixos/mail.nix @@ -0,0 +1,77 @@ +# This file configures offlineimap, notmuch and MSMTP. +# +# Some manual configuration is required the first time this is +# applied: +# +# 1. Credential setup. +# 2. Linking of MSMTP config (ln -s /etc/msmtprc ~/.msmtprc) +# 3. Linking of notmuch config (ln -s /etc/notmuch-config ~/.notmuch-config) + +{ config, lib, pkgs, ... }: + +let offlineImapConfig = pkgs.writeText "offlineimaprc" + (builtins.readFile ./dotfiles/offlineimaprc); + +msmtpConfig = pkgs.writeText "msmtprc" + (builtins.readFile ./dotfiles/msmtprc); + +notmuchConfig = pkgs.writeText "notmuch-config" + (builtins.readFile ./dotfiles/notmuch-config); + +tagConfig = pkgs.writeText "notmuch-tags" '' + # Tag emacs-devel mailing list: + -inbox +emacs-devel -- to:emacs-devel@gnu.org OR cc:emacs-devel@gnu.org + + # Tag nix-devel mailing list & discourse: + -inbox +nix-devel -- to:nix-devel@googlegroups.com OR from:nixos1@discoursemail.com + + # Tag my own mail (from other devices) as sent: + -inbox +sent -- from:mail@tazj.in + + # Drafts are always read, duh. + -unread -- tag:draft +''; + +notmuchIndex = pkgs.writeShellScriptBin "notmuch-index" '' + echo "Indexing new mails in notmuch" + + # Index new mail + ${pkgs.notmuch}/bin/notmuch new + + # Apply tags + cat ${tagConfig} | ${pkgs.notmuch}/bin/notmuch tag --batch + + echo "Done indexing new mails" +''; +in { + # Enable OfflineIMAP timer & service: + systemd.user.timers.offlineimap = { + description = "OfflineIMAP timer"; + wantedBy = [ "timers.target" ]; + + timerConfig = { + Unit = "offlineimap.service"; + OnCalendar = "*:0/2"; # every 2 minutes + Persistent = "true"; # persist timer state after reboots + }; + }; + + systemd.user.services.offlineimap = { + description = "OfflineIMAP service"; + path = with pkgs; [ pass notmuch ]; + + serviceConfig = { + Type = "oneshot"; + ExecStart = "${pkgs.offlineimap}/bin/offlineimap -u syslog -o -c ${offlineImapConfig}"; + ExecStartPost = "${notmuchIndex}/bin/notmuch-index"; + TimeoutStartSec = "2min"; + }; + }; + + # Link configuration files to /etc/ (from where they will be linked + # further): + environment.etc = { + "msmtprc".source = msmtpConfig; + "notmuch-config".source = notmuchConfig; + }; +} diff --git a/ops/infra/nixos/packages.nix b/ops/infra/nixos/packages.nix new file mode 100644 index 000000000000..b90a4a9ee8b4 --- /dev/null +++ b/ops/infra/nixos/packages.nix @@ -0,0 +1,132 @@ +# This file contains configuration for packages to install. +# It does not contain configuration for software that is already covered +# by other NixOS options (e.g. emacs) + +{ config, pkgs, ... }: + +let + fetchChannel = { rev, sha256 }: import (fetchTarball { + inherit sha256; + url = "https://github.com/NixOS/nixpkgs-channels/archive/${rev}.tar.gz"; + }) { config.allowUnfree = true; }; + + # Channels last updated: 2018-10-10 + # + # Instead of relying on Nix channels and ending up with out-of-sync + # situations between machines, the commit for the stable Nix channel + # is pinned here. + stable = fetchChannel { + rev = "d96c7a356383302db4426a0d5a8383af921d964f"; + sha256 = "0hlhczh3m077rwrhp4smf3zd2sfj38h2c126bycv66m0aff0gycn"; + }; + + # Certain packages from unstable are hand-picked into the package + # set. + unstable = fetchChannel { + rev = "32bcd72bf28a971c9063a9cdcc32effe49f49331"; + sha256 = "1f74m18r6xl9s55jbkj9bjhdxg2489kwjam4d96pf9rzq0i1f8li"; + }; +in { + # Configure the Nix package manager + nixpkgs = { + config.allowUnfree = true; + # To use the pinned channel, the original package set is thrown + # away in the overrides: + config.packageOverrides = oldPkgs: stable // { + # Store whole unstable channel in case that other modules need + # it (see emacs.nix for example): + inherit unstable; + + # Backport Exa from unstable until a fix for the Rust builder is + # backported. + # + # https://github.com/NixOS/nixpkgs/pull/48020 + exa = unstable.exa; + + wallpapers = import ./pkgs/wallpapers.nix; + pulseaudio-ctl = import pkgs/pulseaudio-ctl.nix; + }; + }; + + # ... and declare packages to be installed. + environment.systemPackages = with pkgs; [ + # Default nixos.* packages: + alacritty + binutils-unwrapped + chromium + curl + direnv + dnsutils + dotnet-sdk + evince + exa + extremetuxracer + fd + file + firefox-unwrapped + fish + gcc + git + gnumake + gnupg + google-cloud-sdk + gopass + hicolor-icon-theme + htop + i3lock + iftop + jq + kontemplate + kubernetes + lispPackages.quicklisp + lxappearance-gtk3 + manpages + maven + mono + mq-cli + msmtp + ngrok + notmuch + numix-cursor-theme + numix-gtk-theme + numix-icon-theme + offlineimap + openjdk + openssl + openssl.dev + pass + pavucontrol + pkgconfig + pulseaudio-ctl + pwgen + ripgrep + rustup + sbcl + screen + siege + spotify + stdmanpages + systemd.dev + tdesktop + terraform + tig + tmux + tokei + transmission + tree + units + unzip + vlc + xclip + xfce.xfce4-screenshooter + + # Haskell packages: + cabal-install + ghc + hlint + stack + stack2nix + haskellPackages.stylish-haskell + haskellPackages.yesod-bin + ]; +} diff --git a/ops/infra/nixos/stallo-configuration.nix b/ops/infra/nixos/stallo-configuration.nix new file mode 100644 index 000000000000..4af4a5fd4c22 --- /dev/null +++ b/ops/infra/nixos/stallo-configuration.nix @@ -0,0 +1,39 @@ +# Local configuration for 'stallo' (Home desktop PC) +{ config, pkgs, ...}: + +{ + boot.initrd.luks.devices.stallo-luks.device = "/dev/disk/by-uuid/b484cf1e-a27b-4785-8bd6-fa85a004b073"; + + # Use proprietary nvidia driver + services.xserver.videoDrivers = [ "nvidia" ]; + + # Enable 32-bit compatibility for Steam: + hardware.opengl.driSupport32Bit = true; + hardware.pulseaudio.support32Bit = true; + + # Wine for Blizzard stuff + environment.systemPackages = with pkgs.unstable; [ wineWowPackages.staging winetricks ]; + + networking = { + hostName = "stallo"; + wireless.enable = true; + wireless.networks = { + # Welcome to roast club! + + "How do I computer fast?" = { + psk = "washyourface"; + # Prefer 5Ghz unless the card is acting up. + priority = 10; + }; + + "How do I computer?" = { + psk = "washyourface"; + }; + }; + # IPv6 at home, of course: + nameservers = [ + "2606:4700:4700::1111" + "2606:4700:4700::1001" + ]; + }; +} 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..40bdc962800a --- /dev/null +++ b/ops/journaldriver/Cargo.lock @@ -0,0 +1,816 @@ +[[package]] +name = "aho-corasick" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ascii" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "atty" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "backtrace" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "backtrace-sys" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "base64" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "bitflags" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "byteorder" +version = "1.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cc" +version = "1.0.25" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cfg-if" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "chrono" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "chunked_transfer" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "cloudabi" +version = "0.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cookie" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "core-foundation-sys" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "cstr-argument" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "env_logger" +version = "0.5.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", + "humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "failure" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", + "failure_derive 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "failure_derive" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", + "synstructure 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "humantime" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "idna" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "itoa" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "journaldriver" +version = "1.1.0" +dependencies = [ + "chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)", + "failure 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "medallion 2.2.3 (registry+https://github.com/rust-lang/crates.io-index)", + "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "systemd 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "ureq 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "lazy_static" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.43" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "libsystemd-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "log" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "matches" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "medallion" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl 0.10.12 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "memchr" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "memchr" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "native-tls" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl 0.10.12 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-sys 0.9.36 (registry+https://github.com/rust-lang/crates.io-index)", + "schannel 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)", + "security-framework 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "security-framework-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "tempfile 3.0.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-integer" +version = "0.1.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "num-traits" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "openssl" +version = "0.10.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-sys 0.9.36 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "openssl-probe" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "openssl-sys" +version = "0.9.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", + "vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "percent-encoding" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "pkg-config" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "proc-macro2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "qstring" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "quick-error" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "quote" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand_core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "redox_syscall" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "redox_termios" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "regex" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "aho-corasick 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", + "memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "regex-syntax 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "utf8-ranges 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "regex-syntax" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "remove_dir_all" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "ryu" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "safemem" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "schannel" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "security-framework" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "security-framework-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "security-framework-sys" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "serde" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "serde_derive" +version = "1.0.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.15.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "serde_json" +version = "1.0.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", + "ryu 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "syn" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "synstructure" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "systemd" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cstr-argument 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "libsystemd-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "utf8-cstr 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "tempfile" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "termcolor" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "termion" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "thread_local" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "time" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)", + "redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ucd-util" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "unicode-bidi" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "unicode-normalization" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "unicode-xid" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "ureq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "ascii 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)", + "base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", + "chunked_transfer 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "native-tls 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "qstring 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "url" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", + "percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "utf8-cstr" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "utf8-ranges" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "vcpkg" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "version_check" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-util" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "wincolor" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum aho-corasick 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "68f56c7353e5a9547cbd76ed90f7bb5ffc3ba09d4ea9bd1d8c06c8b1142eeb5a" +"checksum ascii 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a5fc969a8ce2c9c0c4b0429bb8431544f6658283c8326ba5ff8c762b75369335" +"checksum atty 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "9a7d5b8723950951411ee34d271d99dddcc2035a16ab25310ea2c8cfd4369652" +"checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a" +"checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0" +"checksum base64 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "489d6c0ed21b11d038c31b6ceccca973e65d73ba3bd8ecb9a2babf5546164643" +"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" +"checksum byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "90492c5858dd7d2e78691cfb89f90d273a2800fc11d98f60786e5d87e2f83781" +"checksum cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "f159dfd43363c4d08055a07703eb7a3406b0dac4d0584d96965a3262db3c9d16" +"checksum cfg-if 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0c4e7bb64a8ebb0d856483e1e682ea3422f883c5f5615a90d51a2c82fe87fdd3" +"checksum chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "45912881121cb26fad7c38c17ba7daa18764771836b34fab7d3fbd93ed633878" +"checksum chunked_transfer 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "498d20a7aaf62625b9bf26e637cf7736417cde1d0c99f1d04d1170229a85cf87" +"checksum cloudabi 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" +"checksum cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1465f8134efa296b4c19db34d909637cb2bf0f7aaf21299e23e18fa29ac557cf" +"checksum core-foundation 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "286e0b41c3a20da26536c6000a280585d519fd07b3956b43aed8a79e9edce980" +"checksum core-foundation-sys 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "716c271e8613ace48344f723b60b900a93150271e5be206212d052bbc0883efa" +"checksum cstr-argument 0.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "514570a4b719329df37f93448a70df2baac553020d0eb43a8dfa9c1f5ba7b658" +"checksum env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)" = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38" +"checksum failure 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7efb22686e4a466b1ec1a15c2898f91fa9cb340452496dca654032de20ff95b9" +"checksum failure_derive 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "946d0e98a50d9831f5d589038d2ca7f8f455b1c21028c0db0e84116a12696426" +"checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +"checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +"checksum humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e" +"checksum idna 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" +"checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" +"checksum lazy_static 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ca488b89a5657b0a2ecd45b95609b3e848cf1755da332a0da46e2b2b1cb371a7" +"checksum libc 0.2.43 (registry+https://github.com/rust-lang/crates.io-index)" = "76e3a3ef172f1a0b9a9ff0dd1491ae5e6c948b94479a3021819ba7d860c8645d" +"checksum libsystemd-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e751b723417158e0949ba470bee4affd6f1dd6b67622b5240d79186631b6a0d9" +"checksum log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fcce5fa49cc693c312001daf1d13411c4a5283796bac1084299ea3e567113f" +"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" +"checksum medallion 2.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b2e6f0713b388174fc3de9b63a0a63dfcee191a8abc8e06c0a9c6d80821c1891" +"checksum memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "148fab2e51b4f1cfc66da2a7c32981d1d3c083a803978268bb11fe4b86925e7a" +"checksum memchr 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4b3629fe9fdbff6daa6c33b90f7c08355c1aca05a3d01fa8063b822fcf185f3b" +"checksum native-tls 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8b0a7bd714e83db15676d31caf968ad7318e9cc35f93c85a90231c8f22867549" +"checksum num-integer 0.1.39 (registry+https://github.com/rust-lang/crates.io-index)" = "e83d528d2677f0518c570baf2b7abdcf0cd2d248860b68507bdcb3e91d4c0cea" +"checksum num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0b3a5d7cc97d6d30d8b9bc8fa19bf45349ffe46241e8816f50f62f6d6aaabee1" +"checksum openssl 0.10.12 (registry+https://github.com/rust-lang/crates.io-index)" = "5e2e79eede055813a3ac52fb3915caf8e1c9da2dec1587871aec9f6f7b48508d" +"checksum openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" +"checksum openssl-sys 0.9.36 (registry+https://github.com/rust-lang/crates.io-index)" = "409d77eeb492a1aebd6eb322b2ee72ff7c7496b4434d98b3bf8be038755de65e" +"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" +"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c" +"checksum proc-macro2 0.4.20 (registry+https://github.com/rust-lang/crates.io-index)" = "3d7b7eaaa90b4a90a932a9ea6666c95a389e424eff347f0f793979289429feee" +"checksum qstring 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "545ec057a36a93e25fb5883baed912e4984af4e2543bbf0e3463d962e0408469" +"checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" +"checksum quote 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "dd636425967c33af890042c483632d33fa7a18f19ad1d7ea72e8998c6ef8dea5" +"checksum rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e464cd887e869cddcae8792a4ee31d23c7edd516700695608f5b98c67ee0131c" +"checksum rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1961a422c4d189dfb50ffa9320bf1f2a9bd54ecb92792fb9477f99a1045f3372" +"checksum rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0905b6b7079ec73b314d4c748701f6931eb79fd97c668caa3f1899b22b32c6db" +"checksum redox_syscall 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "c214e91d3ecf43e9a4e41e578973adeb14b474f2bee858742d127af75a0112b1" +"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76" +"checksum regex 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2069749032ea3ec200ca51e4a31df41759190a88edca0d2d86ee8bedf7073341" +"checksum regex-syntax 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "747ba3b235651f6e2f67dfa8bcdcd073ddb7c243cb21c442fc12395dfcac212d" +"checksum remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3488ba1b9a2084d38645c4c08276a1752dcbf2c7130d74f1569681ad5d2799c5" +"checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395" +"checksum ryu 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7153dd96dade874ab973e098cb62fcdbb89a03682e46b144fd09550998d4a4a7" +"checksum safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dca453248a96cb0749e36ccdfe2b0b4e54a61bfef89fb97ec621eb8e0a93dd9" +"checksum schannel 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "0e1a231dc10abf6749cfa5d7767f25888d484201accbd919b66ab5413c502d56" +"checksum security-framework 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "697d3f3c23a618272ead9e1fb259c1411102b31c6af8b93f1d64cca9c3b0e8e0" +"checksum security-framework-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab01dfbe5756785b5b4d46e0289e5a18071dfa9a7c2b24213ea00b9ef9b665bf" +"checksum serde 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)" = "84257ccd054dc351472528c8587b4de2dbf0dc0fe2e634030c1a90bfdacebaa9" +"checksum serde_derive 1.0.79 (registry+https://github.com/rust-lang/crates.io-index)" = "31569d901045afbff7a9479f793177fe9259819aff10ab4f89ef69bbc5f567fe" +"checksum serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)" = "43344e7ce05d0d8280c5940cabb4964bea626aa58b1ec0e8c73fa2a8512a38ce" +"checksum syn 0.14.9 (registry+https://github.com/rust-lang/crates.io-index)" = "261ae9ecaa397c42b960649561949d69311f08eeaea86a65696e6e46517cf741" +"checksum syn 0.15.8 (registry+https://github.com/rust-lang/crates.io-index)" = "356d1c5043597c40489e9af2d2498c7fefc33e99b7d75b43be336c8a59b3e45e" +"checksum synstructure 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "85bb9b7550d063ea184027c9b8c20ac167cd36d3e06b3a40bceb9d746dc1a7b7" +"checksum systemd 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1b62a732355787f960c25536210ae0a981aca2e5dae9dab8491bdae39613ce48" +"checksum tempfile 3.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "55c1195ef8513f3273d55ff59fe5da6940287a0d7a98331254397f464833675b" +"checksum termcolor 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "4096add70612622289f2fdcdbd5086dc81c1e2675e6ae58d6c4f62a16c6d7f2f" +"checksum termion 1.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "689a3bdfaab439fd92bc87df5c4c78417d3cbe537487274e9b0b2dce76e92096" +"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" +"checksum time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)" = "d825be0eb33fda1a7e68012d51e9c7f451dc1a69391e7fdc197060bb8c56667b" +"checksum ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d" +"checksum unicode-bidi 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "49f2bd0c6468a8230e1db229cff8029217cf623c767ea5d60bfbd42729ea54d5" +"checksum unicode-normalization 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "6a0180bc61fc5a987082bfa111f4cc95c4caff7f9799f3e46df09163a937aa25" +"checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" +"checksum ureq 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "5f3f941c0434783c82e46d30508834be5f3c1f2c85dd1b98f0681984c7be8e03" +"checksum url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2a321979c09843d272956e73700d12c4e7d3d92b2ee112b31548aef0d4efc5a6" +"checksum utf8-cstr 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "55bcbb425141152b10d5693095950b51c3745d019363fc2929ffd8f61449b628" +"checksum utf8-ranges 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd70f467df6810094968e2fce0ee1bd0e87157aceb026a8c083bcf5e25b9efe4" +"checksum vcpkg 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "def296d3eb3b12371b2c7d0e83bfe1403e4db2d7a0bba324a12b21c4ee13143d" +"checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" +"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "afc5508759c5bf4285e61feb862b6083c8480aec864fa17a81fdec6f69b461ab" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +"checksum wincolor 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "561ed901ae465d6185fa7864d63fbd5720d0ef718366c9a4dc83cf6170d7e9ba" diff --git a/ops/journaldriver/Cargo.toml b/ops/journaldriver/Cargo.toml new file mode 100644 index 000000000000..248b22807fe1 --- /dev/null +++ b/ops/journaldriver/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "journaldriver" +version = "1.1.0" +authors = ["Vincent Ambo <mail@tazj.in>"] +license = "GPL-3.0-or-later" + +[dependencies] +chrono = { version = "0.4", features = [ "serde" ]} +env_logger = "0.5" +failure = "0.1" +lazy_static = "1.0" +log = "0.4" +medallion = "2.2" +serde = "1.0" +serde_derive = "1.0" +serde_json = "1.0" +systemd = "0.3" +ureq = { version = "0.6.2", features = [ "json" ]} + +[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..d64c82a88a71 --- /dev/null +++ b/ops/journaldriver/build.rs @@ -0,0 +1,6 @@ +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..2df5e58fc8df --- /dev/null +++ b/ops/journaldriver/default.nix @@ -0,0 +1,9 @@ +{ pkgs, ... }: + +pkgs.third_party.naersk.buildPackage { + src = ./.; + + buildInputs = with pkgs.third_party; [ + pkgconfig openssl systemd.dev + ]; +} diff --git a/ops/journaldriver/src/main.rs b/ops/journaldriver/src/main.rs new file mode 100644 index 000000000000..a57bb3505ddc --- /dev/null +++ b/ops/journaldriver/src/main.rs @@ -0,0 +1,665 @@ +// 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. + +#[macro_use] extern crate failure; +#[macro_use] extern crate log; +#[macro_use] extern crate serde_derive; +#[macro_use] extern crate serde_json; +#[macro_use] extern crate lazy_static; + +extern crate chrono; +extern crate env_logger; +extern crate medallion; +extern crate serde; +extern crate systemd; +extern crate ureq; + +use chrono::offset::LocalResult; +use chrono::prelude::*; +use failure::ResultExt; +use serde_json::{from_str, Value}; +use std::env; +use std::fs::{self, File, rename}; +use std::io::{self, Read, ErrorKind, Write}; +use std::mem; +use std::path::PathBuf; +use std::process; +use std::time::{Duration, Instant}; +use systemd::journal::*; + +#[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"; + +/// Convenience type alias for results using failure's `Error` type. +type Result<T> = std::result::Result<T, failure::Error>; + +/// 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 = ureq::get(url) + .set("Metadata-Flavor", "Google") + .timeout_connect(5000) + .timeout_read(5000) + .call(); + + if response.ok() { + // Whitespace is trimmed to remove newlines from responses. + let body = response.into_string() + .context("Failed to decode metadata response")? + .trim().to_string(); + + Ok(body) + } else { + let status = response.status_line().to_string(); + let body = response.into_string() + .unwrap_or_else(|e| format!("Metadata body error: {}", e)); + bail!("Metadata failure: {} ({})", body, status) + } +} + +/// Convenience helper for determining the project ID. +fn get_project_id() -> String { + env::var("GOOGLE_CLOUD_PROJECT") + .map_err(Into::into) + .or_else(|_: failure::Error| 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 = Utc::now(); + let exp = iat.checked_add_signed(chrono::Duration::seconds(3600)) + .ok_or_else(|| format_err!("Failed to calculate token expiry"))?; + + 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.timestamp() as u64), + exp: Some(exp.timestamp() as u64), + ..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<DateTime<Utc>> { + if input.len() != 16 { + return None; + } + + let seconds: i64 = (&input[..10]).parse().ok()?; + let micros: u32 = (&input[10..]).parse().ok()?; + + match Utc.timestamp_opt(seconds, micros * 1000) { + LocalResult::Single(time) => Some(time), + _ => None, + } +} + +/// 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")] + timestamp: Option<DateTime<Utc>>, + + #[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()?; + mem::replace(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 = ureq::post(ENTRIES_WRITE_URL) + .set("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 hit an error case in case of network troubles. + // Presumably no request in a functioning environment will + // ever hit these limits. + .timeout_connect(2000) + .timeout_read(5000) + .send_json(request); + + if response.ok() { + Ok(()) + } else { + let status = response.status_line().to_string(); + let body = response.into_string() + .unwrap_or_else(|_| "no response body".into()); + bail!("Write failure: {} ({})", body, status) + } +} + +/// 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..779add7a7012 --- /dev/null +++ b/ops/journaldriver/src/tests.rs @@ -0,0 +1,95 @@ +use super::*; +use serde_json::to_string; + +#[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_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: DateTime<Utc> = "2018-06-16T18:52:29.291187Z" + .to_string().parse().unwrap(); + + assert_eq!(Some(expected), parse_microseconds(input)); +} diff --git a/ops/kms_pass.nix b/ops/kms_pass.nix new file mode 100644 index 000000000000..14989b392dd1 --- /dev/null +++ b/ops/kms_pass.nix @@ -0,0 +1,60 @@ +# This tool mimics a subset of the interface of 'pass', but uses +# Google Cloud KMS for encryption. +# +# It is intended to be compatible with how 'kontemplate' invokes +# 'pass.' +# +# Only the 'show' and 'insert' commands are supported. + +{ pkgs, kms, ... }: + +let inherit (pkgs.third_party) google-cloud-sdk tree writeShellScriptBin; +in (writeShellScriptBin "pass" '' + set -eo pipefail + + CMD="$1" + readonly SECRET=$2 + readonly SECRET_PATH="$SECRETS_DIR/$SECRET" + + function secret_check { + if [[ -z $SECRET ]]; then + echo 'Secret must be specified' + exit 1 + fi + } + + if [[ -z $CMD ]]; then + CMD="ls" + fi + + case "$CMD" in + ls) + ${tree}/bin/tree $SECRETS_DIR + ;; + show) + secret_check + ${google-cloud-sdk}/bin/gcloud kms decrypt \ + --project ${kms.project} \ + --location ${kms.region} \ + --keyring ${kms.keyring} \ + --key ${kms.key} \ + --ciphertext-file $SECRET_PATH \ + --plaintext-file - + ;; + insert) + secret_check + ${google-cloud-sdk}/bin/gcloud kms encrypt \ + --project ${kms.project} \ + --location ${kms.region} \ + --keyring ${kms.keyring} \ + --key ${kms.key} \ + --ciphertext-file $SECRET_PATH \ + --plaintext-file - + echo "Inserted secret '$SECRET'" + ;; + *) + echo "Usage: pass show/insert <secret>" + exit 1 + ;; + esac +'') // { meta.enableCI = true; } 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..e959e1b6460b --- /dev/null +++ b/ops/kontemplate/README.md @@ -0,0 +1,188 @@ +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 signed binary releases available on the +[releases page][]. Release binaries are available for Linux, OS X, FreeBSD and Windows. + +### Homebrew + +OS X users with Homebrew installed can "tap" Kontemplate like such: + +```sh +brew tap tazjin/kontemplate https://github.com/tazjin/kontemplate +brew install kontemplate +``` + +### NixOS + +Kontemplate has been included in [NixOS](https://nixos.org/) since version 17.09. + +It is available as `kontemplate` from the default Nix package set. + +### Arch Linux + +An [AUR package][] is available for Arch Linux and other `pacman`-based distributions. + +### Building from source + +Assuming you have Go configured correctly, you can simply `go get github.com/tazjin/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). + +[Kontemplate]: http://kontemplate.works +[Helm]: https://helm.sh/ +[releases page]: https://github.com/tazjin/kontemplate/releases +[AUR package]: https://aur.archlinux.org/packages/kontemplate-git/ +[Repeatr]: http://repeatr.io/ 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..7ecd9d587d24 --- /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..8a56bba7fe88 --- /dev/null +++ b/ops/kontemplate/default.nix @@ -0,0 +1,36 @@ +# 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 install Kontemplate on +# Nix-based systems. + +{ pkgs, ... }: + +with pkgs.third_party; buildGoPackage rec { + name = "kontemplate-${version}"; + version = "master"; + src = ./.; + goPackagePath = "github.com/tazjin/kontemplate"; + goDeps = ./deps.nix; + buildInputs = [ 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..4af08f50c7bb --- /dev/null +++ b/ops/kontemplate/release.nix @@ -0,0 +1,54 @@ +# 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 = "master"; + 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..c20858c203b4 --- /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/secrets/.skip-subtree b/ops/secrets/.skip-subtree new file mode 100644 index 000000000000..25dba2a344f4 --- /dev/null +++ b/ops/secrets/.skip-subtree @@ -0,0 +1 @@ +No Nix derivations under //ops/secrets diff --git a/ops/secrets/gcsr-tazjin-password b/ops/secrets/gcsr-tazjin-password new file mode 100644 index 000000000000..5893de131560 --- /dev/null +++ b/ops/secrets/gcsr-tazjin-password Binary files differdiff --git a/ops/secrets/nixery-gcs-json b/ops/secrets/nixery-gcs-json new file mode 100644 index 000000000000..b8b544511685 --- /dev/null +++ b/ops/secrets/nixery-gcs-json Binary files differdiff --git a/ops/secrets/nixery-gcs-pem b/ops/secrets/nixery-gcs-pem new file mode 100644 index 000000000000..798a1e5a66f8 --- /dev/null +++ b/ops/secrets/nixery-gcs-pem Binary files differdiff --git a/ops/secrets/nixery-ssh-private b/ops/secrets/nixery-ssh-private new file mode 100644 index 000000000000..5c4ff2023350 --- /dev/null +++ b/ops/secrets/nixery-ssh-private Binary files differdiff --git a/ops/sync-gcsr/default.nix b/ops/sync-gcsr/default.nix new file mode 100644 index 000000000000..114ff221bed1 --- /dev/null +++ b/ops/sync-gcsr/default.nix @@ -0,0 +1,10 @@ +{ pkgs, ... }: + +pkgs.buildGo.program { + name = "sync-gcsr"; + srcs = [ ./main.go ]; + + deps = with pkgs.third_party; map (p: p.gopkg) [ + gopkgs."gopkg.in".src-d.go-git + ]; +} diff --git a/ops/sync-gcsr/main.go b/ops/sync-gcsr/main.go new file mode 100644 index 000000000000..daec76b3464b --- /dev/null +++ b/ops/sync-gcsr/main.go @@ -0,0 +1,92 @@ +// Copyright 2019 Google LLC. +// SPDX-License-Identifier: Apache-2.0 +// +// sync-gcsr implements a small utility that periodically mirrors a +// remote Google Cloud Source Repository to a local file path. +package main + +import ( + "fmt" + "log" + "os" + "time" + + git "gopkg.in/src-d/go-git.v4" + "gopkg.in/src-d/go-git.v4/plumbing/transport/http" +) + +func EnvOr(key, def string) string { + v := os.Getenv(key) + if v == "" { + return def + } + + return v +} + +func updateRepo(repo *git.Repository, tree *git.Worktree, opts *git.PullOptions) error { + err := tree.Pull(opts) + if err == git.NoErrAlreadyUpToDate { + // nothing to do ... + return nil + } else if err != nil { + return err + } + + log.Println("Updated local repository mirror") + return nil +} + +func main() { + var dest = EnvOr("SYNC_DEST", "/git/depot") + var project = EnvOr("SYNC_PROJECT", "tazjins-infrastructure") + var repo = EnvOr("SYNC_REPO", "depot") + var user = os.Getenv("SYNC_USER") + var pass = os.Getenv("SYNC_PASS") + + log.Printf("Syncing repository '%s/%s' to destination '%s'", project, repo, dest) + + var cloneOpts = git.CloneOptions{ + URL: fmt.Sprintf("https://source.developers.google.com/p/%s/r/%s", project, repo), + } + + if user != "" && pass != "" { + cloneOpts.Auth = &http.BasicAuth{ + Username: user, + Password: pass, + } + log.Println("Enabling basic authentication as user", user) + } + + action := "clone" + handle, err := git.PlainClone(dest, false, &cloneOpts) + + if err == git.ErrRepositoryAlreadyExists { + log.Println("Repository has already been cloned!") + handle, err = git.PlainOpen(dest) + action = "open" + } + + if err != nil { + log.Fatalf("Failed to %s repository: %s", action, err) + } else { + log.Println("Initiating update loop") + } + + tree, err := handle.Worktree() + if err != nil { + log.Fatalln("Failed to open repository worktree:", err) + } + + pullOpts := git.PullOptions{ + Auth: cloneOpts.Auth, + Force: true, + } + + for { + if err = updateRepo(handle, tree, &pullOpts); err != nil { + log.Fatalf("Failed to pull updated repository: %s", err) + } + time.Sleep(30 * time.Second) // TODO(tazjin): Config option for pull interval? + } +} |