author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
350,429
26.04.2020 16:11:35
-32,400
3c9f79476e17f6af602421cc057a0a85c8d059b1
Fix tiny typo in error message
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/volumes.rs", "new_path": "crates/kubelet/src/volumes.rs", "diff": "@@ -126,7 +126,7 @@ async fn configure(\npopulate_from_secret(\n&s.secret_name\n.as_ref()\n- .ok_or_else(|| anyhow::anyhow!(\"no configmap name was given\"))?,\n+ .ok_or_else(|| anyhow::anyhow!(\"no secret name was given\"))?,\nnamespace,\nclient,\npath,\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix tiny typo in error message
350,405
06.05.2020 11:26:59
-43,200
b190a9a618aaa9e684dd9ae793f64f9b0f44a89c
Don't watch files under ./target in VS Code
[ { "change_type": "ADD", "old_path": null, "new_path": ".vscode/settings.json", "diff": "+{\n+ \"files.watcherExclude\": {\n+ \"**/.git/objects/**\": true,\n+ \"**/.git/subtree-cache/**\": true,\n+ \"**/node_modules/**\": true,\n+ \"**/.hg/store/**\": true,\n+ \"**/target/**\": true\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Don't watch files under ./target in VS Code
350,422
06.05.2020 13:20:20
25,200
b3045e7926b9ca83cd26f4526a183d8c227beb6a
Instructions for running krustlet with microk8s
[ { "change_type": "MODIFY", "old_path": "docs/howto/README.md", "new_path": "docs/howto/README.md", "diff": "@@ -9,6 +9,7 @@ However, these guides will help you quickly accomplish common tasks.\n- [Running Krustlet on Kubernetes-in-Docker (KinD)](krustlet-on-kind.md)\n- [Running Krustlet on Minikube](krustlet-on-minikube.md)\n- [Running Krustlet on any Kubernetes cluster with inlets](krustlet-with-inlets.md)\n+- [Running Krustlet on MicroK8s](krustlet-on-microk8s.md)\n- [Running Kubernetes on Azure Kubernetes Service (AKS)](kubernetes-on-aks.md)\n- [Running Kubernetes on Amazon Elastic Kubernetes Service (EKS)](kubernetes-on-eks.md)\n- [Running Kubernetes on Kubernetes-in-Docker (KinD)](kubernetes-on-kind.md)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/howto/krustlet-on-microk8s.md", "diff": "+# Running Krustlet on [MicroK8s](https://microk8s.io)\n+\n+These are steps for running Krustlet node(s) and [MicroK8s](https://microk8s.io) on the same machine.\n+\n+## Prerequisites\n+\n+You will require a running MicroK8s cluster for this guide. The steps below assume you will run\n+MicroK8s and the Krustlet, on a single machine. `kubectl` is required but is installed with MicroK8s\n+as `microk8s.kubectl`. The following instructions use `microk8s.kubectl` for simplicity.\n+You may use a standlone `kubectl` if you prefer.\n+\n+## Step 1: Create a service account user for the node\n+\n+We need to edit the Kubernetes configuration file (known as the kubeconfig) and create a service account\n+for Krustlet to use to register nodes and access specific secrets.\n+\n+The service account can be created by using the Kubernetes manifest in the [assets](./assets) directory:\n+\n+```shell\n+$ microk8s.kubectl apply --namespace=kube-system --filename=./docs/howto/assets/krustlet-service-account.yaml\n+```\n+\n+You can also do this by using the manifest straight from GitHub:\n+\n+```shell\n+$ microk8s.kubectl apply --namespace=kube-system --filename=https://raw.githubusercontent.com/deislabs/krustlet/master/docs/howto/assets/krustlet-service-account.yaml\n+```\n+The following commands edit Kubernetes configuration file, adding a context that will be used by Krustlet:\n+\n+```shell\n+SERVICE_ACCOUNT_NAME=\"krustlet\"\n+CONTEXT=\"krustlet\"\n+CLUSTER=\"microk8s-cluster\"\n+NAMESPACE=\"kube-system\"\n+USER=\"${CONTEXT}-token-user\"\n+\n+SECRET_NAME=$(microk8s.kubectl get serviceaccount/${SERVICE_ACCOUNT_NAME} \\\n+ --namespace=${NAMESPACE} \\\n+ --output=jsonpath='{.secrets[0].name}')\n+TOKEN_DATA=$(microk8s.kubectl get secret/${SECRET_NAME} \\\n+ --namespace=${NAMESPACE} \\\n+ --output=jsonpath='{.data.token}')\n+\n+TOKEN=$(echo ${TOKEN_DATA} | base64 -d)\n+\n+# Create user\n+microk8s.kubectl config set-credentials ${USER} \\\n+--token ${TOKEN}\n+# Create context\n+microk8s.kubectl config set-context ${CONTEXT}\n+# Set context to use cluster, namespace and user\n+microk8s.kubectl config set-context ${CONTEXT} \\\n+--cluster=${CLUSTER} \\\n+--user=${USER} \\\n+--namespace=${NAMESPACE}\n+```\n+\n+> **NOTE** We'll switch to this context when we run Krustlet; for now we'll continue using the\n+current (probably 'default') context\n+\n+## Step 2: Create Certificate\n+\n+Krustlet requires a certificate for securing communication with the Kubernetes API. Because\n+Kubernetes has its own certificates, we'll need to get a signed certificate from the Kubernetes\n+API that we can use. First things first, let's create a certificate signing request (CSR):\n+\n+```shell\n+$ openssl req -new -sha256 -newkey rsa:2048 -keyout krustlet.key -out krustlet.csr -nodes -subj \"/C=US/ST=./L=./O=./OU=./CN=krustlet\"\n+```\n+\n+This will create a CSR and a new key for the certificate, using `krustlet` as the hostname of the\n+server.\n+\n+Now that it is created, we'll need to send the request to Kubernetes:\n+\n+```shell\n+$ cat <<EOF | microk8s.kubectl apply --filename=-\n+apiVersion: certificates.k8s.io/v1beta1\n+kind: CertificateSigningRequest\n+metadata:\n+ name: krustlet\n+spec:\n+ request: $(cat krustlet.csr | base64 | tr -d '\\n')\n+ usages:\n+ - digital signature\n+ - key encipherment\n+ - server auth\n+EOF\n+certificatesigningrequest.certificates.k8s.io/krustlet created\n+```\n+\n+Once that runs, an admin (that is probably you! at least it should be if you are trying to add a\n+node to the cluster) needs to approve the request:\n+\n+```shell\n+$ microk8s.kubectl certificate approve krustlet\n+certificatesigningrequest.certificates.k8s.io/krustlet approved\n+```\n+\n+After approval, you can download the cert like so:\n+\n+```shell\n+$ microk8s.kubectl get csr krustlet --output=jsonpath='{.status.certificate}' \\\n+ | base64 --decode > krustlet.crt\n+```\n+\n+Lastly, combine the key and the cert into a PFX bundle, choosing your own password instead of\n+\"password\":\n+\n+```shell\n+$ openssl pkcs12 -export -out krustlet.pfx -inkey krustlet.key -in krustlet.crt -password \"pass:password\"\n+```\n+\n+## Step 3: Install and configure Krustlet\n+\n+Install the latest release of Krustlet following [the install guide](../intro/install.md).\n+\n+We want the Krustlet to run as the service account that we created in step #1. This is configured\n+by the context (`krustlet`) that we created in that step. Unfortunately, it's not possible to\n+reference a specific context, so we must change the context before running Krustlet:\n+\n+```shell\n+$ microk8s.kubectl use context ${CONTEXT}\n+Switched to context \"krustlet\".\n+```\n+\n+There are 2 binaries (`krustlet-wasi` and `krustlet-wascc`), let's start the first:\n+\n+```shell\n+$ KUBECONFIG=/var/snap/microk8s/current/credentials/client.config \\\n+./krustlet-wasi \\\n+--node-ip=127.0.0.1 \\\n+--node-name=krustlet \\\n+--pfx-password=\"password\" \\\n+--pfx-path=./krustlet.pfx\n+```\n+\n+In another terminal:\n+\n+We'll ensure the Kubernetes context is reverted to the default (`microk8s`) before proceeding:\n+\n+```shell\n+$ microk8s.kubectl use context microk8s\n+Switched to context \"microk8s\".\n+```\n+\n+```shell\n+$ microk8s.kubectl get nodes --output=wide\n+NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME\n+krustlet Ready agent 11s v1.17.0 127.0.0.1 <none> <unknown> <unknown> mvp\n+microk8s Ready <none> 13m v1.18.2 10.138.0.4 <none> Ubuntu 20.04 LTS 5.4.0-1009-gcp containerd://1.2.5\n+```\n+\n+## Step 4: Test that things work\n+\n+We'll ensure the Kubernetes context is reverted to the default (`microk8s`) before proceeding:\n+\n+```shell\n+$ microk8s.kubectl use context microk8s\n+Switched to context \"microk8s\".\n+```\n+\n+Now you can see things work! Feel free to give any of the demos a try like so:\n+\n+```shell\n+$ microk8s.kubectl apply --file=https://raw.githubusercontent.com/deislabs/krustlet/master/demos/wasi/hello-world-rust/k8s.yaml\n+$ microk8s.kubectl logs pod/hello-world-wasi-rust\n+hello from stdout!\n+hello from stderr!\n+CONFIG_MAP_VAL=cool stuff\n+FOO=bar\n+POD_NAME=hello-world-wasi-rust\n+Args are: []\n+```\n" }, { "change_type": "MODIFY", "old_path": "docs/intro/quickstart.md", "new_path": "docs/intro/quickstart.md", "diff": "@@ -51,6 +51,7 @@ accessible from the Kubernetes control plane.\nFor testing/development environments:\n- [Kubernetes-in-Docker (KinD)](../howto/krustlet-on-kind.md)\n+- [MicroK8s](../howto/krustlet-on-microk8s.md)\n- [Minikube](../howto/krustlet-on-minikube.md)\n- [Windows Subsystem for Linux (WSL2)](../howto/krustlet-on-wsl2.md)\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Instructions for running krustlet with microk8s (#233)
350,405
07.05.2020 10:18:49
-43,200
487148252542ef205fd21c20cc73bfe6a8f5a4f6
Refactor WASI integration test to named functions
[ { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -131,14 +131,7 @@ async fn test_wascc_provider() -> Result<(), Box<dyn std::error::Error>> {\nOk(())\n}\n-#[tokio::test]\n-async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\n- let client = kube::Client::try_default().await?;\n-\n- let nodes: Api<Node> = Api::all(client);\n-\n- let node = nodes.get(\"krustlet-wasi\").await?;\n-\n+async fn verify_wasi_node(node: Node) -> () {\nlet node_status = node.status.expect(\"node reported no status\");\nassert_eq!(\nnode_status\n@@ -179,44 +172,14 @@ async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\n..Default::default()\n}\n);\n-\n- let client: kube::Client = nodes.into();\n- let secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\n- secrets\n- .create(\n- &PostParams::default(),\n- &serde_json::from_value(json!({\n- \"apiVersion\": \"v1\",\n- \"kind\": \"Secret\",\n- \"metadata\": {\n- \"name\": \"hello-wasi-secret\"\n- },\n- \"stringData\": {\n- \"myval\": \"a cool secret\"\n}\n- }))?,\n- )\n- .await?;\n- let config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), \"default\");\n- config_maps\n- .create(\n- &PostParams::default(),\n- &serde_json::from_value(json!({\n- \"apiVersion\": \"v1\",\n- \"kind\": \"ConfigMap\",\n- \"metadata\": {\n- \"name\": \"hello-wasi-configmap\"\n- },\n- \"data\": {\n- \"myval\": \"a cool configmap\"\n- }\n- }))?,\n- )\n- .await?;\n+async fn create_wasi_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+) -> Result<(), Box<dyn std::error::Error>> {\n// Create a temp directory to use for the host path\nlet tempdir = tempfile::tempdir()?;\n- let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\nlet p = serde_json::from_value(json!({\n\"apiVersion\": \"v1\",\n\"kind\": \"Pod\",\n@@ -313,13 +276,127 @@ async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\nassert!(went_ready, \"pod never went ready\");\n- let mut logs = pods.log_stream(\"hello-wasi\", &LogParams::default()).await?;\n+ Ok(())\n+}\n+\n+async fn set_up_wasi_test_environment(\n+ client: kube::Client,\n+) -> Result<(), Box<dyn std::error::Error>> {\n+ let secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\n+ secrets\n+ .create(\n+ &PostParams::default(),\n+ &serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Secret\",\n+ \"metadata\": {\n+ \"name\": \"hello-wasi-secret\"\n+ },\n+ \"stringData\": {\n+ \"myval\": \"a cool secret\"\n+ }\n+ }))?,\n+ )\n+ .await?;\n+\n+ let config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), \"default\");\n+ config_maps\n+ .create(\n+ &PostParams::default(),\n+ &serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"ConfigMap\",\n+ \"metadata\": {\n+ \"name\": \"hello-wasi-configmap\"\n+ },\n+ \"data\": {\n+ \"myval\": \"a cool configmap\"\n+ }\n+ }))?,\n+ )\n+ .await?;\n+\n+ Ok(())\n+}\n+\n+async fn clean_up_wasi_test_resources(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+) -> Result<(), Box<dyn std::error::Error>> {\n+ pods.delete(\"hello-wasi\", &DeleteParams::default()).await?;\n+ let secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\n+ secrets\n+ .delete(\"hello-wasi-secret\", &DeleteParams::default())\n+ .await?;\n+ let config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), \"default\");\n+ config_maps\n+ .delete(\"hello-wasi-configmap\", &DeleteParams::default())\n+ .await?;\n+ Ok(())\n+}\n+\n+#[tokio::test]\n+async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\n+ let client = kube::Client::try_default().await?;\n+\n+ let nodes: Api<Node> = Api::all(client);\n+\n+ let node = nodes.get(\"krustlet-wasi\").await?;\n+\n+ verify_wasi_node(node).await;\n+\n+ let client: kube::Client = nodes.into();\n+\n+ set_up_wasi_test_environment(client.clone()).await?;\n+\n+ let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\n+\n+ create_wasi_pod(client.clone(), &pods).await?;\n+\n+ assert_pod_log_equals(&pods, \"hello-wasi\", \"Hello, world!\\n\").await?;\n+\n+ assert_pod_exited_successfully(&pods, \"hello-wasi\").await?;\n+\n+ // TODO: Create a module that actually reads from a directory and outputs to logs\n+ assert_container_file_contains(\n+ \"secret-test/myval\",\n+ \"a cool secret\",\n+ \"unable to open secret file\",\n+ )\n+ .await?;\n+ assert_container_file_contains(\n+ \"configmap-test/myval\",\n+ \"a cool configmap\",\n+ \"unable to open configmap file\",\n+ )\n+ .await?;\n+\n+ // cleanup\n+ // TODO: Find an actual way to perform cleanup automatically, even in the case of failures\n+ clean_up_wasi_test_resources(client.clone(), &pods).await?;\n+\n+ Ok(())\n+}\n+\n+async fn assert_pod_log_equals(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ expected_log: &str,\n+) -> Result<(), Box<dyn std::error::Error>> {\n+ let mut logs = pods.log_stream(pod_name, &LogParams::default()).await?;\nwhile let Some(line) = logs.try_next().await? {\n- assert_eq!(\"Hello, world!\\n\", String::from_utf8_lossy(&line));\n+ assert_eq!(expected_log, String::from_utf8_lossy(&line));\n}\n- let pod = pods.get(\"hello-wasi\").await?;\n+ Ok(())\n+}\n+\n+async fn assert_pod_exited_successfully(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+) -> Result<(), Box<dyn std::error::Error>> {\n+ let pod = pods.get(pod_name).await?;\nlet state = (|| {\npod.status?.container_statuses?[0]\n@@ -331,31 +408,23 @@ async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\n.expect(\"Could not fetch terminated states\");\nassert_eq!(state.exit_code, 0);\n- // TODO: Create a module that actually reads from a directory and outputs to logs\n+ Ok(())\n+}\n+\n+async fn assert_container_file_contains(\n+ container_file_path: &str,\n+ expected_content: &str,\n+ file_error: &str,\n+) -> Result<(), Box<dyn std::error::Error>> {\nlet file_path_base = dirs::home_dir()\n.expect(\"home dir does not exist\")\n.join(\".krustlet/volumes/hello-wasi-default\");\n- let secret_file_bytes = tokio::fs::read(file_path_base.join(\"secret-test/myval\"))\n+ let container_file_bytes = tokio::fs::read(file_path_base.join(container_file_path))\n.await\n- .expect(\"unable to open secret file\");\n- let configmap_file_bytes = tokio::fs::read(file_path_base.join(\"configmap-test/myval\"))\n- .await\n- .expect(\"unable to open configmap file\");\n- assert_eq!(\"a cool secret\".to_owned().into_bytes(), secret_file_bytes);\n+ .expect(file_error);\nassert_eq!(\n- \"a cool configmap\".to_owned().into_bytes(),\n- configmap_file_bytes\n+ expected_content.to_owned().into_bytes(),\n+ container_file_bytes\n);\n-\n- // cleanup\n- // TODO: Find an actual way to perform cleanup automatically, even in the case of failures\n- pods.delete(\"hello-wasi\", &DeleteParams::default()).await?;\n- secrets\n- .delete(\"hello-wasi-secret\", &DeleteParams::default())\n- .await?;\n- config_maps\n- .delete(\"hello-wasi-configmap\", &DeleteParams::default())\n- .await?;\n-\nOk(())\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Refactor WASI integration test to named functions
350,426
09.05.2020 00:40:56
0
bdff4bdbaafbb70d09d45019999b52eca85df899
Make stream_logs available to providers.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/lib.rs", "new_path": "crates/kubelet/src/lib.rs", "diff": "@@ -62,7 +62,7 @@ pub mod volumes;\npub use self::kubelet::Kubelet;\npub use handle::{LogHandleFactory, PodHandle, RuntimeHandle};\n-pub use logs::{LogSendError, LogSender};\n+pub use logs::{LogSendError, LogSender, stream_logs};\npub use pod::Pod;\n#[doc(inline)]\npub use provider::Provider;\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Make stream_logs available to providers.
350,422
11.05.2020 14:08:08
25,200
75de071f516cd263438453efb8497286cf236220
Krustlet on Google Kubernetes Engine Implements
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/howto/krustlet-on-gke.md", "diff": "+# Running Krustlet on Google Kubernetes Engine (GKE)\n+\n+These steps are for running a Krustlet node in a GKE cluster.\n+\n+## Prerequisites\n+\n+You will require a GKE cluster. See the [how-to guide for running Kubernetes on GKE](kubernetes-on-gke.md)\n+for more information.\n+\n+This specific tutorial will be running Krustlet on a Compute Engine VM; however you may follow\n+these steps from any device that can start a web server on an IP accessible from the Kubernetes\n+control plane.\n+\n+In the [how-to guide for running Kubernetes on GKE](kubernetes-on-gke.md), several environment\n+variables were used to define a Google Cloud Platform project, region and Kubernetes Engine\n+cluster. Let's reuse those values:\n+\n+```shell\n+$ PROJECT=[YOUR-PROJECT] # Perhaps $(whoami)-$(date +%y%m%d)-krustlet\n+$ REGION=\"us-west1\" # Use a region close to you `gcloud compute regions list --project=${PROJECT}`\n+$ CLUSTER=\"cluster\"\n+```\n+\n+Let's confirm that the cluster exists. We can do this using either `gcloud` or `kubectl`:\n+\n+```shell\n+$ gcloud container clusters describe ${CLUSTER} --project=${PROJECT} --region=${REGION}\n+$ gcloud container clusters describe ${CLUSTER} --project=${PROJECT} --region=${REGION} --format=\"value(status)\"\n+RUNNING\n+```\n+\n+Or:\n+\n+```shell\n+$ kubectl get nodes\n+NAME STATUS ROLES AGE VERSION\n+gke-cluster-default-pool-1a3a5b85-scds Ready <none> 1m v1.17.4-gke.10\n+gke-cluster-default-pool-3885c0e3-6zw2 Ready <none> 1m v1.17.4-gke.10\n+gke-cluster-default-pool-6d70a85d-19r8 Ready <none> 1m v1.17.4-gke.10\n+```\n+\n+> **NOTE** If you chose to create a single-zone cluster, replace `--region=${REGION}` with\n+`--zone=${ZONE}` in the above `gcloud` commands.\n+\n+## Step 1: Create a service account user for the node\n+\n+We will create a service account for Krustlet to use to register nodes and access specific secrets.\n+\n+This can be done by using the Kubernetes manifest in the [assets](./assets) directory:\n+\n+```shell\n+$ kubectl apply --namespace=kube-system --filename=./docs/howto/assets/krustlet-service-account.yaml\n+```\n+\n+Or by using the manifest directly from GitHub:\n+\n+```shell\n+$ kubectl apply \\\n+--namespace=kube-system \\\n+--filename=https://raw.githubusercontent.com/deislabs/krustlet/master/docs/howto/assets/krustlet-service-account.yaml\n+```\n+\n+Now that things are all set up, we need to generate the kubeconfig. You can do this by running\n+(assuming you are in the root of the krustlet repo):\n+\n+```shell\n+$ ./docs/howto/assets/generate-kubeconfig.sh\n+```\n+\n+Or if you are feeling more trusting, you can run it straight from the repo:\n+\n+```shell\n+bash <(curl https://raw.githubusercontent.com/deislabs/krustlet/master/docs/howto/assets/generate-kubeconfig.sh)\n+```\n+\n+Either way, it will output a file called `kubeconfig-sa` in your current directory. Save this for\n+later.\n+\n+## Step 1: Create Compute Engine VM\n+\n+We can create a new VM with the following command:\n+\n+```shell\n+$ INSTANCE=\"krustlet\" # Name of this VM must matches the certificate's CN\n+$ # The cluster is distributed across the zones in the region\n+$ # For the VM, we'll pick one of the zones\n+$ ZONE=\"${REGION}-a\" # Pick one of the zones in this region\n+$ gcloud beta compute instances create ${INSTANCE} \\\n+--project=${PROJECT} \\\n+--zone=${ZONE} \\\n+--machine-type \"n1-standard-1\" \\\n+--image-family=\"debian-10\" \\\n+--image-project=\"debian-cloud\"\n+NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS\n+krustlet us-west1-a n1-standard-1 xx.xx.xx.xx yy.yy.yy.yy RUNNING\n+```\n+\n+It should take less than 30-seconds to provision the VM.\n+\n+Let's determine the instance's internal (!) IP to use when creating the Kubernete certificate and\n+subsequently running Krustlet. In step #4, you'll need to copy this value into the command that is\n+used to run Krustlet on the VM:\n+\n+```shell\n+$ IP=$(gcloud compute instances describe ${INSTANCE} \\\n+--project=${PROJECT} \\\n+--zone=${ZONE} \\\n+--format=\"value(networkInterfaces[0].networkIP)\") && echo ${IP}\n+```\n+\n+## Step 2: Create Certificate\n+\n+Krustlet requires a certificate for securing communication with the Kubernetes API. Because\n+Kubernetes has its own certificates, we'll need to get a signed certificate from the Kubernetes\n+API that we can use.\n+\n+In order for the Kubernetes cluster to resolve the name of the VM running the Krustlet, we'll\n+include aliases for the VM's name in the certificate.\n+\n+First things first, let's create a certificate signing request (CSR):\n+\n+```shell\n+$ ALIASES=\"DNS:${INSTANCE},DNS:${INSTANCE}.${ZONE},IP:${IP}\" && echo ${ALIASES}\n+$ openssl req -new -sha256 -newkey rsa:2048 -keyout ./krustlet.key -out ./krustlet.csr -nodes -config <(\n+cat <<-EOF\n+[req]\n+default_bits = 2048\n+prompt = no\n+default_md = sha256\n+req_extensions = req_ext\n+distinguished_name = dn\n+[dn]\n+O=.\n+CN=${INSTANCE}\n+[req_ext]\n+subjectAltName = ${ALIASES}\n+EOF\n+)\n+Generating a RSA private key\n+....................+++++\n+............................................+++++\n+writing new private key to './krustlet.key'\n+```\n+\n+This will create a CSR and a new key for the certificate. Now that it is created, we'll need to\n+send the request to Kubernetes:\n+\n+```shell\n+$ cat <<EOF | kubectl apply --filename=-\n+apiVersion: certificates.k8s.io/v1beta1\n+kind: CertificateSigningRequest\n+metadata:\n+ name: krustlet\n+spec:\n+ request: $(cat krustlet.csr | base64 | tr -d '\\n')\n+ usages:\n+ - digital signature\n+ - key encipherment\n+ - server auth\n+EOF\n+certificatesigningrequest.certificates.k8s.io/krustlet created\n+```\n+\n+You should then approve the request:\n+\n+```shell\n+$ kubectl certificate approve krustlet\n+certificatesigningrequest.certificates.k8s.io/krustlet approved\n+```\n+\n+After approval, you can download the cert like so:\n+\n+```shell\n+$ kubectl get csr krustlet --output=jsonpath='{.status.certificate}' \\\n+ | base64 --decode > krustlet.crt\n+```\n+\n+Lastly, combine the key and the cert into a PFX bundle, choosing your own password instead of\n+\"password\":\n+\n+```shell\n+$ openssl pkcs12 -export -out krustlet.pfx -inkey krustlet.key -in krustlet.crt -password \"pass:password\"\n+```\n+\n+## Step 3: Copy assets to VM\n+\n+The first thing we'll need to do is copy up the assets we generated in steps 1 and 2. Copy them to\n+the VM by typing:\n+\n+```shell\n+$ gcloud compute scp krustlet.pfx ${INSTANCE}: --project=${PROJECT} --zone=${ZONE}\n+$ gcloud compute scp kubeconfig-sa ${INSTANCE}: --project=${PROJECT} --zone=${ZONE}\n+```\n+\n+We can then SSH into the instance by typing:\n+\n+```shell\n+$ gcloud compute ssh ${INSTANCE} --project=${PROJECT} --zone=${ZONE}\n+```\n+\n+## Step 4: Install and configure Krustlet\n+\n+Install the latest release of krustlet following [the install guide](../intro/install.md).\n+\n+There are two flavors of Krustlet (`krustlet-wasi` and `krustlet-wascc`), let's use the first:\n+\n+```shell\n+$ KUBECONFIG=${PWD}/kubeconfig-sa krustlet-wasi \\\n+--hostname=\"krustlet\" \\\n+--node-ip=${IP} \\\n+--node-name=\"krustlet\" \\\n+--pfx-password=\"password\" \\\n+--pfx-path=./krustlet.pfx\n+```\n+\n+> **NOTE** To increase the level of debugging, you may prefix the command with `RUST_LOG=info` or\n+`RUST_LOG=debug`.\n+\n+> **NOTE** The value of `${IP}` was determined in step #1.\n+\n+\n+\n+From another terminal that's configured to access the cluster, you should be able to enumerate the\n+cluster's nodes including the Krustlet by typing:\n+\n+```shell\n+$ kubectl get nodes\n+NAME STATUS ROLES AGE VERSION\n+gke-cluster-default-pool-1a3a5b85-scds Ready <none> 59m v1.17.4-gke.10\n+gke-cluster-default-pool-3885c0e3-6zw2 Ready <none> 36m v1.17.4-gke.10\n+gke-cluster-default-pool-6d70a85d-19r8 Ready <none> 59m v1.17.4-gke.10\n+krustlet Ready agent 8s v1.17.0\n+```\n+\n+## Step 5: Test that things work\n+\n+We may test that the Krustlet is working by running one of the demos:\n+\n+```shell\n+$ kubectl apply --filename=https://raw.githubusercontent.com/deislabs/krustlet/master/demos/wasi/hello-world-rust/k8s.yaml\n+$ # wait a few seconds for the pod to run\n+$ kubectl logs pods/hello-world-wasi-rust\n+hello from stdout!\n+hello from stderr!\n+CONFIG_MAP_VAL=cool stuff\n+FOO=bar\n+POD_NAME=hello-world-wasi-rust\n+Args are: []\n+```\n+\n+> **NOTE** you may receive an `ErrImagePull` and `Failed to pull image` and\n+`failed to generate container`. This results if the taints do not apply correctly. You should be\n+able to resolve this issue, using the following YAML.\n+\n+```YAML\n+apiVersion: v1\n+kind: ConfigMap\n+metadata:\n+ name: hello-world-wasi-rust\n+data:\n+ myval: \"cool stuff\"\n+---\n+apiVersion: v1\n+kind: Pod\n+metadata:\n+ name: hello-world-wasi-rust\n+spec:\n+ containers:\n+ - name: hello-world-wasi-rust\n+ image: webassembly.azurecr.io/hello-world-wasi-rust:v0.1.0\n+ env:\n+ - name: FOO\n+ value: bar\n+ - name: POD_NAME\n+ valueFrom:\n+ fieldRef:\n+ fieldPath: metadata.name\n+ - name: CONFIG_MAP_VAL\n+ valueFrom:\n+ configMapKeyRef:\n+ key: myval\n+ name: hello-world-wasi-rust\n+ nodeSelector:\n+ kubernetes.io/arch: \"wasm32-wasi\"\n+ tolerations:\n+ - key: \"krustlet/arch\"\n+ operator: \"Equal\"\n+ value: \"wasm32-wasi\"\n+ effect: \"NoExecute\"\n+ - key: \"node.kubernetes.io/network-unavailable\"\n+ operator: \"Exists\"\n+ effect: \"NoSchedule\"\n+```\n+\n+## Step 6: Run Krustlet as a service\n+\n+Create `krustlet.service` in `/etc/systemd/system/krustlet.service` on the VM. Make\n+sure to change the value of `PFX_PASSWORD` to the password you set for your certificate.\n+\n+```\n+[Unit]\n+Description=Krustlet, a kubelet implementation for running WASM\n+\n+[Service]\n+Restart=on-failure\n+RestartSec=5s\n+Environment=KUBECONFIG=/etc/krustlet/kubeconfig-sa\n+Environment=NODE_NAME=krustlet\n+Environment=PFX_PATH=/etc/krustlet/krustlet.pfx\n+Environment=PFX_PASSWORD=password\n+Environment=KRUSTLET_DATA_DIR=/etc/krustlet\n+Environment=RUST_LOG=wascc_provider=info,wasi_provider=info,main=info\n+ExecStart=/usr/local/bin/krustlet-wasi\n+User=root\n+Group=root\n+\n+[Install]\n+WantedBy=multi-user.target\n+```\n+\n+Ensure that the `krustlet.service` has the correct ownership and permissions with:\n+\n+```shell\n+$ sudo chown root:root /etc/systemd/system/krustlet.service\n+$ sudo chmod 644 /etc/systemd/system/krustlet.service\n+```\n+\n+Then:\n+\n+```shell\n+$ sudo mkdir -p /etc/krustlet && sudo chown root:root /etc/krustlet\n+$ sudo mv {krustlet.pfx,kubeconfig-sa} /etc/krustlet && chmod 600 /etc/krustlet/*\n+```\n+\n+Once you have done that, run the following commands to make sure the unit is configured to start on\n+boot:\n+\n+```shell\n+$ sudo systemctl enable krustlet && sudo systemctl start krustlet\n+```\n+\n+## Delete the VM\n+\n+When you are finished with the VM, you can delete it by typing:\n+\n+```shell\n+$ gcloud compute instances delete ${INSTANCE} --project=${PROJECT} --zone=${ZONE} --quiet\n+```\n+\n+When you are finished with the cluster, you can delete it by typing:\n+\n+```shell\n+$ # If you created a regional cluster\n+$ gcoud container clusters delete ${CLUSTER} --project=${PROJECT} --region=${REGION}\n+$ # If you created a zonal cluster\n+$ gcoud container clusters delete ${CLUSTER} --project=${PROJECT} --zone=${ZONE}\n+```\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/howto/kubernetes-on-gke.md", "diff": "+# Running Kubernetes on Google Kubernetes Engine (GKE)\n+\n+[Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine) is a secured and managed Kubernetes service.\n+\n+If you haven't used Google Cloud Platform, you'll need a Google (e.g. Gmail) account. As a new customer, you may benefit from $300 free credit. Google Cloud Platform includes always free products. See [Google Cloud Platform Free Tier](https://cloud.google.com/free)\n+\n+\n+## Prerequisites\n+\n+You should be able to run [Google Cloud SDK ](https://cloud.google.com/sdk) command-line tool `gcloud`. This is used to provision resources in Google Cloud Platform including Kubernetes clusters.\n+\n+Either install [Google Cloud SDK](https://cloud.google.com/sdk/install) or open a [Cloud Shell](https://console.cloud.google.com/home/dashboard?cloudshell=true).\n+\n+Google Cloud SDK is available for Linux, Windows and Mac OS. The instructions that follow document using the command-line on Linux. There may be subtle changes for Windows and Mac OS.\n+\n+Google Cloud Platform provides a browser-based [Console](https://console.cloud.google.com). This is generally functionally equivalent to the command-line tool. The instructions that follow document using the command-line tool but you may perform these steps using the Console too.\n+\n+You will also need Kubernetes command-line tool `kubectl`. `kubectl` is used by all Kubernetes distributions. So, if you've created Kubernetes clusters locally or on other cloud platforms, you may already have this tool installed. See [Install and Set Up kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) for instructions.\n+\n+## Configure Google Cloud CLI\n+\n+After installing Google Cloud SDK, you will need to initialize the tool. This also authenticates your account using a Google identity (e.g. Gmail). Do this by typing `gcloud init`. If for any reason, you have already run `gcloud init`, you may reauthenticate using `gcloud auth login` or check authentication with `gcloud auth list`.\n+\n+## Create GKE cluster\n+\n+Google Cloud Platform resources are aggregated by projects. Projects are assigned to Billing Accounts. GKE uses Compute Engine VMs as nodes and Compute Engine VMs require that assign a Billing Account to our project so that we may pay for the VMs.\n+\n+```shell\n+$ PROJECT=[YOUR-PROJECT] # Perhaps $(whoami)-$(date +%y%m%d)-krustlet\n+$ BILLING=[YOUR-BILLING] # You may list these using `gcloud beta billing accounts list`\n+$ # Create Project and assing Billing Account\n+$ gcloud projects create ${PROJECT}\n+$ gcloud alpha billing projects link ${PROJECT} --billing-account=${BILLING}\n+$ # Enable Kubernetes Engine & Compute Engine\n+$ gcloud services enable container.googleapis.com --project=${PROJECT}\n+$ gcloud services enable compute.googleapis.com --project=${PROJECT}\n+$ REGION=\"us-west1\" # Use a region close to you `gcloud compute regions list --project=${PROJECT}`\n+$ CLUSTER=\"cluster\"\n+$ # Create GKE cluster with 3 nodes (one per zone in the region)\n+$ gcloud beta container clusters create ${CLUSTER} \\\n+--project=${PROJECT} \\\n+--region=${REGION} \\\n+--no-enable-basic-auth \\\n+--release-channel \"rapid\" \\\n+--machine-type \"n1-standard-1\" \\\n+--image-type \"COS_CONTAINERD\" \\\n+--preemptible \\\n+--num-nodes=\"1\"\n+```\n+\n+> **NOTE** This creates a cluster with nodes distributed across multiple zones in a region. This\n+increases the cluster's availability. If you'd prefer a less available (and cheaper) single zone\n+cluster, you may use the following commands instead:\n+\n+```shell\n+$ ZONE=\"${REGION}-a\" # Or \"-b\" or \"-c\"\n+$ gcloud beta container clusters create ${CLUSTER} \\\n+--project=${PROJECT} \\\n+--zone=${ZONE} \\\n+--no-enable-basic-auth \\\n+--release-channel \"rapid\" \\\n+--machine-type \"n1-standard-1\" \\\n+--image-type \"COS_CONTAINERD\" \\\n+--preemptible \\\n+--num-nodes=\"1\"\n+```\n+\n+After a minute, you should see the cluster created:\n+\n+```shell\n+NAME LOCATION MASTER_VERSION MASTER_IP MACHINE_TYPE NODE_VERSION NUM_NODES STATUS\n+cluster us-west1 1.17.4-gke.10 xx.xx.xx.xx n1-standard-1 1.17.4-gke.10 3 RUNNING\n+```\n+\n+> **NOTE** You may also use Cloud Console to interact with the cluster:\n+https://console.cloud.google.com/kubernetes/list?project=${PROJECT}\n+\n+> **NOTE** `gcloud clusters create` also configures `kubectl` to be able to access the cluster.\n+\n+You may confirm access to the cluster by typing:\n+\n+```shell\n+$ kubectl get nodes\n+NAME STATUS ROLES AGE VERSION\n+gke-cluster-default-pool-1a3a5b85-scds Ready <none> 10m v1.17.4-gke.10\n+gke-cluster-default-pool-3885c0e3-6zw2 Ready <none> 10m v1.17.4-gke.10\n+gke-cluster-default-pool-6d70a85d-19r8 Ready <none> 10m v1.17.4-gke.10\n+```\n+\n+You may confirm the Kubernetes configuration either by:\n+\n+```shell\n+$ more ${HOME}/.kube/config\n+apiVersion: v1\n+clusters:\n+- cluster:\n+ certificate-authority-data: LS0tLS1C...\n+ server: https://xx.xx.xx.xx\n+ name: gke_${PROJECT}_${REGION}_${CLUSTER}\n+contexts:\n+- context:\n+ cluster: gke_${PROJECT}_${REGION}_${CLUSTER}\n+ user: gke_${PROJECT}_${REGION}_${CLUSTER}\n+ name: gke_${PROJECT}_${REGION}_${CLUSTER}\n+current-context: gke_${PROJECT}_${REGION}_${CLUSTER}\n+kind: Config\n+preferences: {}\n+users:\n+- name: gke_${PROJECT}_${REGION}_${CLUSTER}\n+ user:\n+ auth-provider:\n+ config:\n+ cmd-args: config config-helper --format=json\n+ cmd-path: /snap/google-cloud-sdk/130/bin/gcloud\n+ expiry-key: '{.credential.token_expiry}'\n+ token-key: '{.credential.access_token}'\n+ name: gcp\n+```\n+\n+Or:\n+\n+```shell\n+$ kubectl config current-context\n+gke_${PROJECT}_${REGION}_${CLUSTER}\n+$ kubectl config get-contexts\n+CURRENT NAME CLUSTER AUTHINFO\n+* gke_${PROJECT}_${REGION}_${CLUSTER} gke_${PROJECT}_${REGION}_${CLUSTER} gke_${PROJECT}_${REGION}_${CLUSTER}\n+```\n+\n+## Delete the Cluster\n+\n+When you are finished with the cluster, you may delete it with:\n+\n+```shell\n+$ gcloud beta container clusters delete ${CLUSTER} --project=${PROJECT} --region=${REGION} --quiet\n+```\n+\n+If you wish to delete everything in the project, you may delete hte project (including all its\n+resources) with:\n+\n+```shell\n+$ gcloud projects delete ${PROJECT} --quiet\n+```\n+\n+> **NOTE** Both commands are irrevocable.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Krustlet on Google Kubernetes Engine (#242) Implements #236
350,426
12.05.2020 08:21:44
18,000
2beeba03302bd65717cacb6def82f2164683b02b
Make provider hook async.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node.rs", "new_path": "crates/kubelet/src/node.rs", "diff": "@@ -111,7 +111,7 @@ pub async fn create_node<P: 'static + Provider + Sync + Send>(\nbuilder.set_port(config.server_config.port as i32);\n- provider.node(&mut builder);\n+ provider.node(&mut builder).await;\nlet node = builder.build().into_inner();\nmatch retry!(node_client.create(&PostParams::default(), &node).await, times: 4, break_on: &Error::Api(ErrorResponse { code: 409, .. }))\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider.rs", "new_path": "crates/kubelet/src/provider.rs", "diff": "@@ -50,7 +50,7 @@ pub trait Provider {\nconst ARCH: &'static str;\n/// Allows provider to populate node information.\n- fn node(&self, _builder: &mut NodeBuilder) {}\n+ async fn node(&self, _builder: &mut NodeBuilder) {}\n/// Given a Pod definition, execute the workload.\nasync fn add(&self, pod: Pod) -> anyhow::Result<()>;\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -186,7 +186,7 @@ impl<S: ModuleStore + Send + Sync> WasccProvider<S> {\nimpl<S: ModuleStore + Send + Sync> Provider for WasccProvider<S> {\nconst ARCH: &'static str = TARGET_WASM32_WASCC;\n- fn node(&self, builder: &mut NodeBuilder) {\n+ async fn node(&self, builder: &mut NodeBuilder) {\nbuilder.set_architecture(\"wasm-wasi\");\nbuilder.add_taint(\"NoExecute\", \"krustlet/arch\", Self::ARCH);\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/lib.rs", "new_path": "crates/wasi-provider/src/lib.rs", "diff": "@@ -89,7 +89,7 @@ impl<S: ModuleStore + Send + Sync> WasiProvider<S> {\nimpl<S: ModuleStore + Send + Sync> Provider for WasiProvider<S> {\nconst ARCH: &'static str = TARGET_WASM32_WASI;\n- fn node(&self, builder: &mut NodeBuilder) {\n+ async fn node(&self, builder: &mut NodeBuilder) {\nbuilder.set_architecture(\"wasm-wasi\");\nbuilder.add_taint(\"NoExecute\", \"krustlet/arch\", Self::ARCH);\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Make provider hook async.
350,426
12.05.2020 09:18:28
18,000
107ffe6bcfd34cc20f52ac2f3754dd39bba073a4
Make node hook failable.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node.rs", "new_path": "crates/kubelet/src/node.rs", "diff": "@@ -111,7 +111,11 @@ pub async fn create_node<P: 'static + Provider + Sync + Send>(\nbuilder.set_port(config.server_config.port as i32);\n- provider.node(&mut builder).await;\n+ match provider.node(&mut builder).await {\n+ Ok(()) => (),\n+ Err(e) => warn!(\"Provider node annotation error: {:?}\", e),\n+ }\n+\nlet node = builder.build().into_inner();\nmatch retry!(node_client.create(&PostParams::default(), &node).await, times: 4, break_on: &Error::Api(ErrorResponse { code: 409, .. }))\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider.rs", "new_path": "crates/kubelet/src/provider.rs", "diff": "@@ -50,7 +50,9 @@ pub trait Provider {\nconst ARCH: &'static str;\n/// Allows provider to populate node information.\n- async fn node(&self, _builder: &mut NodeBuilder) {}\n+ async fn node(&self, _builder: &mut NodeBuilder) -> anyhow::Result<()> {\n+ Ok(())\n+ }\n/// Given a Pod definition, execute the workload.\nasync fn add(&self, pod: Pod) -> anyhow::Result<()>;\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -186,9 +186,10 @@ impl<S: ModuleStore + Send + Sync> WasccProvider<S> {\nimpl<S: ModuleStore + Send + Sync> Provider for WasccProvider<S> {\nconst ARCH: &'static str = TARGET_WASM32_WASCC;\n- async fn node(&self, builder: &mut NodeBuilder) {\n+ async fn node(&self, builder: &mut NodeBuilder) -> anyhow::Result<()> {\nbuilder.set_architecture(\"wasm-wasi\");\nbuilder.add_taint(\"NoExecute\", \"krustlet/arch\", Self::ARCH);\n+ Ok(())\n}\nasync fn add(&self, pod: Pod) -> anyhow::Result<()> {\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/lib.rs", "new_path": "crates/wasi-provider/src/lib.rs", "diff": "@@ -89,9 +89,10 @@ impl<S: ModuleStore + Send + Sync> WasiProvider<S> {\nimpl<S: ModuleStore + Send + Sync> Provider for WasiProvider<S> {\nconst ARCH: &'static str = TARGET_WASM32_WASI;\n- async fn node(&self, builder: &mut NodeBuilder) {\n+ async fn node(&self, builder: &mut NodeBuilder) -> anyhow::Result<()> {\nbuilder.set_architecture(\"wasm-wasi\");\nbuilder.add_taint(\"NoExecute\", \"krustlet/arch\", Self::ARCH);\n+ Ok(())\n}\nasync fn add(&self, pod: Pod) -> anyhow::Result<()> {\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Make node hook failable.
350,422
12.05.2020 09:22:42
25,200
1a028b0e02ddb1f907941409239079921f3b1379
Corrected `kubectl` command
[ { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-microk8s.md", "new_path": "docs/howto/krustlet-on-microk8s.md", "diff": "@@ -120,7 +120,7 @@ by the context (`krustlet`) that we created in that step. Unfortunately, it's no\nreference a specific context, so we must change the context before running Krustlet:\n```shell\n-$ microk8s.kubectl use context ${CONTEXT}\n+$ microk8s.kubectl config use-context ${CONTEXT}\nSwitched to context \"krustlet\".\n```\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Corrected `kubectl` command
350,426
12.05.2020 11:42:58
18,000
b8c8f9bf4b99f01b381aa8c44e4a56e62fb9be85
Introduce signal handler.
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -1748,6 +1748,7 @@ dependencies = [\n\"rpassword\",\n\"serde\",\n\"serde_json\",\n+ \"signal-hook\",\n\"structopt\",\n\"thiserror\",\n\"tokio\",\n@@ -2874,6 +2875,16 @@ dependencies = [\n\"opaque-debug\",\n]\n+[[package]]\n+name = \"signal-hook\"\n+version = \"0.1.15\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"8ff2db2112d6c761e12522c65f7768548bd6e8cd23d2a9dae162520626629bd6\"\n+dependencies = [\n+ \"libc\",\n+ \"signal-hook-registry\",\n+]\n+\n[[package]]\nname = \"signal-hook-registry\"\nversion = \"1.2.0\"\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/Cargo.toml", "new_path": "crates/kubelet/Cargo.toml", "diff": "@@ -35,6 +35,7 @@ lazy_static = \"1.4\"\noci-distribution = { path = \"../oci-distribution\", version = \"0.1.0\" }\nrpassword = \"4.0\"\nurl = \"2.1\"\n+signal-hook = \"0.1\"\n[features]\ncli = [\"structopt\"]\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "///! This library contains code for running a kubelet. Use this to create a new\n///! Kubelet with a specific handler (called a `Provider`)\nuse crate::config::Config;\n-use crate::node::{create_node, update_node};\n+use crate::node::{cordon_node, create_node, update_node};\nuse crate::queue::PodQueue;\nuse crate::server::start_webserver;\nuse crate::status::{update_pod_status, Phase};\nuse crate::Provider;\n-\nuse futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::{\n@@ -15,9 +14,9 @@ use kube::{\nApi,\n};\nuse log::{debug, error, warn};\n-use tokio::sync::mpsc;\n-\n+use std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\n+use tokio::sync::mpsc;\n/// A Kubelet server backed by a given `Provider`.\n///\n@@ -54,6 +53,7 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n/// events, which it will handle.\npub async fn start(&self) -> anyhow::Result<()> {\nlet client = kube::Client::new(self.kube_config.clone());\n+ let handler_client = client.clone();\n// Create the node. If it already exists, \"adopt\" the node definition\ncreate_node(&client, &self.config, self.provider.clone()).await;\n@@ -138,8 +138,25 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n// Start the webserver\nlet webserver = start_webserver(self.provider.clone(), &self.config.server_config);\n+ let term = Arc::new(AtomicBool::new(false));\n+ signal_hook::flag::register(signal_hook::SIGTERM, Arc::clone(&term))?;\n+ let node_name = self.config.node_name.clone();\n+ let signal_handler = tokio::task::spawn(async move {\n+ let duration = std::time::Duration::from_millis(100);\n+ loop {\n+ if term.load(Ordering::Relaxed) {\n+ warn!(\"Signal caught.\");\n+ cordon_node(&handler_client, &node_name).await;\n+ // TODO: Evict Pods\n+ // TODO: Delete node\n+ break;\n+ }\n+ tokio::time::delay_for(duration).await;\n+ }\n+ });\n+\nlet threads = async {\n- futures::try_join!(node_updater, pod_informer, error_handler)?;\n+ futures::try_join!(node_updater, pod_informer, error_handler, signal_handler)?;\nOk(())\n};\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node.rs", "new_path": "crates/kubelet/src/node.rs", "diff": "@@ -166,6 +166,54 @@ pub async fn create_node<P: 'static + Provider + Sync + Send>(\ninfo!(\"Successfully created node '{}'\", &config.node_name);\n}\n+pub async fn node_uid(client: &kube::Client, node_name: &str) -> anyhow::Result<String> {\n+ let node_client: Api<KubeNode> = Api::all(client.clone());\n+ match retry!(node_client.get(node_name).await, times: 4, log_error: |e| error!(\"Failed to get node to cordon: {:?}\", e))\n+ {\n+ Ok(node) => match node.metadata.and_then(|meta| meta.uid) {\n+ Some(uid) => Ok(uid),\n+ None => {\n+ let err = format!(\"Node missing metadata or uid {}.\", node_name);\n+ error!(\"{}\", &err);\n+ anyhow::bail!(err);\n+ }\n+ },\n+ Err(e) => {\n+ error!(\"Error fetching node {} id: {:?}.\", node_name, e);\n+ anyhow::bail!(e);\n+ }\n+ }\n+}\n+\n+pub async fn cordon_node(client: &kube::Client, node_name: &str) {\n+ debug!(\"Cordining node.\");\n+ let node_client: Api<KubeNode> = Api::all(client.clone());\n+ let patch = serde_json::to_vec(&cordon_patch()).unwrap();\n+ let mut params = PatchParams::default();\n+ params.patch_strategy = kube::api::PatchStrategy::Merge;\n+ let resp = node_client.patch(node_name, &params, patch).await;\n+ match &resp {\n+ Ok(_) => debug!(\"Node cordoned '{}'\", node_name),\n+ Err(e) => error!(\"Failed to cordon node '{}': {}\", node_name, e),\n+ }\n+}\n+\n+fn cordon_patch() -> serde_json::Value {\n+ serde_json::json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Node\",\n+ \"spec\": {\n+ \"taints\": [\n+ {\n+ \"effect\": \"NoSchedule\",\n+ \"key\": \"node.kubernetes.io/unschedulable\",\n+ \"operator\": \"Exists\"\n+ }\n+ ]\n+ },\n+ })\n+}\n+\n/// Update the timestamps on the Node object.\n///\n/// This is how we report liveness to the upstream.\n@@ -175,11 +223,8 @@ pub async fn create_node<P: 'static + Provider + Sync + Send>(\n/// doing our processing of the pod queue.\npub async fn update_node(client: &kube::Client, node_name: &str) {\ndebug!(\"Updating node '{}'\", node_name);\n- let node_client: Api<KubeNode> = Api::all(client.clone());\n- if let Ok(node) = retry!(node_client.get(node_name).await, times: 4, log_error: |e| error!(\"Failed to get node to update: {:?}\", e))\n- {\n+ if let Ok(uid) = node_uid(client, node_name).await {\ndebug!(\"Node to update '{}' fetched.\", node_name);\n- let uid = node.metadata.and_then(|m| m.uid).unwrap();\nretry!(update_lease(&uid, node_name, client).await, times: 4)\n.expect(\"Could not update lease\");\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Introduce signal handler.
350,405
13.05.2020 10:09:27
-43,200
8cb802f1dc25692cc264d6c0f84b6934eacec7db
Ensure WASI cleanup runs even if tests fail
[ { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -319,20 +319,39 @@ async fn set_up_wasi_test_environment(\nOk(())\n}\n-async fn clean_up_wasi_test_resources(\n- client: kube::Client,\n- pods: &Api<Pod>,\n-) -> Result<(), Box<dyn std::error::Error>> {\n- pods.delete(\"hello-wasi\", &DeleteParams::default()).await?;\n+async fn clean_up_wasi_test_resources() -> () {\n+ let client = kube::Client::try_default()\n+ .await\n+ .expect(\"Failed to create client\");\n+ println!(\"did first await\");\n+ let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\n+ pods.delete(\"hello-wasi\", &DeleteParams::default())\n+ .await\n+ .expect(\"Failed to delete pod\");\nlet secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\nsecrets\n.delete(\"hello-wasi-secret\", &DeleteParams::default())\n- .await?;\n+ .await\n+ .expect(\"Failed to delete secret\");\nlet config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), \"default\");\nconfig_maps\n.delete(\"hello-wasi-configmap\", &DeleteParams::default())\n- .await?;\n- Ok(())\n+ .await\n+ .expect(\"Failed to delete configmap\");\n+}\n+\n+struct WasiTestResourceCleaner {}\n+\n+impl Drop for WasiTestResourceCleaner {\n+ fn drop(&mut self) {\n+ let t = std::thread::spawn(move || {\n+ let mut rt =\n+ tokio::runtime::Runtime::new().expect(\"Failed to reate Tokio runtime for cleanup\");\n+ rt.block_on(clean_up_wasi_test_resources());\n+ });\n+\n+ t.join().expect(\"Failed to clean up WASI test resources\");\n+ }\n}\n#[tokio::test]\n@@ -349,6 +368,8 @@ async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\nset_up_wasi_test_environment(client.clone()).await?;\n+ let _cleaner = WasiTestResourceCleaner {};\n+\nlet pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\ncreate_wasi_pod(client.clone(), &pods).await?;\n@@ -371,10 +392,6 @@ async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\n)\n.await?;\n- // cleanup\n- // TODO: Find an actual way to perform cleanup automatically, even in the case of failures\n- clean_up_wasi_test_resources(client.clone(), &pods).await?;\n-\nOk(())\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Ensure WASI cleanup runs even if tests fail
350,405
14.05.2020 09:22:06
-43,200
7cbc5fa5772d9ce020db2c3f310384972e990a5e
Use anyhow::Result to reduce verbosity
[ { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -174,10 +174,7 @@ async fn verify_wasi_node(node: Node) -> () {\n);\n}\n-async fn create_wasi_pod(\n- client: kube::Client,\n- pods: &Api<Pod>,\n-) -> Result<(), Box<dyn std::error::Error>> {\n+async fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\n// Create a temp directory to use for the host path\nlet tempdir = tempfile::tempdir()?;\nlet p = serde_json::from_value(json!({\n@@ -279,9 +276,7 @@ async fn create_wasi_pod(\nOk(())\n}\n-async fn set_up_wasi_test_environment(\n- client: kube::Client,\n-) -> Result<(), Box<dyn std::error::Error>> {\n+async fn set_up_wasi_test_environment(client: kube::Client) -> anyhow::Result<()> {\nlet secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\nsecrets\n.create(\n@@ -355,7 +350,7 @@ impl Drop for WasiTestResourceCleaner {\n}\n#[tokio::test]\n-async fn test_wasi_provider() -> Result<(), Box<dyn std::error::Error>> {\n+async fn test_wasi_provider() -> anyhow::Result<()> {\nlet client = kube::Client::try_default().await?;\nlet nodes: Api<Node> = Api::all(client);\n@@ -399,7 +394,7 @@ async fn assert_pod_log_equals(\npods: &Api<Pod>,\npod_name: &str,\nexpected_log: &str,\n-) -> Result<(), Box<dyn std::error::Error>> {\n+) -> anyhow::Result<()> {\nlet mut logs = pods.log_stream(pod_name, &LogParams::default()).await?;\nwhile let Some(line) = logs.try_next().await? {\n@@ -409,10 +404,7 @@ async fn assert_pod_log_equals(\nOk(())\n}\n-async fn assert_pod_exited_successfully(\n- pods: &Api<Pod>,\n- pod_name: &str,\n-) -> Result<(), Box<dyn std::error::Error>> {\n+async fn assert_pod_exited_successfully(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\nlet pod = pods.get(pod_name).await?;\nlet state = (|| {\n@@ -432,7 +424,7 @@ async fn assert_container_file_contains(\ncontainer_file_path: &str,\nexpected_content: &str,\nfile_error: &str,\n-) -> Result<(), Box<dyn std::error::Error>> {\n+) -> anyhow::Result<()> {\nlet file_path_base = dirs::home_dir()\n.expect(\"home dir does not exist\")\n.join(\".krustlet/volumes/hello-wasi-default\");\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Use anyhow::Result to reduce verbosity
350,426
14.05.2020 02:59:00
0
178a6935a2d1ad15806035e5c7510bbb810c05ed
Implement graceful shutdown.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "///! This library contains code for running a kubelet. Use this to create a new\n///! Kubelet with a specific handler (called a `Provider`)\nuse crate::config::Config;\n-use crate::node::{cordon_node, create_node, update_node};\n+use crate::node::{create_node, delete_node, drain_node, update_node};\nuse crate::queue::PodQueue;\nuse crate::server::start_webserver;\nuse crate::status::{update_pod_status, Phase};\nuse crate::Provider;\n+use futures::future::FutureExt;\nuse futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::{\n@@ -53,29 +54,158 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n/// events, which it will handle.\npub async fn start(&self) -> anyhow::Result<()> {\nlet client = kube::Client::new(self.kube_config.clone());\n- let handler_client = client.clone();\n+\n// Create the node. If it already exists, \"adopt\" the node definition\ncreate_node(&client, &self.config, self.provider.clone()).await;\n- // Get the node name for use in the update loop\n- let node_name = self.config.node_name.clone();\n+ // Flag to indicate graceful shutdown has started.\n+ let signal = Arc::new(AtomicBool::new(false));\n+ signal_hook::flag::register(signal_hook::SIGINT, Arc::clone(&signal))?;\n+\n+ // Start the webserver\n+ let webserver = start_webserver(self.provider.clone(), &self.config.server_config).fuse();\n+\n+ let (error_sender, error_receiver) =\n+ mpsc::channel::<(KubePod, anyhow::Error)>(self.config.max_pods as usize);\n+ let error_handler = start_error_handler(error_receiver, client.clone()).fuse();\n+\n// Start updating the node lease periodically\n- let update_client = client.clone();\n- let node_updater = tokio::task::spawn(async move {\n- let sleep_interval = std::time::Duration::from_secs(10);\n+ let node_updater = start_node_updater(\n+ Arc::clone(&signal),\n+ client.clone(),\n+ self.config.node_name.clone(),\n+ )\n+ .fuse();\n+\n+ // If any of these tasks fail, we can initiate graceful shutdown.\n+ let services = async {\n+ futures::pin_mut!(webserver, error_handler, node_updater);\n+\n+ futures::select! {\n+ res = error_handler => error!(\"Error handler task completed with result: {:?}\", &res),\n+ res = webserver => error!(\"Webserver task completed with result {:?}\", &res),\n+ res = node_updater => if let Err(e) = res {\n+ error!(\"Node updater task completed with error {:?}\", &e);\n+ }\n+ };\n+ signal.store(true, Ordering::Relaxed);\n+ Ok::<(), anyhow::Error>(())\n+ };\n+\n+ // Periodically checks for shutdown signal and cleans up resources gracefully if caught.\n+ let signal_handler = start_signal_handler(\n+ Arc::clone(&signal),\n+ client.clone(),\n+ self.config.node_name.clone(),\n+ )\n+ .fuse();\n+\n+ // Create a queue that locks on events per pod\n+ let queue = PodQueue::new(self.provider.clone(), error_sender);\n+ let pod_informer =\n+ start_pod_informer::<T>(client.clone(), self.config.node_name.clone(), queue).fuse();\n+\n+ // These must all be running for graceful shutdown. An error here exits ungracefully.\n+ let core = async {\n+ futures::pin_mut!(pod_informer, signal_handler);\n+\n+ futures::select! {\n+ res = signal_handler => res.map_err(|e| {\n+ error!(\"Signal handler task joined with error {:?}\", &e);\n+ e.into()\n+ }),\n+ res = pod_informer => res.map_err(|e| {\n+ error!(\"Pod informer task joined with error {:?}\", &e);\n+ e.into()\n+ })\n+ }\n+ };\n+\n+ // Services will not return an error, so this will wait for both to return, or core to\n+ // return an error. Services will return if signal is set because node_updater checks this\n+ // and will exit.\n+ futures::try_join!(core, services)?;\n+ Ok(())\n+ }\n+}\n+\n+// We cannot `#[derive(Clone)]` because that would place the\n+// unnecessary `P: Clone` constraint.\n+impl<P> Clone for Kubelet<P> {\n+ fn clone(&self) -> Self {\n+ Self {\n+ provider: self.provider.clone(),\n+ kube_config: self.kube_config.clone(),\n+ config: self.config.clone(),\n+ }\n+ }\n+}\n+\n+/// Listens for updates to pods on this node and forwards them to queue.\n+async fn start_pod_informer<P: 'static + Provider + Sync + Send>(\n+ client: kube::Client,\n+ node_name: String,\n+ mut queue: PodQueue<P>,\n+) -> anyhow::Result<()> {\n+ let node_selector = format!(\"spec.nodeName={}\", node_name);\n+ let params = ListParams {\n+ field_selector: Some(node_selector),\n+ ..Default::default()\n+ };\n+ let api = Api::<KubePod>::all(client);\n+ let informer = Informer::new(api).params(params);\nloop {\n- update_node(&update_client, &node_name).await;\n+ // TODO Should these results be ignored if Err? It seems reasonable to just keep trying,\n+ // especially since this function is critical for a graceful shutdown.\n+ let mut stream = informer.poll().await?.boxed();\n+ while let Some(event) = stream.try_next().await? {\n+ debug!(\"Handling Kubernetes pod event: {:?}\", event);\n+ match queue.enqueue(event).await {\n+ Ok(()) => debug!(\"Enqueued event for processing\"),\n+ Err(e) => warn!(\"Error enqueuing pod event: {}\", e),\n+ };\n+ }\n+ }\n+}\n+\n+/// Periodically renew node lease. Exits if signal is caught.\n+async fn start_node_updater(\n+ signal: Arc<AtomicBool>,\n+ client: kube::Client,\n+ node_name: String,\n+) -> anyhow::Result<()> {\n+ let sleep_interval = std::time::Duration::from_secs(10);\n+ while !signal.load(Ordering::Relaxed) {\n+ update_node(&client, &node_name).await;\ntokio::time::delay_for(sleep_interval).await;\n}\n- });\n+ Ok(())\n+}\n- // TODO: How should we configure this value? We should eventually have a max pods setting\n- // just like a normal kubelet, so maybe that?\n- let (error_sender, mut error_receiver) = mpsc::channel::<(KubePod, anyhow::Error)>(200);\n- let client_clone = client.clone();\n- let error_handler = tokio::task::spawn(async move {\n- let client = client_clone;\n- while let Some((pod, err)) = error_receiver.recv().await {\n+/// Checks for shutdown signal and cleans up resources gracefully.\n+async fn start_signal_handler(\n+ signal: Arc<AtomicBool>,\n+ client: kube::Client,\n+ node_name: String,\n+) -> anyhow::Result<()> {\n+ let duration = std::time::Duration::from_millis(100);\n+ loop {\n+ if signal.load(Ordering::Relaxed) {\n+ warn!(\"Signal caught.\");\n+ drain_node(&client, &node_name).await?;\n+ delete_node(&client, &node_name).await?;\n+ break Ok(());\n+ }\n+ tokio::time::delay_for(duration).await;\n+ }\n+}\n+\n+/// Consumes error channel and notifies API server of pod failures.\n+async fn start_error_handler(\n+ mut rx: mpsc::Receiver<(KubePod, anyhow::Error)>,\n+ client: kube::Client,\n+) -> anyhow::Result<()> {\n+ while let Some((pod, err)) = rx.recv().await {\nlet json_status = serde_json::json!(\n{\n\"metadata\": {\n@@ -109,74 +239,7 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n),\n}\n}\n- });\n-\n- // Create a queue that locks on events per pod\n- let mut queue = PodQueue::new(self.provider.clone(), error_sender);\n-\n- let node_selector = format!(\"spec.nodeName={}\", self.config.node_name);\n- let pod_informer = tokio::task::spawn(async move {\n- // Create our informer and start listening.\n- let params = ListParams {\n- field_selector: Some(node_selector),\n- ..Default::default()\n- };\n- let api = Api::<KubePod>::all(client);\n- let informer = Informer::new(api).params(params);\n- loop {\n- let mut stream = informer.poll().await.expect(\"informer poll failed\").boxed();\n- while let Some(event) = stream.try_next().await.unwrap() {\n- debug!(\"Handling Kubernetes pod event: {:?}\", event);\n- match queue.enqueue(event).await {\n- Ok(()) => debug!(\"Enqueued event for processing\"),\n- Err(e) => warn!(\"Error enqueuing pod event: {}\", e),\n- };\n- }\n- }\n- });\n-\n- // Start the webserver\n- let webserver = start_webserver(self.provider.clone(), &self.config.server_config);\n-\n- let term = Arc::new(AtomicBool::new(false));\n- signal_hook::flag::register(signal_hook::SIGINT, Arc::clone(&term))?;\n- let node_name = self.config.node_name.clone();\n- let signal_handler = tokio::task::spawn(async move {\n- let duration = std::time::Duration::from_millis(100);\n- loop {\n- if term.load(Ordering::Relaxed) {\n- warn!(\"Signal caught.\");\n- cordon_node(&handler_client, &node_name).await;\n- // TODO: Evict Pods\n- // TODO: Delete node\n- break;\n- }\n- tokio::time::delay_for(duration).await;\n- }\n- });\n-\n- let threads = async {\n- futures::try_join!(node_updater, pod_informer, error_handler, signal_handler)?;\nOk(())\n- };\n-\n- // Return an error as soon as either the webserver or the threads error\n- futures::try_join!(webserver, threads)?;\n-\n- Ok(())\n- }\n-}\n-\n-// We cannot `#[derive(Clone)]` because that would place the\n-// unnecessary `P: Clone` constraint.\n-impl<P> Clone for Kubelet<P> {\n- fn clone(&self) -> Self {\n- Self {\n- provider: self.provider.clone(),\n- kube_config: self.kube_config.clone(),\n- config: self.config.clone(),\n- }\n- }\n}\n#[cfg(test)]\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node.rs", "new_path": "crates/kubelet/src/node.rs", "diff": "use crate::config::Config;\nuse crate::provider::Provider;\nuse chrono::prelude::*;\n+use futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::coordination::v1::Lease;\nuse k8s_openapi::api::core::v1::Node as KubeNode;\n+use k8s_openapi::api::core::v1::Pod;\nuse k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;\n-use kube::api::{Api, DeleteParams, PatchParams, PostParams};\n+use kube::api::{Api, DeleteParams, ListParams, PatchParams, PostParams};\nuse kube::error::ErrorResponse;\nuse kube::Error;\nuse log::{debug, error, info, warn};\nuse std::collections::BTreeMap;\nuse std::sync::Arc;\n-\nconst KUBELET_VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\nmacro_rules! retry {\n@@ -166,6 +167,7 @@ pub async fn create_node<P: 'static + Provider + Sync + Send>(\ninfo!(\"Successfully created node '{}'\", &config.node_name);\n}\n+/// Fetch the uid of a node by name.\npub async fn node_uid(client: &kube::Client, node_name: &str) -> anyhow::Result<String> {\nlet node_client: Api<KubeNode> = Api::all(client.clone());\nmatch retry!(node_client.get(node_name).await, times: 4, log_error: |e| error!(\"Failed to get node to cordon: {:?}\", e))\n@@ -185,33 +187,102 @@ pub async fn node_uid(client: &kube::Client, node_name: &str) -> anyhow::Result<\n}\n}\n-pub async fn cordon_node(client: &kube::Client, node_name: &str) {\n- debug!(\"Cordining node.\");\n- let node_client: Api<KubeNode> = Api::all(client.clone());\n- let patch = serde_json::to_vec(&cordon_patch()).unwrap();\n- let mut params = PatchParams::default();\n- params.patch_strategy = kube::api::PatchStrategy::Merge;\n- let resp = node_client.patch(node_name, &params, patch).await;\n- match &resp {\n- Ok(_) => debug!(\"Node cordoned '{}'\", node_name),\n- Err(e) => error!(\"Failed to cordon node '{}': {}\", node_name, e),\n+/// Cordons node and evicts all pods.\n+pub async fn drain_node(client: &kube::Client, node_name: &str) -> anyhow::Result<()> {\n+ cordon_node(client, node_name).await?;\n+ evict_pods(client, node_name).await?;\n+ Ok(())\n+}\n+\n+/// Fetches list of pods on this node and deletes them.\n+pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Result<()> {\n+ let pod_client: Api<Pod> = Api::all(client.clone());\n+ let node_selector = format!(\"spec.nodeName={}\", node_name);\n+ let params = ListParams {\n+ field_selector: Some(node_selector),\n+ ..Default::default()\n+ };\n+ let kube::api::ObjectList { items: pods, .. } = pod_client.list(&params).await?;\n+\n+ warn!(\"Evicting {} pods.\", pods.len());\n+\n+ // TODO: Filter mirror pods,daemonsets, kube-system?\n+ for pod in &pods {\n+ if let Some(name) = pod.metadata.as_ref().and_then(|meta| meta.name.as_ref()) {\n+ let namespace = pod\n+ .metadata\n+ .as_ref()\n+ .and_then(|meta| meta.namespace.clone())\n+ .unwrap_or_else(|| \"default\".to_owned());\n+ match evict_pod(&client, name, &namespace).await {\n+ Ok(_) => (),\n+ Err(e) => {\n+ // Absorb the error and attempt to delete other pods with best effort.\n+ error!(\"Error evicting pod: {:?}\", e)\n}\n}\n+ } else {\n+ error!(\"Pod with no name: {:?}\", pod.metadata);\n+ }\n+ }\n+ Ok(())\n+}\n-fn cordon_patch() -> serde_json::Value {\n- serde_json::json!({\n- \"apiVersion\": \"v1\",\n- \"kind\": \"Node\",\n- \"spec\": {\n- \"taints\": [\n- {\n- \"effect\": \"NoSchedule\",\n- \"key\": \"node.kubernetes.io/unschedulable\",\n- \"operator\": \"Exists\"\n+async fn evict_pod(client: &kube::Client, name: &str, namespace: &str) -> anyhow::Result<()> {\n+ let ns_client: Api<Pod> = Api::namespaced(client.clone(), namespace);\n+ let lp = ListParams::default()\n+ .fields(&format!(\"metadata.name={}\", name))\n+ .fields(&format!(\"metadata.namespace={}\", namespace));\n+\n+ // The delete call may return a \"pending\" response, we must watch for the actual delete event.\n+ // TODO Timeout?\n+ let mut stream = ns_client.watch(&lp, \"0\").await?.boxed();\n+\n+ warn!(\"Evicting namespace '{}' pod '{}'\", namespace, name);\n+ let params = Default::default();\n+ let response = ns_client.delete(name, &params).await?;\n+\n+ if response.is_left() {\n+ warn!(\"Waiting for pod '{}' eviction.\", name);\n+ while let Some(status) = stream.try_next().await? {\n+ match status {\n+ kube::api::WatchEvent::Deleted(_) => {\n+ warn!(\"Pod '{}' evicted: {:?}\", name, status);\n+ break;\n}\n- ]\n+ _ => (),\n+ }\n+ }\n+ } else {\n+ warn!(\"Pod '{}' evicted.\", name);\n+ }\n+ Ok(())\n+}\n+\n+/// Deregister this node with the kube-apiserver.\n+pub async fn delete_node(client: &kube::Client, node_name: &str) -> anyhow::Result<()> {\n+ warn!(\"Deleting node {}\", node_name);\n+ let params = Default::default();\n+ let node_client: Api<KubeNode> = Api::all(client.clone());\n+ let response = node_client.delete(node_name, &params).await?;\n+ warn!(\"Node deleted: {:?}\", response);\n+ Ok(())\n+}\n+\n+/// Mark this node as unschedulable.\n+pub async fn cordon_node(client: &kube::Client, node_name: &str) -> anyhow::Result<()> {\n+ warn!(\"Cordoning node.\");\n+ let node_client: Api<KubeNode> = Api::all(client.clone());\n+ let patch = serde_json::to_vec(&serde_json::json!({\n+ \"spec\": {\n+ \"unschedulable\": true\n},\n- })\n+ }))?;\n+ let mut params = PatchParams::default();\n+ params.patch_strategy = kube::api::PatchStrategy::Merge;\n+ let response = node_client.patch(node_name, &params, patch).await?;\n+ warn!(\"Node cordoned '{}': {:?}\", node_name, &response);\n+ Ok(())\n}\n/// Update the timestamps on the Node object.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Implement graceful shutdown.
350,426
16.05.2020 15:32:04
0
46aaa44b8530c27b6ded381293677d2dc716fc03
Filter daemonset and mirror pods.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node.rs", "new_path": "crates/kubelet/src/node.rs", "diff": "use crate::config::Config;\nuse crate::pod::Pod;\nuse crate::provider::Provider;\n+use crate::status::{ContainerStatus, Status};\nuse chrono::prelude::*;\nuse futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::coordination::v1::Lease;\n@@ -11,7 +12,7 @@ use kube::api::{Api, DeleteParams, ListParams, PatchParams, PostParams};\nuse kube::error::ErrorResponse;\nuse kube::Error;\nuse log::{debug, error, info, warn};\n-use std::collections::BTreeMap;\n+use std::collections::{BTreeMap, HashMap};\nuse std::sync::Arc;\nconst KUBELET_VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\n@@ -208,14 +209,36 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\nlet lp = ListParams::default().fields(&format!(\"spec.nodeName={}\", node_name));\n// The delete call may return a \"pending\" response, we must watch for the actual delete event.\n- // TODO I dont know what the version number does here.\nlet mut stream = pod_client.watch(&lp, \"0\").await?.boxed();\nwarn!(\"Evicting {} pods.\", pods.len());\n- // TODO: Filter mirror pods,daemonsets, kube-system?\nfor pod in pods {\nlet pod = Pod::new(pod);\n+ if pod.is_daemonset() {\n+ warn!(\"Skipping eviction of DaemonSet '{}'\", pod.name());\n+ continue;\n+ }\n+ if pod.is_static() {\n+ let mut container_statuses = HashMap::new();\n+ for container in pod.containers() {\n+ container_statuses.insert(\n+ container.name.clone(),\n+ ContainerStatus::Terminated {\n+ timestamp: Utc::now(),\n+ message: \"Evicted on node shutdown.\".to_string(),\n+ failed: false,\n+ },\n+ );\n+ }\n+ let status = Status {\n+ message: Some(\"Evicted on node shutdown.\".to_string()),\n+ container_statuses,\n+ };\n+ pod.patch_status(client.clone(), status).await;\n+ warn!(\"Marked static pod as terminated.\");\n+ continue;\n+ }\nmatch evict_pod(&client, pod.name(), pod.namespace(), &mut stream).await {\nOk(_) => (),\nErr(e) => {\n@@ -277,8 +300,8 @@ pub async fn cordon_node(client: &kube::Client, node_name: &str) -> anyhow::Resu\n}))?;\nlet mut params = PatchParams::default();\nparams.patch_strategy = kube::api::PatchStrategy::Merge;\n- let response = node_client.patch(node_name, &params, patch).await?;\n- warn!(\"Node cordoned '{}': {:?}\", node_name, &response);\n+ node_client.patch(node_name, &params, patch).await?;\n+ warn!(\"Node cordoned '{}'.\", node_name);\nOk(())\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod.rs", "new_path": "crates/kubelet/src/pod.rs", "diff": "@@ -84,6 +84,26 @@ impl Pod {\n.unwrap_or_else(|| &EMPTY_MAP)\n}\n+ /// Indicate if this pod is a static pod.\n+ /// TODO: A missing owner_references field was an indication of static pod in my testing but I\n+ /// dont know how reliable this is.\n+ pub fn is_static(&self) -> bool {\n+ self.0.meta().owner_references.is_none()\n+ }\n+\n+ /// Indicate if this pod is part of a Daemonset\n+ pub fn is_daemonset(&self) -> bool {\n+ if let Some(owners) = &self.0.meta().owner_references {\n+ for owner in owners {\n+ match owner.kind.as_ref() {\n+ \"DaemonSet\" => return true,\n+ _ => (),\n+ }\n+ }\n+ }\n+ false\n+ }\n+\n/// Get a specific annotation from the pod\npub fn get_annotation(&self, key: &str) -> Option<&str> {\nSome(self.annotations().get(key)?.as_str())\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Filter daemonset and mirror pods.
350,426
05.05.2020 18:43:49
18,000
c95c35b4ea89c1bfc5aac7d085dc92f25e12093d
Improve parsing and error handling for kubelet API.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/server.rs", "new_path": "crates/kubelet/src/server.rs", "diff": "@@ -79,11 +79,8 @@ async fn handle_request<T>(req: Request<Body>, provider: Arc<T>) -> anyhow::Resu\nwhere\nT: Provider + Send + Sync + 'static,\n{\n- let path: Vec<&str> = req.uri().path().split('/').collect();\n-\n- let response = match (req.method(), path.as_slice()) {\n- (_, path) if path.len() <= 2 => get_ping(),\n- (&Method::GET, [_, \"containerLogs\", namespace, pod, container]) => {\n+ let mut path: Vec<&str> = req.uri().path().split('/').rev().collect();\n+ let method = req.method();\nlet params: std::collections::HashMap<String, String> = req\n.uri()\n.query()\n@@ -93,6 +90,16 @@ where\n.collect()\n})\n.unwrap_or_else(std::collections::HashMap::new);\n+\n+ path.pop();\n+ let resource = path.pop();\n+ match resource {\n+ Some(\"\") | Some(\"healthz\") if method == &Method::GET => get_ping(),\n+ Some(\"containerLogs\") if method == &Method::GET => {\n+ let (namespace, pod, container) = match extract_container_path(path) {\n+ Ok(resource) => resource,\n+ Err(e) => return e,\n+ };\nlet mut tail = None;\nlet mut follow = false;\nfor (key, value) in &params {\n@@ -111,30 +118,90 @@ where\ns => warn!(\"Unknown query parameter: {}={}\", s, value),\n}\n}\n- get_container_logs(\n- &*provider,\n- &req,\n- (*namespace).to_string(),\n- (*pod).to_string(),\n- (*container).to_string(),\n- tail,\n- follow,\n- )\n- .await\n+ get_container_logs(&*provider, &req, namespace, pod, container, tail, follow).await\n}\n- (&Method::POST, [_, \"exec\", _, _, _]) => post_exec(&*provider, &req),\n- _ => Response::builder()\n- .status(StatusCode::NOT_FOUND)\n- .body(Body::from(\"Not Found\"))\n- .unwrap(),\n+ Some(\"exec\") if method == &Method::POST => {\n+ let (namespace, pod, container) = match extract_container_path(path) {\n+ Ok(resource) => resource,\n+ Err(e) => return e,\n};\n+ post_exec(&*provider, &req, namespace, pod, container).await\n+ }\n+ Some(\"tailLines\") | Some(\"containerLogs\") | Some(\"\") | Some(\"healthz\") => return_code(\n+ StatusCode::METHOD_NOT_ALLOWED,\n+ format!(\n+ \"Unsupported method {} for resource '{}'.\",\n+ method,\n+ req.uri().path()\n+ ),\n+ ),\n+ Some(_) | None => return_code(\n+ StatusCode::NOT_FOUND,\n+ format!(\"Unknown resource '{}'.\", req.uri().path()),\n+ ),\n+ }\n+}\n- Ok(response)\n+/// Extract and validate namespace/pod/container resource path.\n+/// On error return response to return to client.\n+fn extract_container_path(\n+ path: Vec<&str>,\n+) -> Result<(String, String, String), anyhow::Result<Response<Body>>> {\n+ match path[..] {\n+ [] => Err(return_code(\n+ StatusCode::BAD_REQUEST,\n+ format!(\"Please specify a namespace.\"),\n+ )),\n+ [_] => Err(return_code(\n+ StatusCode::BAD_REQUEST,\n+ format!(\"Please specify a pod.\"),\n+ )),\n+ [_, _] => Err(return_code(\n+ StatusCode::BAD_REQUEST,\n+ format!(\"Please specify a container.\"),\n+ )),\n+ [s, _, _] if s == \"\" => Err(return_code(\n+ StatusCode::BAD_REQUEST,\n+ format!(\"Please specify a namespace.\"),\n+ )),\n+ [_, s, _] if s == \"\" => Err(return_code(\n+ StatusCode::BAD_REQUEST,\n+ format!(\"Please specify a pod.\"),\n+ )),\n+ [_, _, s] if s == \"\" => Err(return_code(\n+ StatusCode::BAD_REQUEST,\n+ format!(\"Please specify a container.\"),\n+ )),\n+ [namespace, pod, container] => Ok((\n+ namespace.to_string(),\n+ pod.to_string(),\n+ container.to_string(),\n+ )),\n+ [_, _, _, ..] => {\n+ let resource = path\n+ .iter()\n+ .rev()\n+ .map(|s| *s)\n+ .collect::<Vec<&str>>()\n+ .join(\"/\");\n+ Err(return_code(\n+ StatusCode::NOT_FOUND,\n+ format!(\"Unknown resource '{}'.\", resource),\n+ ))\n+ }\n+ }\n}\n/// Return a simple status message\n-fn get_ping() -> Response<Body> {\n- Response::new(Body::from(\"this is the Krustlet HTTP server\"))\n+fn get_ping() -> anyhow::Result<Response<Body>> {\n+ Ok(Response::new(Body::from(\n+ \"this is the Krustlet HTTP server\",\n+ )))\n+}\n+\n+/// Return a HTTP code and message.\n+fn return_code(code: StatusCode, body: String) -> anyhow::Result<Response<Body>> {\n+ Ok(Response::builder().status(code).body(Body::from(body))?)\n}\n/// Get the logs from the running WASM module\n@@ -142,48 +209,52 @@ fn get_ping() -> Response<Body> {\n/// Implements the kubelet path /containerLogs/{namespace}/{pod}/{container}\nasync fn get_container_logs<T: Provider + Sync>(\nprovider: &T,\n- req: &Request<Body>,\n+ _req: &Request<Body>,\nnamespace: String,\npod: String,\ncontainer: String,\ntail: Option<usize>,\nfollow: bool,\n-) -> Response<Body> {\n+) -> anyhow::Result<Response<Body>> {\ndebug!(\n\"Got container log request for container {} in pod {} in namespace {}. tail: {:?}, follow: {}\",\ncontainer, pod, namespace, tail, follow\n);\n- if namespace.is_empty() || pod.is_empty() || container.is_empty() {\n- return Response::builder()\n- .status(StatusCode::NOT_FOUND)\n- .body(Body::from(format!(\n- \"Resource {} not found\",\n- req.uri().path()\n- )))\n- .unwrap();\n- }\n+\nlet (sender, log_body) = hyper::Body::channel();\nlet log_sender = LogSender::new(sender, tail, follow);\nmatch provider.logs(namespace, pod, container, log_sender).await {\n- Ok(()) => Response::new(log_body),\n+ Ok(()) => Ok(Response::new(log_body)),\nErr(e) => {\nerror!(\"Error fetching logs: {}\", e);\n- let mut res = Response::new(Body::from(format!(\"Server error: {}\", e)));\n- *res.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;\nif e.is::<NotImplementedError>() {\n- res = Response::new(Body::from(\"Not Implemented\"));\n- *res.status_mut() = StatusCode::NOT_IMPLEMENTED;\n+ return_code(\n+ StatusCode::NOT_IMPLEMENTED,\n+ format!(\"Logs not implemented in provider.\"),\n+ )\n+ } else {\n+ return_code(\n+ StatusCode::INTERNAL_SERVER_ERROR,\n+ format!(\"Server error: {}\", e),\n+ )\n}\n- res\n}\n}\n}\n+\n/// Run a pod exec command and get the output\n///\n/// Implements the kubelet path /exec/{namespace}/{pod}/{container}\n-fn post_exec<T: Provider>(_provider: &T, _req: &Request<Body>) -> Response<Body> {\n- let mut res = Response::new(Body::from(\"Not Implemented\"));\n- *res.status_mut() = StatusCode::NOT_IMPLEMENTED;\n- res\n+async fn post_exec<T: Provider>(\n+ _provider: &T,\n+ _req: &Request<Body>,\n+ _namespace: String,\n+ _pod: String,\n+ _container: String,\n+) -> anyhow::Result<Response<Body>> {\n+ return_code(\n+ StatusCode::NOT_IMPLEMENTED,\n+ format!(\"Exec not implemented.\"),\n+ )\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Improve parsing and error handling for kubelet API.
350,426
05.05.2020 18:58:28
18,000
5d06758b3ee227bd72b65fc2524b8a222246431f
Fix path ordering and formatting.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/server.rs", "new_path": "crates/kubelet/src/server.rs", "diff": "@@ -79,7 +79,7 @@ async fn handle_request<T>(req: Request<Body>, provider: Arc<T>) -> anyhow::Resu\nwhere\nT: Provider + Send + Sync + 'static,\n{\n- let mut path: Vec<&str> = req.uri().path().split('/').rev().collect();\n+ let mut path: std::collections::VecDeque<&str> = req.uri().path().split('/').collect();\nlet method = req.method();\nlet params: std::collections::HashMap<String, String> = req\n.uri()\n@@ -91,12 +91,12 @@ where\n})\n.unwrap_or_else(std::collections::HashMap::new);\n- path.pop();\n- let resource = path.pop();\n+ path.pop_front();\n+ let resource = path.pop_front();\nmatch resource {\nSome(\"\") | Some(\"healthz\") if method == &Method::GET => get_ping(),\nSome(\"containerLogs\") if method == &Method::GET => {\n- let (namespace, pod, container) = match extract_container_path(path) {\n+ let (namespace, pod, container) = match extract_container_path(path.into()) {\nOk(resource) => resource,\nErr(e) => return e,\n};\n@@ -121,7 +121,7 @@ where\nget_container_logs(&*provider, &req, namespace, pod, container, tail, follow).await\n}\nSome(\"exec\") if method == &Method::POST => {\n- let (namespace, pod, container) = match extract_container_path(path) {\n+ let (namespace, pod, container) = match extract_container_path(path.into()) {\nOk(resource) => resource,\nErr(e) => return e,\n};\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix path ordering and formatting.
350,426
07.05.2020 12:15:30
18,000
30f893e28adf9f06edeb42740d0c3e1466266c46
Fix tail query param.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/logs.rs", "new_path": "crates/kubelet/src/logs.rs", "diff": "@@ -40,13 +40,13 @@ impl std::error::Error for LogSendError {\n#[serde(rename_all = \"camelCase\")]\n/// Client options for fetching logs.\npub struct LogOptions {\n- tail: Option<usize>,\n+ tail_lines: Option<usize>,\nfollow: Option<bool>,\n}\nimpl LogOptions {\npub fn tail(&self) -> Option<usize> {\n- self.tail\n+ self.tail_lines\n}\npub fn follow(&self) -> bool {\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix tail query param.
350,426
07.05.2020 12:43:32
18,000
3c8db271f1d6541d5f33e0263e65b9ef433fa2ff
Respond to comments. Fix e2e test.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -58,6 +58,6 @@ jobs:\nrun: |\njust bootstrap-ssl\njust build\n- ./target/debug/krustlet-wascc --node-name krustlet-wascc --port 3000 --pfx-path ./config/certificate.pfx &\n- ./target/debug/krustlet-wasi --node-name krustlet-wasi --port 3001 --pfx-path ./config/certificate.pfx &\n+ ./target/debug/krustlet-wascc --node-name krustlet-wascc --port 3000 --tls-cert-file ./config/host.cert --tls-private-key-file ./config/host.key &\n+ ./target/debug/krustlet-wasi --node-name krustlet-wasi --port 3001 --tls-cert-file ./config/host.cert --tls-private-key-file ./config/host.key &\njust test-e2e\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/logs.rs", "new_path": "crates/kubelet/src/logs.rs", "diff": "@@ -37,21 +37,12 @@ impl std::error::Error for LogSendError {\n}\n#[derive(Debug, Deserialize)]\n-#[serde(rename_all = \"camelCase\")]\n/// Client options for fetching logs.\npub struct LogOptions {\n- tail_lines: Option<usize>,\n- follow: Option<bool>,\n-}\n-\n-impl LogOptions {\n- pub fn tail(&self) -> Option<usize> {\n- self.tail_lines\n- }\n-\n- pub fn follow(&self) -> bool {\n- self.follow.unwrap_or(false)\n- }\n+ #[serde(rename = \"tailLines\")]\n+ pub tail: Option<usize>,\n+ #[serde(default)]\n+ pub follow: bool,\n}\n/// Sender for streaming logs to client.\n@@ -68,12 +59,12 @@ impl LogSender {\n/// The tail flag indicated by the request if present.\npub fn tail(&self) -> Option<usize> {\n- self.opts.tail()\n+ self.opts.tail\n}\n/// The follow flag indicated by the request, or `false` if absent.\npub fn follow(&self) -> bool {\n- self.opts.follow()\n+ self.opts.follow\n}\n/// Async send some data to a client.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Respond to comments. Fix e2e test.
350,426
20.05.2020 16:06:00
18,000
dd3fb424b028c7ec3b0ec2fd468e5848fd82b14a
Prevent scheduling pods after shutdown has started.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/config.rs", "new_path": "crates/kubelet/src/config.rs", "diff": "@@ -7,7 +7,6 @@ use std::net::IpAddr;\nuse std::net::ToSocketAddrs;\nuse std::path::PathBuf;\n-use rpassword;\n#[cfg(feature = \"cli\")]\nuse structopt::StructOpt;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "@@ -104,8 +104,13 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n// Create a queue that locks on events per pod\nlet queue = PodQueue::new(self.provider.clone(), error_sender);\n- let pod_informer =\n- start_pod_informer::<T>(client.clone(), self.config.node_name.clone(), queue).fuse();\n+ let pod_informer = start_pod_informer::<T>(\n+ client.clone(),\n+ self.config.node_name.clone(),\n+ queue,\n+ Arc::clone(&signal),\n+ )\n+ .fuse();\n// These must all be running for graceful shutdown. An error here exits ungracefully.\nlet core = async {\n@@ -156,6 +161,7 @@ async fn start_pod_informer<P: 'static + Provider + Sync + Send>(\nclient: kube::Client,\nnode_name: String,\nmut queue: PodQueue<P>,\n+ signal: Arc<AtomicBool>,\n) -> anyhow::Result<()> {\nlet node_selector = format!(\"spec.nodeName={}\", node_name);\nlet params = ListParams {\n@@ -177,6 +183,14 @@ async fn start_pod_informer<P: 'static + Provider + Sync + Send>(\nmatch stream.try_next().await {\nOk(Some(event)) => {\ndebug!(\"Handling Kubernetes pod event: {:?}\", event);\n+ if let kube::api::WatchEvent::Added(_) = event {\n+ if signal.load(Ordering::Relaxed) {\n+ warn!(\n+ \"Node is shutting down and unschedulable. Dropping Add Pod event.\"\n+ );\n+ continue;\n+ }\n+ }\nmatch queue.enqueue(event).await {\nOk(()) => debug!(\"Enqueued event for processing\"),\nErr(e) => warn!(\"Error enqueuing pod event: {}\", e),\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node.rs", "new_path": "crates/kubelet/src/node.rs", "diff": "@@ -14,7 +14,8 @@ use kube::Error;\nuse log::{debug, error, info, warn};\nuse std::collections::{BTreeMap, HashMap};\nuse std::sync::Arc;\n-const KUBELET_VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\n+\n+const KUBELET_VERSION: &str = env!(\"CARGO_PKG_VERSION\");\nmacro_rules! retry {\n($action:expr, times: $num_times:expr, error: $on_err:expr) => {{\n@@ -273,16 +274,13 @@ async fn evict_pod(\n// TODO Timeout?\ninfo!(\"Waiting for pod '{}' eviction.\", name);\nwhile let Some(event) = stream.try_next().await? {\n- match event {\n- kube::api::WatchEvent::Deleted(s) => {\n+ if let kube::api::WatchEvent::Deleted(s) = event {\nlet pod = Pod::new(s);\nif name == pod.name() && namespace == pod.namespace() {\ninfo!(\"Pod '{}' evicted.\", name);\nbreak;\n}\n}\n- _ => (),\n- }\n}\n} else {\ninfo!(\"Pod '{}' evicted.\", name);\n@@ -671,8 +669,8 @@ impl NodeBuilder {\n.push(k8s_openapi::api::core::v1::NodeCondition {\ntype_: type_.to_string(),\nstatus: status.to_string(),\n- last_heartbeat_time: Some(Time(timestamp.clone())),\n- last_transition_time: Some(Time(timestamp.clone())),\n+ last_heartbeat_time: Some(Time(*timestamp)),\n+ last_transition_time: Some(Time(*timestamp)),\nreason: Some(reason.to_string()),\nmessage: Some(message.to_string()),\n});\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Prevent scheduling pods after shutdown has started.
350,437
21.05.2020 17:48:23
25,200
8fd2cb5eb3be65c926eb2cd409ba12d90076daf7
Update setup-kind GitHub Action Update configurator GitHub Action
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -24,7 +24,7 @@ jobs:\n}\nsteps:\n- uses: actions/checkout@v2\n- - uses: engineerd/[email protected]\n+ - uses: engineerd/[email protected]\nwith:\nname: ${{ matrix.config.name }}\nurl: ${{ matrix.config.url }}\n@@ -43,7 +43,7 @@ jobs:\nruns-on: ubuntu-latest\nsteps:\n- uses: actions/checkout@v2\n- - uses: engineerd/[email protected]\n+ - uses: engineerd/[email protected]\n- uses: engineerd/[email protected]\nwith:\nname: just\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Update setup-kind GitHub Action Update configurator GitHub Action Signed-off-by: Radu M <[email protected]>
350,415
30.05.2020 10:53:17
14,400
8c51ba13bd573e2e15535475b095d7eec6a3f171
implemented tls bootstrapping
[ { "change_type": "MODIFY", "old_path": ".gitignore", "new_path": ".gitignore", "diff": "@@ -3,3 +3,4 @@ target/\n/config\n_dist/\nnode_modules/\n+.DS_Store\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".vscode/launch.json", "diff": "+{\n+ \"version\": \"0.2.0\",\n+ \"configurations\": [{\n+ \"type\": \"lldb\",\n+ \"request\": \"launch\",\n+ \"name\": \"Kubelet\",\n+ \"args\": [],\n+ \"program\": \"${workspaceFolder}/target/debug/krustlet\",\n+ \"windows\": {\n+ \"program\": \"${workspaceFolder}/target/debug/krustlet.exe\"\n+ },\n+ \"cwd\": \"${workspaceFolder}\",\n+ \"stopOnEntry\": false,\n+ \"sourceLanguages\": [\"rust\"],\n+ \"sourceMap\": {\n+ \"/rustc/*\": \"${env:HOME}/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust\"\n+ }\n+ }]\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -360,9 +360,9 @@ dependencies = [\n[[package]]\nname = \"async-trait\"\n-version = \"0.1.31\"\n+version = \"0.1.33\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"26c4f3195085c36ea8d24d32b2f828d23296a9370a28aa39d111f6f16bef9f3b\"\n+checksum = \"8f1c13101a3224fb178860ae372a031ce350bbd92d39968518f016744dde0bf7\"\ndependencies = [\n\"proc-macro2\",\n\"quote\",\n@@ -535,9 +535,9 @@ dependencies = [\n[[package]]\nname = \"bumpalo\"\n-version = \"3.3.0\"\n+version = \"3.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"5356f1d23ee24a1f785a56d1d1a5f0fd5b0f6a0c0fb2412ce11da71649ab78f6\"\n+checksum = \"2e8c087f005730276d1096a652e92a8bacee2e2472bcc9715a74d2bec38b5820\"\n[[package]]\nname = \"byte-tools\"\n@@ -654,9 +654,9 @@ checksum = \"245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc\"\n[[package]]\nname = \"copyless\"\n-version = \"0.1.4\"\n+version = \"0.1.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"6ff9c56c9fb2a49c05ef0e431485a22400af20d33226dc0764d891d09e724127\"\n+checksum = \"a2df960f5d869b2dd8532793fde43eb5427cceb126c929747a26823ab0eeb536\"\n[[package]]\nname = \"core-foundation\"\n@@ -837,9 +837,9 @@ dependencies = [\n[[package]]\nname = \"crossbeam-queue\"\n-version = \"0.2.1\"\n+version = \"0.2.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"c695eeca1e7173472a32221542ae469b3e9aac3a4fc81f7696bcad82029493db\"\n+checksum = \"ab6bffe714b6bb07e42f201352c34f51fefd355ace793f9e638ebd52d23f98d2\"\ndependencies = [\n\"cfg-if\",\n\"crossbeam-utils\",\n@@ -856,15 +856,6 @@ dependencies = [\n\"lazy_static\",\n]\n-[[package]]\n-name = \"ct-logs\"\n-version = \"0.6.0\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"4d3686f5fa27dbc1d76c751300376e167c5a43387f44bb451fd1c24776e49113\"\n-dependencies = [\n- \"sct\",\n-]\n-\n[[package]]\nname = \"curve25519-dalek\"\nversion = \"1.2.3\"\n@@ -1456,9 +1447,9 @@ dependencies = [\n[[package]]\nname = \"hyper\"\n-version = \"0.13.5\"\n+version = \"0.13.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"96816e1d921eca64d208a85aab4f7798455a8e34229ee5a88c935bdee1b78b14\"\n+checksum = \"a6e7655b9594024ad0ee439f3b5a7299369dc2a3f459b47c696f9ff676f9aa1f\"\ndependencies = [\n\"bytes 0.5.4\",\n\"futures-channel\",\n@@ -1470,8 +1461,8 @@ dependencies = [\n\"httparse\",\n\"itoa\",\n\"log 0.4.8\",\n- \"net2\",\n\"pin-project\",\n+ \"socket2\",\n\"time 0.1.43\",\n\"tokio\",\n\"tower-service\",\n@@ -1485,14 +1476,12 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ac965ea399ec3a25ac7d13b8affd4b8f39325cca00858ddf5eb29b79e6b14b08\"\ndependencies = [\n\"bytes 0.5.4\",\n- \"ct-logs\",\n\"futures-util\",\n\"hyper\",\n\"log 0.4.8\",\n\"rustls 0.17.0\",\n- \"rustls-native-certs\",\n\"tokio\",\n- \"tokio-rustls 0.13.0\",\n+ \"tokio-rustls 0.13.1\",\n\"webpki\",\n]\n@@ -1551,9 +1540,9 @@ dependencies = [\n[[package]]\nname = \"indexmap\"\n-version = \"1.3.2\"\n+version = \"1.4.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"076f042c5b7b98f31d205f1249267e12a6518c1481e9dae9764af19b707d2292\"\n+checksum = \"c398b2b113b55809ceb9ee3e753fcbac793f1956663f3c36549c1346015c2afe\"\ndependencies = [\n\"autocfg 1.0.0\",\n]\n@@ -1585,7 +1574,7 @@ dependencies = [\n\"socket2\",\n\"widestring\",\n\"winapi 0.3.8\",\n- \"winreg\",\n+ \"winreg 0.6.2\",\n]\n[[package]]\n@@ -1614,9 +1603,9 @@ dependencies = [\n[[package]]\nname = \"js-sys\"\n-version = \"0.3.39\"\n+version = \"0.3.40\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"fa5a448de267e7358beaf4a5d849518fe9a0c13fce7afd44b06e68550e5562a7\"\n+checksum = \"ce10c23ad2ea25ceca0093bd3192229da4c5b3c0f2de499c1ecac0d98d452177\"\ndependencies = [\n\"wasm-bindgen\",\n]\n@@ -1702,6 +1691,7 @@ version = \"0.2.1\"\ndependencies = [\n\"anyhow\",\n\"async-trait\",\n+ \"base64 0.12.1\",\n\"chrono\",\n\"dirs\",\n\"futures\",\n@@ -1714,9 +1704,12 @@ dependencies = [\n\"log 0.4.8\",\n\"native-tls\",\n\"oci-distribution\",\n+ \"openssl\",\n\"reqwest\",\n+ \"rpassword\",\n\"serde\",\n\"serde_json\",\n+ \"serde_yaml\",\n\"structopt\",\n\"thiserror\",\n\"tokio\",\n@@ -1745,9 +1738,9 @@ checksum = \"3576a87f2ba00f6f106fdfcd16db1d698d648a26ad8e0573cad8537c3c362d2a\"\n[[package]]\nname = \"libc\"\n-version = \"0.2.70\"\n+version = \"0.2.71\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"3baa92041a6fec78c687fa0cc2b3fae8884f743d672cf551bed1d6dac6988d0f\"\n+checksum = \"9457b06509d27052635f90d6466700c65095fdf75409b3fbdd903e988b886f49\"\n[[package]]\nname = \"libloading\"\n@@ -1803,9 +1796,9 @@ dependencies = [\n[[package]]\nname = \"mach\"\n-version = \"0.2.3\"\n+version = \"0.3.2\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"86dd2487cdfea56def77b88438a2c915fb45113c5319bfe7e14306ca4cd0b0e1\"\n+checksum = \"b823e83b2affd8f40a9ee8c29dbc56404c1e34cd2710921f2801e2cf29527afa\"\ndependencies = [\n\"libc\",\n]\n@@ -2207,18 +2200,18 @@ dependencies = [\n[[package]]\nname = \"pin-project\"\n-version = \"0.4.17\"\n+version = \"0.4.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"edc93aeee735e60ecb40cf740eb319ff23eab1c5748abfdb5c180e4ce49f7791\"\n+checksum = \"ba3a1acf4a3e70849f8a673497ef984f043f95d2d8252dcdf74d54e6a1e47e8a\"\ndependencies = [\n\"pin-project-internal\",\n]\n[[package]]\nname = \"pin-project-internal\"\n-version = \"0.4.17\"\n+version = \"0.4.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"e58db2081ba5b4c93bd6be09c40fd36cb9193a8336c384f3b40012e531aa7e40\"\n+checksum = \"194e88048b71a3e02eb4ee36a6995fed9b8236c11a7bb9f7247a9d9835b3f265\"\ndependencies = [\n\"proc-macro2\",\n\"quote\",\n@@ -2227,9 +2220,9 @@ dependencies = [\n[[package]]\nname = \"pin-project-lite\"\n-version = \"0.1.5\"\n+version = \"0.1.7\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"f7505eeebd78492e0f6108f7171c4948dbb120ee8119d9d77d0afa5469bef67f\"\n+checksum = \"282adbf10f2698a7a77f8e983a74b2d18176c19a7fd32a45446139ae7b02b715\"\n[[package]]\nname = \"pin-utils\"\n@@ -2295,9 +2288,9 @@ checksum = \"8e946095f9d3ed29ec38de908c22f95d9ac008e424c7bcae54c75a79c527c694\"\n[[package]]\nname = \"proc-macro2\"\n-version = \"1.0.17\"\n+version = \"1.0.18\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"1502d12e458c49a4c9cbff560d0fe0060c252bc29799ed94ca2ed4bb665a0101\"\n+checksum = \"beae6331a816b1f65d04c45b078fd8e6c93e8071771f41b8163255bbd8d7c8fa\"\ndependencies = [\n\"unicode-xid\",\n]\n@@ -2538,9 +2531,9 @@ dependencies = [\n[[package]]\nname = \"regex\"\n-version = \"1.3.7\"\n+version = \"1.3.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"a6020f034922e3194c711b82a627453881bc4682166cabb07134a10c26ba7692\"\n+checksum = \"9c3780fcf44b193bc4d09f36d2a3c87b251da4a046c87795a0d35f4f927ad8e6\"\ndependencies = [\n\"aho-corasick\",\n\"memchr\",\n@@ -2550,15 +2543,15 @@ dependencies = [\n[[package]]\nname = \"regex-syntax\"\n-version = \"0.6.17\"\n+version = \"0.6.18\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"7fe5bd57d1d7414c6b5ed48563a2c855d995ff777729dcd91c369ec7fea395ae\"\n+checksum = \"26412eb97c6b088a6997e05f69403a802a92d520de2f8e63c2b65f9e0f47c4e8\"\n[[package]]\nname = \"region\"\n-version = \"2.1.2\"\n+version = \"2.2.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"448e868c6e4cfddfa49b6a72c95906c04e8547465e9536575b95c70a4044f856\"\n+checksum = \"877e54ea2adcd70d80e9179344c97f93ef0dffd6b03e1f4529e6e83ab2fa9ae0\"\ndependencies = [\n\"bitflags\",\n\"libc\",\n@@ -2577,12 +2570,12 @@ dependencies = [\n[[package]]\nname = \"reqwest\"\n-version = \"0.10.4\"\n+version = \"0.10.6\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"02b81e49ddec5109a9dcfc5f2a317ff53377c915e9ae9d4f2fb50914b85614e2\"\n+checksum = \"3b82c9238b305f26f53443e3a4bc8528d64b8d0bee408ec949eb7bf5635ec680\"\ndependencies = [\n\"async-compression\",\n- \"base64 0.11.0\",\n+ \"base64 0.12.1\",\n\"bytes 0.5.4\",\n\"encoding_rs\",\n\"futures-core\",\n@@ -2604,16 +2597,15 @@ dependencies = [\n\"serde\",\n\"serde_json\",\n\"serde_urlencoded\",\n- \"time 0.1.43\",\n\"tokio\",\n- \"tokio-rustls 0.13.0\",\n+ \"tokio-rustls 0.13.1\",\n\"tokio-tls\",\n\"url 2.1.1\",\n\"wasm-bindgen\",\n\"wasm-bindgen-futures\",\n\"web-sys\",\n\"webpki-roots\",\n- \"winreg\",\n+ \"winreg 0.7.0\",\n]\n[[package]]\n@@ -2628,9 +2620,9 @@ dependencies = [\n[[package]]\nname = \"ring\"\n-version = \"0.16.13\"\n+version = \"0.16.14\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"703516ae74571f24b465b4a1431e81e2ad51336cb0ded733a55a1aa3eccac196\"\n+checksum = \"06b3fefa4f12272808f809a0af618501fdaba41a58963c5fb72238ab0be09603\"\ndependencies = [\n\"cc\",\n\"libc\",\n@@ -2662,6 +2654,16 @@ dependencies = [\n\"serde\",\n]\n+[[package]]\n+name = \"rpassword\"\n+version = \"4.0.5\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"99371657d3c8e4d816fb6221db98fa408242b0b53bac08f8676a41f8554fe99f\"\n+dependencies = [\n+ \"libc\",\n+ \"winapi 0.3.8\",\n+]\n+\n[[package]]\nname = \"rust-argon2\"\nversion = \"0.7.0\"\n@@ -2721,23 +2723,11 @@ dependencies = [\n\"webpki\",\n]\n-[[package]]\n-name = \"rustls-native-certs\"\n-version = \"0.3.0\"\n-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"a75ffeb84a6bd9d014713119542ce415db3a3e4748f0bfce1e1416cd224a23a5\"\n-dependencies = [\n- \"openssl-probe\",\n- \"rustls 0.17.0\",\n- \"schannel\",\n- \"security-framework\",\n-]\n-\n[[package]]\nname = \"ryu\"\n-version = \"1.0.4\"\n+version = \"1.0.5\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"ed3d612bc64430efeb3f7ee6ef26d590dce0c43249217bddc62112540c7941e1\"\n+checksum = \"71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e\"\n[[package]]\nname = \"safemem\"\n@@ -2837,9 +2827,9 @@ checksum = \"388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3\"\n[[package]]\nname = \"serde\"\n-version = \"1.0.110\"\n+version = \"1.0.111\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"99e7b308464d16b56eba9964e4972a3eee817760ab60d88c3f86e1fecb08204c\"\n+checksum = \"c9124df5b40cbd380080b2cc6ab894c040a3070d995f5c9dc77e18c34a8ae37d\"\ndependencies = [\n\"serde_derive\",\n]\n@@ -2865,9 +2855,9 @@ dependencies = [\n[[package]]\nname = \"serde_derive\"\n-version = \"1.0.110\"\n+version = \"1.0.111\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"818fbf6bfa9a42d3bfcaca148547aa00c7b915bec71d1757aa2d44ca68771984\"\n+checksum = \"3f2c3ac8e6ca1e9c80b8be1023940162bf81ae3cffbb1809474152f2ce1eb250\"\ndependencies = [\n\"proc-macro2\",\n\"quote\",\n@@ -3038,9 +3028,12 @@ checksum = \"dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8\"\n[[package]]\nname = \"standback\"\n-version = \"0.2.8\"\n+version = \"0.2.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"47e4b8c631c998468961a9ea159f064c5c8499b95b5e4a34b77849d45949d540\"\n+checksum = \"b0437cfb83762844799a60e1e3b489d5ceb6a650fbacb86437badc1b6d87b246\"\n+dependencies = [\n+ \"version_check 0.9.2\",\n+]\n[[package]]\nname = \"stdweb\"\n@@ -3132,9 +3125,9 @@ dependencies = [\n[[package]]\nname = \"subtle\"\n-version = \"2.2.2\"\n+version = \"2.2.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"7c65d530b10ccaeac294f349038a597e435b18fb456aadd0840a623f83b9e941\"\n+checksum = \"502d53007c02d7605a05df1c1a73ee436952781653da5d0bf57ad608f66932c1\"\n[[package]]\nname = \"subtle-encoding\"\n@@ -3147,9 +3140,9 @@ dependencies = [\n[[package]]\nname = \"syn\"\n-version = \"1.0.24\"\n+version = \"1.0.30\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"f87bc5b2815ebb664de0392fdf1b95b6d10e160f86d9f64ff65e5679841ca06a\"\n+checksum = \"93a56fabc59dce20fe48b6c832cc249c713e7ed88fa28b0ee0a3bfcaae5fe4e2\"\ndependencies = [\n\"proc-macro2\",\n\"quote\",\n@@ -3371,9 +3364,9 @@ dependencies = [\n[[package]]\nname = \"tokio-rustls\"\n-version = \"0.13.0\"\n+version = \"0.13.1\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"4adb8b3e5f86b707f1b54e7c15b6de52617a823608ccda98a15d3a24222f265a\"\n+checksum = \"15cb62a0d2770787abc96e99c1cd98fcf17f94959f3af63ca85bdfb203f051b4\"\ndependencies = [\n\"futures-core\",\n\"rustls 0.17.0\",\n@@ -3648,9 +3641,9 @@ dependencies = [\n[[package]]\nname = \"vcpkg\"\n-version = \"0.2.8\"\n+version = \"0.2.9\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"3fc439f2794e98976c88a2a2dafce96b930fe8010b0a256b3c2199a773933168\"\n+checksum = \"55d1e41d56121e07f1e223db0a4def204e45c85425f6a16d462fd07c8d10d74c\"\n[[package]]\nname = \"vec_map\"\n@@ -3893,9 +3886,9 @@ dependencies = [\n[[package]]\nname = \"wasm-bindgen\"\n-version = \"0.2.62\"\n+version = \"0.2.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"e3c7d40d09cdbf0f4895ae58cf57d92e1e57a9dd8ed2e8390514b54a47cc5551\"\n+checksum = \"4c2dc4aa152834bc334f506c1a06b866416a8b6697d5c9f75b9a689c8486def0\"\ndependencies = [\n\"cfg-if\",\n\"serde\",\n@@ -3905,9 +3898,9 @@ dependencies = [\n[[package]]\nname = \"wasm-bindgen-backend\"\n-version = \"0.2.62\"\n+version = \"0.2.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"c3972e137ebf830900db522d6c8fd74d1900dcfc733462e9a12e942b00b4ac94\"\n+checksum = \"ded84f06e0ed21499f6184df0e0cb3494727b0c5da89534e0fcc55c51d812101\"\ndependencies = [\n\"bumpalo\",\n\"lazy_static\",\n@@ -3920,9 +3913,9 @@ dependencies = [\n[[package]]\nname = \"wasm-bindgen-futures\"\n-version = \"0.4.12\"\n+version = \"0.4.13\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"8a369c5e1dfb7569e14d62af4da642a3cbc2f9a3652fe586e26ac22222aa4b04\"\n+checksum = \"64487204d863f109eb77e8462189d111f27cb5712cc9fdb3461297a76963a2f6\"\ndependencies = [\n\"cfg-if\",\n\"js-sys\",\n@@ -3932,9 +3925,9 @@ dependencies = [\n[[package]]\nname = \"wasm-bindgen-macro\"\n-version = \"0.2.62\"\n+version = \"0.2.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"2cd85aa2c579e8892442954685f0d801f9129de24fa2136b2c6a539c76b65776\"\n+checksum = \"838e423688dac18d73e31edce74ddfac468e37b1506ad163ffaf0a46f703ffe3\"\ndependencies = [\n\"quote\",\n\"wasm-bindgen-macro-support\",\n@@ -3942,9 +3935,9 @@ dependencies = [\n[[package]]\nname = \"wasm-bindgen-macro-support\"\n-version = \"0.2.62\"\n+version = \"0.2.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"8eb197bd3a47553334907ffd2f16507b4f4f01bbec3ac921a7719e0decdfe72a\"\n+checksum = \"3156052d8ec77142051a533cdd686cba889537b213f948cd1d20869926e68e92\"\ndependencies = [\n\"proc-macro2\",\n\"quote\",\n@@ -3955,9 +3948,9 @@ dependencies = [\n[[package]]\nname = \"wasm-bindgen-shared\"\n-version = \"0.2.62\"\n+version = \"0.2.63\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"a91c2916119c17a8e316507afaaa2dd94b47646048014bbdf6bef098c1bb58ad\"\n+checksum = \"c9ba19973a58daf4db6f352eda73dc0e289493cd29fb2632eb172085b6521acd\"\n[[package]]\nname = \"wasmparser\"\n@@ -4124,27 +4117,27 @@ dependencies = [\n[[package]]\nname = \"wast\"\n-version = \"17.0.0\"\n+version = \"18.0.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"5a0e1c36b928fca33dbaf96235188f5fad22ee87100e26cc606bd0fbabdf1932\"\n+checksum = \"01b1f23531740a81f9300bd2febd397a95c76bfa4aa4bfaf4ca8b1ee3438f337\"\ndependencies = [\n\"leb128\",\n]\n[[package]]\nname = \"wat\"\n-version = \"1.0.18\"\n+version = \"1.0.19\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"2b50f9e5e5c81e6fd987ae6997a9f4bbb751df2dec1d8cadb0b5778f1ec13bbe\"\n+checksum = \"4006d418d59293172aebfeeadb7673459dc151874a79135946ea7996b6a98515\"\ndependencies = [\n- \"wast 17.0.0\",\n+ \"wast 18.0.0\",\n]\n[[package]]\nname = \"web-sys\"\n-version = \"0.3.39\"\n+version = \"0.3.40\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"8bc359e5dd3b46cb9687a051d50a2fdd228e4ba7cf6fcf861a5365c3d671a642\"\n+checksum = \"7b72fe77fd39e4bd3eaa4412fd299a0be6b3dfe9d2597e2f1c20beb968f41d17\"\ndependencies = [\n\"js-sys\",\n\"wasm-bindgen\",\n@@ -4152,9 +4145,9 @@ dependencies = [\n[[package]]\nname = \"webpki\"\n-version = \"0.21.2\"\n+version = \"0.21.3\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"f1f50e1972865d6b1adb54167d1c8ed48606004c2c9d0ea5f1eeb34d95e863ef\"\n+checksum = \"ab146130f5f790d45f82aeeb09e55a256573373ec64409fc19a6fb82fb1032ae\"\ndependencies = [\n\"ring\",\n\"untrusted\",\n@@ -4162,9 +4155,9 @@ dependencies = [\n[[package]]\nname = \"webpki-roots\"\n-version = \"0.18.0\"\n+version = \"0.19.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"91cd5736df7f12a964a5067a12c62fa38e1bd8080aff1f80bc29be7c80d19ab4\"\n+checksum = \"f8eff4b7516a57307f9349c64bf34caa34b940b66fed4b2fb3136cb7386e5739\"\ndependencies = [\n\"webpki\",\n]\n@@ -4276,6 +4269,15 @@ dependencies = [\n\"winapi 0.3.8\",\n]\n+[[package]]\n+name = \"winreg\"\n+version = \"0.7.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"0120db82e8a1e0b9fb3345a539c478767c0048d842860994d96113d5b667bd69\"\n+dependencies = [\n+ \"winapi 0.3.8\",\n+]\n+\n[[package]]\nname = \"winx\"\nversion = \"0.16.0\"\n@@ -4322,9 +4324,9 @@ dependencies = [\n[[package]]\nname = \"yaml-rust\"\n-version = \"0.4.3\"\n+version = \"0.4.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"65923dd1784f44da1d2c3dbbc5e822045628c590ba72123e1c73d3c230c4434d\"\n+checksum = \"39f0c922f1a334134dc2f7a8b67dc5d25f0735263feec974345ff706bcf20b0d\"\ndependencies = [\n\"linked-hash-map\",\n]\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/Cargo.toml", "new_path": "crates/kubelet/Cargo.toml", "diff": "@@ -34,11 +34,13 @@ docs = [\"cli\"]\n[dependencies]\nasync-trait = \"0.1\"\n+base64 = \"0.12.1\"\ndirs = \"2.0\"\nanyhow = \"1.0\"\nfutures = { version = \"0.3\", default-features = false }\nserde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"\n+serde_yaml = \"0.8.11\"\nhyper = { version = \"0.13\", default-features = false, features = [\"stream\"] }\nlog = \"0.4\"\nreqwest = \"0.10\"\n@@ -56,6 +58,8 @@ oci-distribution = { path = \"../oci-distribution\", version = \"0.1\", default-feat\nurl = \"2.1\"\nwarp = { version = \"0.2\", features = ['tls'] }\nhttp = \"0.2\"\n+rpassword = \"4.0\"\n+openssl = \"0.10.29\"\n[dev-dependencies]\nreqwest = {version = \"0.10\", default-features = false }\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/TLS_BOOTSTRAP.md", "diff": "+# TLS Bootstraping Instructions\n+\n+[TLS bootstrapping](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet-tls-bootstrapping/), at a high level, requires the generation of a bootstrap-kubelet.conf file that contains a bootstrap token.\n+A bootstrap token is a token that has just enough permissions to allow kubelets too auto-negotiate\n+mTLS configuration with the Kube API server. From the Krustlet perspective, this will require developers/operators\n+to execute the following steps:\n+\n+- Generate a bootstrap-kubelet.conf file containing a boostrap token\n+- Proxy the Kube API server to the host\n+- Modify the bootstrap-kubelet.conf file to reflect host to cluster proxy configuration\n+- Set required kubernetes environment variables on the host\n+- Remove/archive all pem/key/crt files in the kubeconfig directory that may have been created when installing krustlet\n+-\n+\n+To generate a bootstrap config you must execute the following commands from the master node\n+in your cluster. Path's will vary based on how you are running your cluster. The paths below\n+work on KinD.\n+\n+To identify your nodes execute this command.\n+\n+```shell\n+$ kubectl get nodes\n+```\n+\n+The output should look similar to this.\n+\n+```shell\n+NAME STATUS ROLES AGE VERSION\n+krustlet-control-plane Ready master 8d v1.17.0\n+```\n+\n+Exceute this command to open an interactive termional with a master node.\n+\n+```shell\n+$ docker exec -it krustlet-control-plane /bin/bash\n+```\n+\n+```shell\n+API_SERVER=\"https://$(cat /etc/kubernetes/kubelet.conf | grep server | sed -r 's/[^0-9.]+/\\n/' | xargs)\" && \\\n+kubectl config --kubeconfig=/etc/kubernetes/bootstrap-kubeconfig set-cluster kubernetes --server=$API_SERVER --certificate-authority=/etc/kubernetes/pki/ca.crt --embed-certs=true &&\n+BOOTSTRAP_TOKEN=$(kubeadm token generate) && \\\n+kubectl config --kubeconfig=/etc/kubernetes/bootstrap-kubeconfig set-credentials tls-bootstrap-token-user --token=$BOOTSTRAP_TOKEN && \\\n+kubectl config --kubeconfig=/etc/kubernetes/bootstrap-kubeconfig set-context tls-bootstrap-token-user@kubernetes --user=tls-bootstrap-token-user --cluster=kubernetes && \\\n+kubectl config --kubeconfig=/etc/kubernetes/bootstrap-kubeconfig use-context tls-bootstrap-token-user@kubernetes\n+```\n+\n+This will generate a file call bootstrap-kubelet.conf in the specified directory. The cluster stanza\n+will contain an entry for the server address that looks like this `server: https://172.17.0.2:6443`.\n+This is the cluster internal address and will not be reachable from your krustlet running on the host.\n+Depending on your kubernetes provider and networking configuration the ip address/port may vary.\n+\n+To enable host to cluster communications for the krustlet bootstrapping process you must:\n+\n+- Expose the Kube API server via proxy with the following command: `kubectl proxy --port=6443`.\n+ You may choose any unassigned port. KinD seems to default to 6443 for in cluster communication\n+ so that port is used throughout these examples.\n+- Copy the contents of the generated bootstrap-kubelet.conf file from the in cluster node where you generated\n+- Modify the bootstrap-kubelet.conf server entry so that it talks to the proxy. e.g. `server: https://127.0.0.1:6443`.\n+ See example-boostrap-kubelet.conf in this directory for a example output.\n+- Set the KUBERNETES_SERVICE_HOST environment variable to localhost. e.g. `export KUBERNETES_SERVICE_HOST=\"127.0.0.1\"`\n+- Set the KUBERNETES_SERVICE_PORT to the port you chose. e.g. `export KUBERNETES_SERVICE_PORT=\"6443\"`.\n+- Set the KUBECONFIG to ~/.krustlet/config/config\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/example-bootstrap-kubelet.conf", "diff": "+apiVersion: v1\n+clusters:\n+- cluster:\n+ certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUN5RENDQWJDZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJd01EVXlNakV4TURRek5sb1hEVE13TURVeU1ERXhNRFF6Tmxvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTXhnCi81dW5RUC9WbVhZUkV4Um5KRkhyRmpZU3VaU1dtL1o4Vlp4RlJjemwxbmVwYUI4c0xVR25KNUNTVGVjUVY5d0kKZmc3NmoweXdta2toQktNdGllVFVTSHE4TTJxbW83aG9RSlhaQytZQ0x3WXRiR0U3eW9CN0o3cUg0WVh4Qk9LSQo5dGh0Q3h2Y096YjRwbGNqdSs2NVhaaW5DaGVsNDh4WHMzeDk0R2dGdTNtb2pLbTdOVVRwL0NNclV5WEVwR1hHClFBYTJOV05STjgyLys1L2wzOXhCVTYzOXA5RjhpaEkvK3pLTEhYZlNIenBDNkV0OFB0dlhmOGxJUTEvRDJtYjUKU04zNlV0NmtFYmt6b2NVMVUzNVpZdHhKaStLSkZjbDBkSUFpb0JrK2dyb09mcHhnV0U0RlYrU1A0Z0NJaHNaWgo1TkhDMXBuVkoxZ2Ziby8rRmdrQ0F3RUFBYU1qTUNFd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0RRWUpLb1pJaHZjTkFRRUxCUUFEZ2dFQkFEWWhodGtoQ29JQUMyVUZld1FEZDI2ZW9qYUUKSVVUQUpTdEFWUVNpOFRHbi9aMlV2Z1lQOE52MFl4cVVod2tXajhRYytaK2srTlRYcVhMR1FEeDhYK2h1UWExSgowM3VoRlNNMkhJeDRQVy80K1VTbml1Sm1aY3BWdGlkNDBDYlRCbzdUdWJudGVSZkVtdW1WOHFHbkJFTEljM09XCktRb3dEMWgycVd5bDk2YmhBb1BwN05pNnNHYmhhNjdlNldObEcxdDJmSHJUWVZ4Nm03cWd4OUw3dzVpWlZ0cE4KRXpCR1VXczJUM2NyRk9WTzF2UUdkTU04aXBKY1VESENhMnJHU0NMQU5zeHlaOFZ6RSs5ZHZWYnVJMWlMMS9SUwp3Y0JMbUtXTW5oVWZvU0VPYlBlbTVZU09UR2NmZ0F6czU5REpjWENYMHJJNEtWazNvM1poaW0yeTMrbz0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=\n+ server: http://127.0.0.1:6443\n+ name: kubernetes\n+contexts:\n+- context:\n+ cluster: kubernetes\n+ user: tls-bootstrap-token-user\n+ name: tls-bootstrap-token-user@kubernetes\n+current-context: tls-bootstrap-token-user@kubernetes\n+kind: Config\n+preferences: {}\n+users:\n+- name: tls-bootstrap-token-user\n+ user:\n+ token: zrgtfy.09fzbp9q1ae88x26\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "@@ -41,12 +41,16 @@ pub struct Kubelet<P> {\nimpl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n/// Create a new Kubelet with a provider, a kubernetes configuration,\n/// and a kubelet configuration\n- pub fn new(provider: T, kube_config: kube::Config, config: Config) -> Self {\n- Self {\n+ pub async fn new(\n+ provider: T,\n+ kube_config: kube::Config,\n+ config: Config,\n+ ) -> anyhow::Result<Self> {\n+ Ok(Self {\nprovider: Arc::new(provider),\nkube_config,\nconfig,\n- }\n+ })\n}\n/// Begin answering requests for the Kubelet.\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/lib.rs", "new_path": "crates/kubelet/src/lib.rs", "diff": "@@ -58,6 +58,7 @@ pub mod image_client;\npub mod module_store;\npub mod provider;\npub mod status;\n+pub mod tls_bootstrapper;\npub mod volumes;\npub use self::kubelet::Kubelet;\n" }, { "change_type": "MODIFY", "old_path": "justfile", "new_path": "justfile", "diff": "-export RUST_LOG := \"wascc_host=debug,wascc_provider=debug,wasi_provider=debug,main=debug\"\n+export RUST_LOG := \"debug\"\nexport PFX_PASSWORD := \"testing\"\nexport KEY_DIR := env_var_or_default('KEY_DIR', '$HOME/.krustlet/config')\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wascc.rs", "new_path": "src/krustlet-wascc.rs", "diff": "@@ -9,7 +9,7 @@ async fn main() -> anyhow::Result<()> {\n// a new Kubelet, all you need to implement is a provider.\nlet config = Config::new_from_file_and_flags(env!(\"CARGO_PKG_VERSION\"), None);\n- let kubeconfig = kube::Config::infer().await?;\n+ let kubeconfig = kubelet::tls_bootstrapper::bootstrap(&config.hostname).await?;\n// Initialize the logger\nenv_logger::init();\n@@ -20,6 +20,6 @@ async fn main() -> anyhow::Result<()> {\nlet store = FileModuleStore::new(client, &module_store_path);\nlet provider = WasccProvider::new(store, &config, kubeconfig.clone()).await?;\n- let kubelet = Kubelet::new(provider, kubeconfig, config);\n+ let kubelet = Kubelet::new(provider, kubeconfig, config).await?;\nkubelet.start().await\n}\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wasi.rs", "new_path": "src/krustlet-wasi.rs", "diff": "@@ -9,7 +9,7 @@ async fn main() -> anyhow::Result<()> {\n// a new Kubelet, all you need to implement is a provider.\nlet config = Config::new_from_file_and_flags(env!(\"CARGO_PKG_VERSION\"), None);\n- let kubeconfig = kube::Config::infer().await?;\n+ let kubeconfig = kubelet::tls_bootstrapper::bootstrap(&config.hostname).await?;\n// Initialize the logger\nenv_logger::init();\n@@ -20,6 +20,6 @@ async fn main() -> anyhow::Result<()> {\nlet store = FileModuleStore::new(client, &module_store_path);\nlet provider = WasiProvider::new(store, &config, kubeconfig.clone()).await?;\n- let kubelet = Kubelet::new(provider, kubeconfig, config);\n+ let kubelet = Kubelet::new(provider, kubeconfig, config).await?;\nkubelet.start().await\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
implemented tls bootstrapping
350,405
08.06.2020 15:06:28
-43,200
a9b57cf029cd0727e1bed846b41dcbc9142e224d
Pass container arguments to WASI module
[ { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/lib.rs", "new_path": "crates/wasi-provider/src/lib.rs", "diff": "@@ -110,6 +110,7 @@ impl<S: ModuleStore + Send + Sync> Provider for WasiProvider<S> {\ninfo!(\"Starting containers for pod {:?}\", pod_name);\nfor container in pod.containers() {\nlet env = Self::env_vars(&container, &pod, &client).await;\n+ let args = container.args.clone().unwrap_or_default();\nlet module_data = modules\n.remove(&container.name)\n.expect(\"FATAL ERROR: module map not properly populated\");\n@@ -142,7 +143,7 @@ impl<S: ModuleStore + Send + Sync> Provider for WasiProvider<S> {\nlet runtime = WasiRuntime::new(\nmodule_data,\nenv,\n- Vec::default(),\n+ args,\ncontainer_volumes,\nself.log_path.clone(),\n)\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -174,19 +174,23 @@ async fn verify_wasi_node(node: Node) -> () {\n);\n}\n+const SIMPLE_WASI_POD: &str = \"hello-wasi\";\n+const VERBOSE_WASI_POD: &str = \"hello-world-verbose\";\n+\nasync fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\n+ let pod_name = SIMPLE_WASI_POD;\n// Create a temp directory to use for the host path\nlet tempdir = tempfile::tempdir()?;\nlet p = serde_json::from_value(json!({\n\"apiVersion\": \"v1\",\n\"kind\": \"Pod\",\n\"metadata\": {\n- \"name\": \"hello-wasi\"\n+ \"name\": pod_name\n},\n\"spec\": {\n\"containers\": [\n{\n- \"name\": \"hello-wasi\",\n+ \"name\": pod_name,\n\"image\": \"webassembly.azurecr.io/hello-wasm:v1\",\n\"volumeMounts\": [\n{\n@@ -242,10 +246,51 @@ async fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resul\nassert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n+ wait_for_pod(client, pod_name).await\n+}\n+\n+async fn create_fancy_schmancy_wasi_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+) -> anyhow::Result<()> {\n+ let pod_name = VERBOSE_WASI_POD;\n+ let p = serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Pod\",\n+ \"metadata\": {\n+ \"name\": pod_name\n+ },\n+ \"spec\": {\n+ \"containers\": [\n+ {\n+ \"name\": pod_name,\n+ \"image\": \"webassembly.azurecr.io/hello-world-wasi-rust:v0.1.0\",\n+ \"args\": [ \"arg1\", \"arg2\" ],\n+ },\n+ ],\n+ \"tolerations\": [\n+ {\n+ \"effect\": \"NoExecute\",\n+ \"key\": \"krustlet/arch\",\n+ \"operator\": \"Equal\",\n+ \"value\": \"wasm32-wasi\"\n+ },\n+ ],\n+ }\n+ }))?;\n+\n+ let pod = pods.create(&PostParams::default(), &p).await?;\n+\n+ assert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n+\n+ wait_for_pod(client, pod_name).await\n+}\n+\n+async fn wait_for_pod(client: kube::Client, pod_name: &str) -> anyhow::Result<()> {\nlet api = Api::namespaced(client.clone(), \"default\");\nlet inf: Informer<Pod> = Informer::new(api).params(\nListParams::default()\n- .fields(\"metadata.name=hello-wasi\")\n+ .fields(&format!(\"metadata.name={}\", pod_name))\n.timeout(30),\n);\n@@ -271,7 +316,7 @@ async fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resul\n}\n}\n- assert!(went_ready, \"pod never went ready\");\n+ assert!(went_ready, format!(\"pod {} never went ready\", pod_name));\nOk(())\n}\n@@ -318,10 +363,7 @@ async fn clean_up_wasi_test_resources() -> () {\nlet client = kube::Client::try_default()\n.await\n.expect(\"Failed to create client\");\n- let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\n- pods.delete(\"hello-wasi\", &DeleteParams::default())\n- .await\n- .expect(\"Failed to delete pod\");\n+\nlet secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\nsecrets\n.delete(\"hello-wasi-secret\", &DeleteParams::default())\n@@ -332,6 +374,14 @@ async fn clean_up_wasi_test_resources() -> () {\n.delete(\"hello-wasi-configmap\", &DeleteParams::default())\n.await\n.expect(\"Failed to delete configmap\");\n+\n+ let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\n+ pods.delete(SIMPLE_WASI_POD, &DeleteParams::default())\n+ .await\n+ .expect(\"Failed to delete pod\");\n+ pods.delete(VERBOSE_WASI_POD, &DeleteParams::default())\n+ .await\n+ .expect(\"Failed to delete pod\");\n}\nstruct WasiTestResourceCleaner {}\n@@ -368,9 +418,9 @@ async fn test_wasi_provider() -> anyhow::Result<()> {\ncreate_wasi_pod(client.clone(), &pods).await?;\n- assert_pod_log_equals(&pods, \"hello-wasi\", \"Hello, world!\\n\").await?;\n+ assert_pod_log_equals(&pods, SIMPLE_WASI_POD, \"Hello, world!\\n\").await?;\n- assert_pod_exited_successfully(&pods, \"hello-wasi\").await?;\n+ assert_pod_exited_successfully(&pods, SIMPLE_WASI_POD).await?;\n// TODO: Create a module that actually reads from a directory and outputs to logs\nassert_container_file_contains(\n@@ -386,6 +436,10 @@ async fn test_wasi_provider() -> anyhow::Result<()> {\n)\n.await?;\n+ create_fancy_schmancy_wasi_pod(client.clone(), &pods).await?;\n+\n+ assert_pod_log_contains(&pods, VERBOSE_WASI_POD, r#\"Args are: [\"arg1\", \"arg2\"]\"#).await?;\n+\nOk(())\n}\n@@ -396,13 +450,41 @@ async fn assert_pod_log_equals(\n) -> anyhow::Result<()> {\nlet mut logs = pods.log_stream(pod_name, &LogParams::default()).await?;\n- while let Some(line) = logs.try_next().await? {\n- assert_eq!(expected_log, String::from_utf8_lossy(&line));\n+ while let Some(chunk) = logs.try_next().await? {\n+ assert_eq!(expected_log, String::from_utf8_lossy(&chunk));\n}\nOk(())\n}\n+async fn assert_pod_log_contains(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ expected_log: &str,\n+) -> anyhow::Result<()> {\n+ let mut logs = pods.log_stream(pod_name, &LogParams::default()).await?;\n+ let mut log_chunks: Vec<String> = Vec::default();\n+\n+ while let Some(chunk) = logs.try_next().await? {\n+ let chunk_text = String::from_utf8_lossy(&chunk);\n+ if chunk_text.contains(expected_log) {\n+ return Ok(()); // can early exit if the expected value is entirely within a chunk\n+ } else {\n+ log_chunks.push(chunk_text.to_string());\n+ }\n+ }\n+\n+ let actual_log_text = log_chunks.join(\"\");\n+ assert!(\n+ actual_log_text.contains(expected_log),\n+ format!(\n+ \"Expected log containing {} but got {}\",\n+ expected_log, actual_log_text\n+ )\n+ );\n+ Ok(())\n+}\n+\nasync fn assert_pod_exited_successfully(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\nlet pod = pods.get(pod_name).await?;\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Pass container arguments to WASI module
350,434
10.06.2020 09:26:29
25,200
1d8bec44272a51cad442d864c6a6501d9b253436
fix(hack/bootstrap): set expiration to 1 hour in the future Fix the direction of time
[ { "change_type": "MODIFY", "old_path": "hack/bootstrap.sh", "new_path": "hack/bootstrap.sh", "diff": "@@ -9,7 +9,7 @@ token_secret=\"$(</dev/random tr -dc a-z0-9 | head -c \"${1:-16}\";echo;)\"\n# support gnu and BSD date command\nexpiration=$(date -u \"+%Y-%m-%dT%H:%M:%SZ\" --date \"1 hour\" 2>/dev/null ||\n- date -v1H -u \"+%Y-%m-%dT%H:%M:%SZ\" 2>/dev/null)\n+ date -v+1H -u \"+%Y-%m-%dT%H:%M:%SZ\" 2>/dev/null)\ncat <<EOF | kubectl apply -f -\napiVersion: v1\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
fix(hack/bootstrap): set expiration to 1 hour in the future Fix the direction of time
350,426
23.06.2020 14:17:59
18,000
c2e9f014dc810bc7e6b4d4a5e8a0e3badd967d31
Fix typo and Bootstraping clarification
[ { "change_type": "MODIFY", "old_path": "docs/howto/bootstrapping.md", "new_path": "docs/howto/bootstrapping.md", "diff": "@@ -131,6 +131,8 @@ Once you have the bootstrap config in place, you can run Krustlet:\n$ KUBECONFIG=~/.krustlet/config/kubeconfig krustlet-wasi --port 3000 --bootstrap-file /path/to/your/bootstrap.conf\n```\n+Krustlet will begin the bootstraping process, and then **await manual certificate approval** (described below) before launching.\n+\nA couple important notes here. `KUBECONFIG` should almost always be set, especially in\ndeveloper/local machine situations. During the bootstrap process, Krustlet will generate a\nkubeconfig with the credentials it obtains during the bootstrapping process and write it out to the\n" }, { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-kind.md", "new_path": "docs/howto/krustlet-on-kind.md", "diff": "@@ -15,7 +15,7 @@ Kubernetes control plane, including KinD itself.\n## Step 1: Get a bootstrap config\nKrustlet requires a bootstrap token and config the first time it runs. Follow the guide\n-[here](bootstrapping.md) to generate a bootstrap config and then return to this document. This will\n+[here](bootstrapping.md) to generate a bootstrap config and then return to this document.\nIf you already have a kubeconfig available that you generated through another process, you can\nproceed to the next step. However, the credentials Krustlet uses must be part of the `system:nodes`\ngroup in order for things to function properly.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix typo and Bootstraping clarification
350,425
13.05.2020 21:48:32
25,200
a23a447dbbbeb9c93280a960aeac8158b92cad1a
Use `token` for image registry auth. According to the [Docker registry documentation](https://docs.docker.com/registry/spec/auth/token/#requesting-a-token), `token` is the preferred field and `access_token` is used for OAuth 2 compatibility. This commit changes the expected auth response to be `token` with an alias of `access_token` to support both.
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -326,12 +326,13 @@ impl ClientProtocol {\n/// A token granted during the OAuth2-like workflow for OCI registries.\n#[derive(serde::Deserialize, Default)]\nstruct RegistryToken {\n- access_token: String,\n+ #[serde(alias = \"access_token\")]\n+ token: String,\n}\nimpl RegistryToken {\nfn bearer_token(&self) -> String {\n- format!(\"Bearer {}\", self.access_token)\n+ format!(\"Bearer {}\", self.token)\n}\n}\n@@ -412,7 +413,7 @@ mod test {\nlet tok = c.token.expect(\"token is available\");\n// We test that the token is longer than a minimal hash.\n- assert!(tok.access_token.len() > 64);\n+ assert!(tok.token.len() > 64);\n}\n#[tokio::test]\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Use `token` for image registry auth. According to the [Docker registry documentation](https://docs.docker.com/registry/spec/auth/token/#requesting-a-token), `token` is the preferred field and `access_token` is used for OAuth 2 compatibility. This commit changes the expected auth response to be `token` with an alias of `access_token` to support both.
350,425
24.06.2020 19:24:18
25,200
88971305da417c051dd000e5118c6ff3e68c69d1
Support authenticating with multiple OCI registries. This commit simply maps registries to authentication tokens so that multiple OCI registries can be used.
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -13,6 +13,7 @@ use futures_util::stream::StreamExt;\nuse hyperx::header::Header;\nuse log::debug;\nuse reqwest::header::HeaderMap;\n+use std::collections::HashMap;\nuse tokio::io::{AsyncWrite, AsyncWriteExt};\nuse www_authenticate::{Challenge, ChallengeFields, RawChallenge, WwwAuthenticate};\n@@ -44,7 +45,7 @@ pub struct ImageData {\n#[derive(Default)]\npub struct Client {\nconfig: ClientConfig,\n- token: Option<RegistryToken>,\n+ tokens: HashMap<String, RegistryToken>,\nclient: reqwest::Client,\n}\n@@ -53,7 +54,7 @@ impl Client {\npub fn new(config: ClientConfig) -> Self {\nSelf {\nconfig,\n- token: None,\n+ tokens: HashMap::new(),\nclient: reqwest::Client::new(),\n}\n}\n@@ -64,7 +65,8 @@ impl Client {\n/// not will attempt to do.\npub async fn pull_image(&mut self, image: &Reference) -> anyhow::Result<ImageData> {\ndebug!(\"Pulling image: {:?}\", image);\n- if self.token.is_none() {\n+\n+ if !self.tokens.contains_key(image.registry()) {\nself.auth(image, None).await?;\n}\n@@ -159,11 +161,11 @@ impl Client {\nmatch auth_res.status() {\nreqwest::StatusCode::OK => {\nlet text = auth_res.text().await?;\n- debug!(\"Recevied response from auth request: {}\", text);\n- let docker_token: RegistryToken = serde_json::from_str(&text)\n+ debug!(\"Received response from auth request: {}\", text);\n+ let token: RegistryToken = serde_json::from_str(&text)\n.context(\"Failed to decode registry token from auth request\")?;\n- self.token = Some(docker_token);\ndebug!(\"Succesfully authorized for image '{:?}'\", image);\n+ self.tokens.insert(image.registry().to_owned(), token);\nOk(())\n}\n_ => {\n@@ -183,7 +185,7 @@ impl Client {\ndebug!(\"Pulling image manifest from {}\", url);\nlet request = self.client.get(&url);\n- let res = request.headers(self.auth_headers()).send().await?;\n+ let res = request.headers(self.auth_headers(image)).send().await?;\n// The OCI spec technically does not allow any codes but 200, 500, 401, and 404.\n// Obviously, HTTP servers are going to send other codes. This tries to catch the\n@@ -214,7 +216,7 @@ impl Client {\ndebug!(\"Pulling image manifest from {}\", url);\nlet request = self.client.get(&url);\n- let res = request.headers(self.auth_headers()).send().await?;\n+ let res = request.headers(self.auth_headers(image)).send().await?;\n// The OCI spec technically does not allow any codes but 200, 500, 401, and 404.\n// Obviously, HTTP servers are going to send other codes. This tries to catch the\n@@ -264,7 +266,7 @@ impl Client {\nlet mut stream = self\n.client\n.get(&url)\n- .headers(self.auth_headers())\n+ .headers(self.auth_headers(image))\n.send()\n.await?\n.bytes_stream();\n@@ -281,12 +283,12 @@ impl Client {\n/// If the struct has Some(bearer), this will insert the bearer token in an\n/// Authorization header. It will also set the Accept header, which must\n/// be set on all OCI Registry request.\n- fn auth_headers(&self) -> HeaderMap {\n+ fn auth_headers(&self, image: &Reference) -> HeaderMap {\nlet mut headers = HeaderMap::new();\nheaders.insert(\"Accept\", \"application/vnd.docker.distribution.manifest.v2+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.oci.image.manifest.v1+json\".parse().unwrap());\n- if let Some(bearer) = self.token.as_ref() {\n- headers.insert(\"Authorization\", bearer.bearer_token().parse().unwrap());\n+ if let Some(token) = self.tokens.get(image.registry()) {\n+ headers.insert(\"Authorization\", token.bearer_token().parse().unwrap());\n}\nheaders\n}\n@@ -411,7 +413,7 @@ mod test {\n.await\n.expect(\"result from auth request\");\n- let tok = c.token.expect(\"token is available\");\n+ let tok = c.tokens.get(image.registry()).expect(\"token is available\");\n// We test that the token is longer than a minimal hash.\nassert!(tok.token.len() > 64);\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Support authenticating with multiple OCI registries. This commit simply maps registries to authentication tokens so that multiple OCI registries can be used.
350,434
01.07.2020 16:11:48
25,200
7b64200f5dd43cf06b623c08113432343e459685
docs(demos): correct install instructions for nkeys
[ { "change_type": "MODIFY", "old_path": "demos/wascc/fileserver/README.md", "new_path": "demos/wascc/fileserver/README.md", "diff": "@@ -33,11 +33,11 @@ To set up your development environment, you'll need the following tools:\nInstructions for [installing\n`cargo`](https://doc.rust-lang.org/cargo/getting-started/installation.html) and\n[`wasm-to-oci`](https://github.com/engineerd/wasm-to-oci) can be found in their respective project's\n-documentation. Once those are installed, `wascap` and `nk` can be installed with\n+documentation. Once those are installed, [`wascap`](https://crates.io/crates/wascap) and [`nkeys`](https://crates.io/crates/nkeys) can be installed with\n```\ncargo install wascap --features \"cli\"\n-cargo install nk --features \"cli\"\n+cargo install nkeys --features \"cli\"\n```\nOnce complete, run `make` to compile the example.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
docs(demos): correct install instructions for nkeys (#309)
350,405
07.07.2020 12:31:19
-43,200
f9c877160d6ca7b20eb2a6f5591843536e20028c
waSCC can't honour container args
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "#![deny(missing_docs)]\nuse async_trait::async_trait;\n-use k8s_openapi::api::core::v1::{ContainerStatus as KubeContainerStatus, Pod as KubePod};\n+use k8s_openapi::api::core::v1::{\n+ Container as KubeContainer, ContainerStatus as KubeContainerStatus, Pod as KubePod,\n+};\nuse kube::{api::DeleteParams, Api};\nuse kubelet::container::{Handle as ContainerHandle, Status as ContainerStatus};\nuse kubelet::handle::StopHandler;\n@@ -208,6 +210,8 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n// produces an error, in which case we mark it Failed.\ndebug!(\"Pod added {:?}\", pod.name());\n+ validate_pod_runnable(&pod)?;\n+\ninfo!(\"Starting containers for pod {:?}\", pod.name());\nlet mut modules = self.store.fetch_pod_modules(&pod).await?;\nlet mut container_handles = HashMap::new();\n@@ -426,6 +430,31 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n}\n}\n+fn validate_pod_runnable(pod: &Pod) -> anyhow::Result<()> {\n+ for container in pod.containers() {\n+ validate_container_runnable(container)?;\n+ }\n+ Ok(())\n+}\n+\n+fn validate_container_runnable(container: &KubeContainer) -> anyhow::Result<()> {\n+ if has_args(container) {\n+ return Err(anyhow::anyhow!(\n+ \"Cannot run {}: spec specifies container args which are not supported on wasCC\",\n+ container.name\n+ ));\n+ }\n+\n+ Ok(())\n+}\n+\n+fn has_args(container: &KubeContainer) -> bool {\n+ match &container.args {\n+ None => false,\n+ Some(vec) => !vec.is_empty(),\n+ }\n+}\n+\nstruct VolumeBinding {\nname: String,\nhost_path: PathBuf,\n@@ -557,3 +586,95 @@ fn wascc_run(\nstatus_recv,\n))\n}\n+\n+#[cfg(test)]\n+mod test {\n+ use super::*;\n+ use serde_json::json;\n+\n+ fn make_pod_spec(containers: Vec<KubeContainer>) -> Pod {\n+ let kube_pod: KubePod = serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Pod\",\n+ \"metadata\": {\n+ \"name\": \"test-pod-spec\"\n+ },\n+ \"spec\": {\n+ \"containers\": containers\n+ }\n+ }))\n+ .unwrap();\n+ Pod::new(kube_pod)\n+ }\n+\n+ #[test]\n+ fn can_run_pod_where_container_has_no_args() {\n+ let containers: Vec<KubeContainer> = serde_json::from_value(json!([\n+ {\n+ \"name\": \"greet-wascc\",\n+ \"image\": \"webassembly.azurecr.io/greet-wascc:v0.4\",\n+ },\n+ ]))\n+ .unwrap();\n+ let pod = make_pod_spec(containers);\n+ validate_pod_runnable(&pod).unwrap();\n+ }\n+\n+ #[test]\n+ fn can_run_pod_where_container_has_empty_args() {\n+ let containers: Vec<KubeContainer> = serde_json::from_value(json!([\n+ {\n+ \"name\": \"greet-wascc\",\n+ \"image\": \"webassembly.azurecr.io/greet-wascc:v0.4\",\n+ \"args\": [],\n+ },\n+ ]))\n+ .unwrap();\n+ let pod = make_pod_spec(containers);\n+ validate_pod_runnable(&pod).unwrap();\n+ }\n+\n+ #[test]\n+ fn cannot_run_pod_where_container_has_args() {\n+ let containers: Vec<KubeContainer> = serde_json::from_value(json!([\n+ {\n+ \"name\": \"greet-wascc\",\n+ \"image\": \"webassembly.azurecr.io/greet-wascc:v0.4\",\n+ \"args\": [\n+ \"--foo\",\n+ \"--bar\"\n+ ]\n+ },\n+ ]))\n+ .unwrap();\n+ let pod = make_pod_spec(containers);\n+ assert!(validate_pod_runnable(&pod).is_err());\n+ }\n+\n+ #[test]\n+ fn cannot_run_pod_where_any_container_has_args() {\n+ let containers: Vec<KubeContainer> = serde_json::from_value(json!([\n+ {\n+ \"name\": \"greet-1\",\n+ \"image\": \"webassembly.azurecr.io/greet-wascc:v0.4\"\n+ },\n+ {\n+ \"name\": \"greet-2\",\n+ \"image\": \"webassembly.azurecr.io/greet-wascc:v0.4\",\n+ \"args\": [\n+ \"--foo\",\n+ \"--bar\"\n+ ]\n+ },\n+ ]))\n+ .unwrap();\n+ let pod = make_pod_spec(containers);\n+ let validation = validate_pod_runnable(&pod);\n+ assert!(validation.is_err());\n+ let message = format!(\"{}\", validation.unwrap_err());\n+ assert!(\n+ message.contains(\"greet-2\"),\n+ \"validation error did not give name of bad container\"\n+ );\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
waSCC can't honour container args (#308)
350,405
07.07.2020 12:31:52
-43,200
72d82c3fafafde3bbf2a06e391de0d17f0c51001
The wasmerciser
[ { "change_type": "ADD", "old_path": null, "new_path": "demos/wasi/wasmerciser/Cargo.lock", "diff": "+# This file is automatically @generated by Cargo.\n+# It is not intended for manual editing.\n+[[package]]\n+name = \"anyhow\"\n+version = \"1.0.31\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"85bb70cc08ec97ca5450e6eba421deeea5f172c0fc61f78b5357b2a8e8be195f\"\n+\n+[[package]]\n+name = \"wasmerciser\"\n+version = \"0.1.0\"\n+dependencies = [\n+ \"anyhow\",\n+]\n" }, { "change_type": "ADD", "old_path": null, "new_path": "demos/wasi/wasmerciser/Cargo.toml", "diff": "+[package]\n+name = \"wasmerciser\"\n+version = \"0.1.0\"\n+authors = [\"itowlson <[email protected]>\"]\n+edition = \"2018\"\n+\n+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html\n+\n+[dependencies]\n+anyhow = \"1.0\"\n+\n+[workspace]\n" }, { "change_type": "ADD", "old_path": null, "new_path": "demos/wasi/wasmerciser/README.md", "diff": "+# Exerciser for WASI\n+\n+A simple WASM module designed to be driven using environment variables\n+and flags to exercise functionality that is useful for Krustlet integration\n+tests.\n+\n+## Building from Source\n+\n+If you want to compile the demo and inspect it, you'll need to do the following.\n+\n+### Prerequisites\n+\n+You'll need to have Rust installed with `wasm32-wasi` target installed:\n+\n+```shell\n+$ rustup target add wasm32-wasi\n+```\n+\n+If you don't have Krustlet with the WASI provider running locally, see the instructions in the\n+[tutorial](../../../docs/intro/tutorial03.md) for running locally.\n+\n+### Building\n+\n+Run:\n+\n+```shell\n+$ cargo build --target wasm32-wasi --release\n+```\n+\n+### Pushing\n+\n+Detailed instructions for pushing a module can be found [here](../../../docs/intro/tutorial02.md).\n+\n+We hope to improve and streamline the build and push process in the future. However, for test\n+purposes, the image will be pushed to the `webassembly` Azure Container Registry.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "demos/wasi/wasmerciser/justfile", "diff": "+export RUST_LOG := \"main=debug\"\n+\n+build +FLAGS='':\n+ cargo build {{FLAGS}}\n+\n+build-wasm +FLAGS='':\n+ cargo build --target wasm32-wasi --release {{FLAGS}}\n+\n+test:\n+ cargo fmt --all -- --check\n+ cargo clippy --workspace\n+ cargo test --workspace\n" }, { "change_type": "ADD", "old_path": null, "new_path": "demos/wasi/wasmerciser/src/main.rs", "diff": "+use std::collections::HashMap;\n+use std::env;\n+use std::path::PathBuf;\n+\n+mod syntax;\n+\n+use crate::syntax::{Command, DataDestination, DataSource, Value, Variable};\n+\n+fn main() -> anyhow::Result<()> {\n+ println!(\"INF: Let's wasmercise!\");\n+\n+ // Vocabulary:\n+ // assert_exists(source)\n+ // assert_value(var)is(val)\n+ // read(source)to(var)\n+ // write(val)to(dest)\n+ //\n+ // source := file:foo or env:foo\n+ // dest := file:foo or stm:stdout or stm:stderr\n+ // var := var:foo\n+ // val := lit:foo (literal text) or var:foo (contents of variable)\n+\n+ let real_environment = RealEnvironment::new();\n+ let mut test_context = TestContext::new(real_environment);\n+\n+ let script = get_script();\n+ let result = test_context.process_commands(script);\n+\n+ let message = match &result {\n+ Ok(()) => \"INF: That's enough wasmercising for now; see you next test!\".to_owned(),\n+ Err(e) => format!(\"ERR: Failed with {}\", e),\n+ };\n+\n+ println!(\"{}\", message);\n+\n+ result\n+}\n+\n+fn get_script() -> Vec<String> {\n+ let command_line_script = get_script_from_command_line();\n+ if command_line_script.is_empty() {\n+ get_script_from_environment_variable()\n+ } else {\n+ command_line_script\n+ }\n+}\n+\n+fn get_script_from_command_line() -> Vec<String> {\n+ // TODO: un-hardwire the module file name\n+ let original_args: Vec<String> = env::args().collect();\n+ if !original_args.is_empty() && original_args[0] == \"wasmerciser.wasm\" {\n+ original_args[1..].to_vec()\n+ } else {\n+ original_args\n+ }\n+}\n+\n+fn get_script_from_environment_variable() -> Vec<String> {\n+ parse_script_from_env_var_value(std::env::var(\"WASMERCISER_RUN_SCRIPT\"))\n+}\n+\n+fn parse_script_from_env_var_value(var_value: Result<String, std::env::VarError>) -> Vec<String> {\n+ match var_value {\n+ Ok(script_text) => words(script_text),\n+ Err(_) => vec![],\n+ }\n+}\n+\n+fn words(text: String) -> Vec<String> {\n+ text.split(' ')\n+ .filter(|s| !s.is_empty())\n+ .map(|s| s.to_owned())\n+ .collect()\n+}\n+\n+trait Environment {\n+ fn get_env_var(&self, name: String) -> Result<String, std::env::VarError>;\n+ fn file_exists(&self, path: &PathBuf) -> bool;\n+ fn file_content(&self, path: &PathBuf) -> std::io::Result<String>;\n+ fn write_file(&mut self, path: &PathBuf, content: String) -> std::io::Result<()>;\n+ fn write_stdout(&mut self, content: String) -> anyhow::Result<()>;\n+ fn write_stderr(&mut self, content: String) -> anyhow::Result<()>;\n+}\n+\n+struct RealEnvironment {}\n+\n+impl RealEnvironment {\n+ fn new() -> Self {\n+ Self {}\n+ }\n+}\n+\n+impl Environment for RealEnvironment {\n+ fn get_env_var(&self, name: String) -> Result<String, std::env::VarError> {\n+ std::env::var(name)\n+ }\n+ fn file_exists(&self, path: &PathBuf) -> bool {\n+ path.exists()\n+ }\n+ fn file_content(&self, path: &PathBuf) -> std::io::Result<String> {\n+ std::fs::read_to_string(path)\n+ }\n+ fn write_file(&mut self, path: &PathBuf, content: String) -> std::io::Result<()> {\n+ std::fs::write(path, content)\n+ }\n+ fn write_stdout(&mut self, content: String) -> anyhow::Result<()> {\n+ println!(\"{}\", content);\n+ Ok(())\n+ }\n+ fn write_stderr(&mut self, content: String) -> anyhow::Result<()> {\n+ eprintln!(\"{}\", content);\n+ Ok(())\n+ }\n+}\n+\n+struct TestContext<E: Environment> {\n+ variables: HashMap<String, String>,\n+ environment: E,\n+}\n+\n+impl<E: Environment> TestContext<E> {\n+ fn new(environment: E) -> Self {\n+ TestContext {\n+ variables: Default::default(),\n+ environment,\n+ }\n+ }\n+\n+ fn process_commands(&mut self, commands: Vec<String>) -> anyhow::Result<()> {\n+ for command_text in commands {\n+ self.process_command_text(command_text)?\n+ }\n+ Ok(())\n+ }\n+\n+ fn process_command_text(&mut self, command_text: String) -> anyhow::Result<()> {\n+ match Command::parse(command_text.clone()) {\n+ Ok(command) => self.process_command(command),\n+ Err(e) => Err(anyhow::anyhow!(\n+ \"Error parsing command '{}': {}\",\n+ command_text,\n+ e\n+ )),\n+ }\n+ }\n+\n+ fn process_command(&mut self, command: Command) -> anyhow::Result<()> {\n+ match command {\n+ Command::AssertExists(source) => self.assert_exists(source),\n+ Command::AssertValue(variable, value) => self.assert_value(variable, value),\n+ Command::Read(source, destination) => self.read(source, destination),\n+ Command::Write(value, destination) => self.write(value, destination),\n+ }\n+ }\n+\n+ fn assert_exists(&mut self, source: DataSource) -> anyhow::Result<()> {\n+ match source {\n+ DataSource::File(path) => self.assert_file_exists(PathBuf::from(path)),\n+ DataSource::Env(name) => self.assert_env_var_exists(name),\n+ }\n+ }\n+\n+ fn assert_value(&mut self, variable: Variable, value: Value) -> anyhow::Result<()> {\n+ let Variable::Variable(testee_name) = variable;\n+ let testee_value = self.get_variable(&testee_name)?;\n+ let against_value = match value {\n+ Value::Variable(v) => self.get_variable(&v)?,\n+ Value::Literal(t) => t,\n+ };\n+ if testee_value == against_value {\n+ Ok(())\n+ } else {\n+ fail_with(format!(\n+ \"Expected {} to have value '{}' but was '{}'\",\n+ testee_name, testee_value, against_value\n+ ))\n+ }\n+ }\n+\n+ fn read(&mut self, source: DataSource, destination: Variable) -> anyhow::Result<()> {\n+ let content = match source {\n+ DataSource::File(path) => self.file_content(PathBuf::from(path)),\n+ DataSource::Env(name) => self.env_var_value(name),\n+ };\n+ let Variable::Variable(dest_name) = destination;\n+ self.variables.insert(dest_name, content?);\n+ Ok(())\n+ }\n+\n+ fn write(&mut self, value: Value, destination: DataDestination) -> anyhow::Result<()> {\n+ let content = match value {\n+ Value::Variable(name) => self.get_variable(&name)?,\n+ Value::Literal(text) => text,\n+ };\n+ match destination {\n+ DataDestination::File(path) => self\n+ .environment\n+ .write_file(&PathBuf::from(path), content)\n+ .map_err(anyhow::Error::new),\n+ DataDestination::StdOut => self.environment.write_stdout(content),\n+ DataDestination::StdErr => self.environment.write_stderr(content),\n+ }\n+ }\n+\n+ fn assert_file_exists(&self, path: PathBuf) -> anyhow::Result<()> {\n+ if self.environment.file_exists(&path) {\n+ Ok(())\n+ } else {\n+ fail_with(format!(\n+ \"File {} was expected to exist but did not\",\n+ path.to_string_lossy()\n+ ))\n+ }\n+ }\n+\n+ fn assert_env_var_exists(&self, name: String) -> anyhow::Result<()> {\n+ match self.environment.get_env_var(name.clone()) {\n+ Ok(_) => Ok(()),\n+ Err(_) => fail_with(format!(\n+ \"Env var {} was supposed to exist but did not\",\n+ name\n+ )),\n+ }\n+ }\n+\n+ fn file_content(&self, path: PathBuf) -> anyhow::Result<String> {\n+ self.environment.file_content(&path).map_err(|e| {\n+ anyhow::anyhow!(\n+ \"Error getting content of file {}: {}\",\n+ path.to_string_lossy(),\n+ e\n+ )\n+ })\n+ }\n+\n+ fn env_var_value(&self, name: String) -> anyhow::Result<String> {\n+ self.environment\n+ .get_env_var(name.clone())\n+ .map_err(|e| anyhow::anyhow!(\"Error getting value of env var {}: {}\", name, e))\n+ }\n+\n+ fn get_variable(&self, name: &str) -> anyhow::Result<String> {\n+ match self.variables.get(name) {\n+ Some(s) => Ok(s.to_owned()),\n+ None => Err(anyhow::anyhow!(\"Variable {} not set\", name)),\n+ }\n+ }\n+}\n+\n+fn fail_with(message: String) -> anyhow::Result<()> {\n+ eprintln!(\"ERR: {}\", message);\n+ Err(anyhow::Error::msg(message))\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+ use std::cell::RefCell;\n+ use std::rc::Rc;\n+\n+ struct FakeOutput {\n+ pub name: String,\n+ pub content: String,\n+ }\n+\n+ struct FakeEnvironment {\n+ pub outputs: Rc<RefCell<Vec<FakeOutput>>>,\n+ }\n+\n+ impl FakeEnvironment {\n+ fn new() -> Self {\n+ FakeEnvironment {\n+ outputs: Rc::new(RefCell::new(vec![])),\n+ }\n+ }\n+\n+ fn over(outputs: &Rc<RefCell<Vec<FakeOutput>>>) -> Self {\n+ FakeEnvironment {\n+ outputs: outputs.clone(),\n+ }\n+ }\n+\n+ fn write_out(&mut self, name: String, content: String) -> anyhow::Result<()> {\n+ self.outputs.borrow_mut().push(FakeOutput { name, content });\n+ Ok(())\n+ }\n+ }\n+\n+ impl Environment for FakeEnvironment {\n+ fn get_env_var(&self, name: String) -> Result<String, std::env::VarError> {\n+ match &name[..] {\n+ \"test1\" => Ok(\"one\".to_owned()),\n+ \"test1a\" => Ok(\"one\".to_owned()),\n+ \"test2\" => Ok(\"two\".to_owned()),\n+ _ => Err(std::env::VarError::NotPresent),\n+ }\n+ }\n+ fn file_exists(&self, path: &PathBuf) -> bool {\n+ path.to_string_lossy() == \"/fizz/buzz.txt\"\n+ }\n+ fn file_content(&self, path: &PathBuf) -> std::io::Result<String> {\n+ if path.to_string_lossy() == \"/fizz/buzz.txt\" {\n+ Ok(\"fizzbuzz!\".to_owned())\n+ } else {\n+ Err(std::io::Error::from(std::io::ErrorKind::NotFound))\n+ }\n+ }\n+ fn write_file(&mut self, path: &PathBuf, content: String) -> std::io::Result<()> {\n+ Ok(self\n+ .write_out(path.to_string_lossy().to_string(), content)\n+ .unwrap())\n+ }\n+ fn write_stdout(&mut self, content: String) -> anyhow::Result<()> {\n+ self.write_out(\"**stdout**\".to_owned(), content)\n+ }\n+ fn write_stderr(&mut self, content: String) -> anyhow::Result<()> {\n+ self.write_out(\"**stderr**\".to_owned(), content)\n+ }\n+ }\n+\n+ fn fake_env() -> FakeEnvironment {\n+ FakeEnvironment::new()\n+ }\n+\n+ #[test]\n+ fn missing_env_var_means_no_script() {\n+ let no_env_var = Err(std::env::VarError::NotPresent);\n+ let result = parse_script_from_env_var_value(no_env_var);\n+ assert_eq!(result.len(), 0);\n+ }\n+\n+ #[test]\n+ fn env_var_with_no_spaces_means_one_command() {\n+ let env_var = Ok(\"hello\".to_owned());\n+ let result = parse_script_from_env_var_value(env_var);\n+ assert_eq!(result.len(), 1);\n+ assert_eq!(\"hello\".to_owned(), result[0]);\n+ }\n+\n+ #[test]\n+ fn env_var_with_spaces_is_split_into_commands() {\n+ let env_var = Ok(\"hello world and goodbye \".to_owned());\n+ let result = parse_script_from_env_var_value(env_var);\n+ assert_eq!(result.len(), 4);\n+ assert_eq!(\"hello\".to_owned(), result[0]);\n+ assert_eq!(\"world\".to_owned(), result[1]);\n+ assert_eq!(\"and\".to_owned(), result[2]);\n+ assert_eq!(\"goodbye\".to_owned(), result[3]);\n+ }\n+\n+ #[test]\n+ fn process_assert_file_exists_ok_when_exists() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_command_text(\"assert_exists(file:/fizz/buzz.txt)\".to_owned());\n+ assert!(result.is_ok());\n+ }\n+\n+ #[test]\n+ fn process_assert_file_exists_fails_when_doesnt_exist() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_command_text(\"assert_exists(file:/nope/nope/nope)\".to_owned());\n+ assert!(result.is_err());\n+ }\n+\n+ #[test]\n+ fn process_assert_env_var_exists_ok_when_exists() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_command_text(\"assert_exists(env:test1)\".to_owned());\n+ assert!(result.is_ok());\n+ }\n+\n+ #[test]\n+ fn process_assert_env_var_exists_fails_when_doesnt_exist() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_command_text(\"assert_exists(env:nope)\".to_owned());\n+ assert!(result.is_err());\n+ }\n+\n+ #[test]\n+ fn process_assert_value_passes_when_matches_variable() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_commands(vec![\n+ \"read(env:test1)to(var:e1)\".to_owned(),\n+ \"read(env:test1a)to(var:e1a)\".to_owned(),\n+ \"assert_value(var:e1)is(var:e1a)\".to_owned(),\n+ ]);\n+ assert!(result.is_ok());\n+ }\n+\n+ #[test]\n+ fn process_assert_value_fails_when_does_not_match_variable() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_commands(vec![\n+ \"read(env:test1)to(var:e1)\".to_owned(),\n+ \"read(env:test2)to(var:e2)\".to_owned(),\n+ \"assert_value(var:e1)is(var:e2)\".to_owned(),\n+ ]);\n+ assert!(result.is_err());\n+ }\n+\n+ #[test]\n+ fn process_assert_value_fails_when_match_variable_does_not_exist() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_commands(vec![\n+ \"read(env:test1)to(var:e1)\".to_owned(),\n+ \"assert_value(var:e1)is(var:prodnose)\".to_owned(),\n+ ]);\n+ assert!(result.is_err());\n+ }\n+\n+ #[test]\n+ fn process_assert_value_passes_when_matches_literal() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_commands(vec![\n+ \"read(env:test1)to(var:e1)\".to_owned(),\n+ \"assert_value(var:e1)is(lit:one)\".to_owned(),\n+ ]);\n+ assert!(result.is_ok());\n+ }\n+\n+ #[test]\n+ fn process_assert_value_fails_when_does_not_match_literal() {\n+ let mut context = TestContext::new(fake_env());\n+ let result = context.process_commands(vec![\n+ \"read(env:test1)to(var:e1)\".to_owned(),\n+ \"assert_value(var:e1)is(lit:two)\".to_owned(),\n+ ]);\n+ assert!(result.is_err());\n+ }\n+\n+ #[test]\n+ fn process_read_file_updates_when_exists() {\n+ let mut context = TestContext::new(fake_env());\n+ context\n+ .process_command_text(\"read(file:/fizz/buzz.txt)to(var:ftest)\".to_owned())\n+ .unwrap();\n+ assert_eq!(context.variables.get(\"ftest\").unwrap(), \"fizzbuzz!\");\n+ }\n+\n+ #[test]\n+ fn process_read_env_var_updates_when_exists() {\n+ let mut context = TestContext::new(fake_env());\n+ context\n+ .process_command_text(\"read(env:test1)to(var:etest)\".to_owned())\n+ .unwrap();\n+ assert_eq!(context.variables.get(\"etest\").unwrap(), \"one\");\n+ }\n+\n+ #[test]\n+ fn process_write_file_writes_to_file() {\n+ let outputs = Rc::new(RefCell::new(Vec::<FakeOutput>::new()));\n+ let mut context = TestContext::new(FakeEnvironment::over(&outputs));\n+ context\n+ .process_commands(vec![\n+ \"read(file:/fizz/buzz.txt)to(var:ftest)\".to_owned(),\n+ \"write(var:ftest)to(file:/some/result)\".to_owned(),\n+ ])\n+ .unwrap();\n+ assert_eq!(outputs.borrow().len(), 1);\n+ assert_eq!(outputs.borrow()[0].name, \"/some/result\");\n+ assert_eq!(outputs.borrow()[0].content, \"fizzbuzz!\");\n+ }\n+\n+ #[test]\n+ fn process_write_stdout_writes_to_stdout() {\n+ let outputs = Rc::new(RefCell::new(Vec::<FakeOutput>::new()));\n+ let mut context = TestContext::new(FakeEnvironment::over(&outputs));\n+ context\n+ .process_commands(vec![\n+ \"read(env:test1)to(var:etest)\".to_owned(),\n+ \"write(var:etest)to(stm:stdout)\".to_owned(),\n+ ])\n+ .unwrap();\n+ assert_eq!(outputs.borrow().len(), 1);\n+ assert_eq!(outputs.borrow()[0].name, \"**stdout**\");\n+ assert_eq!(outputs.borrow()[0].content, \"one\");\n+ }\n+\n+ #[test]\n+ fn process_write_stderr_writes_to_stderr() {\n+ let outputs = Rc::new(RefCell::new(Vec::<FakeOutput>::new()));\n+ let mut context = TestContext::new(FakeEnvironment::over(&outputs));\n+ context\n+ .process_commands(vec![\n+ \"read(env:test1)to(var:etest)\".to_owned(),\n+ \"write(var:etest)to(stm:stderr)\".to_owned(),\n+ ])\n+ .unwrap();\n+ assert_eq!(outputs.borrow().len(), 1);\n+ assert_eq!(outputs.borrow()[0].name, \"**stderr**\");\n+ assert_eq!(outputs.borrow()[0].content, \"one\");\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "demos/wasi/wasmerciser/src/syntax.rs", "diff": "+#[derive(Debug, PartialEq)]\n+pub enum Command {\n+ AssertExists(DataSource),\n+ AssertValue(Variable, Value),\n+ Read(DataSource, Variable),\n+ Write(Value, DataDestination),\n+}\n+\n+impl Command {\n+ pub fn parse(text: String) -> anyhow::Result<Self> {\n+ let tokens = CommandToken::parse(text)?;\n+ match &tokens[0] {\n+ CommandToken::Bracketed(t) => {\n+ Err(anyhow::anyhow!(\"don't put commands in brackets: {}\", t))\n+ }\n+ CommandToken::Plain(t) => match &t[..] {\n+ \"assert_exists\" => Self::parse_assert_exists(&tokens),\n+ \"assert_value\" => Self::parse_assert_value(&tokens),\n+ \"read\" => Self::parse_read(&tokens),\n+ \"write\" => Self::parse_write(&tokens),\n+ _ => Err(anyhow::anyhow!(\"unrecognised command: {}\", t)),\n+ },\n+ }\n+ }\n+\n+ fn parse_assert_exists(tokens: &[CommandToken]) -> anyhow::Result<Self> {\n+ match &tokens[..] {\n+ [_, CommandToken::Bracketed(source)] => {\n+ Ok(Self::AssertExists(DataSource::parse(source.to_string())?))\n+ }\n+ _ => Err(anyhow::anyhow!(\"unexpected assert_exists command syntax\")),\n+ }\n+ }\n+\n+ fn parse_assert_value(tokens: &[CommandToken]) -> anyhow::Result<Self> {\n+ match &tokens[..] {\n+ // TODO: enforce that the separator is 'is'\n+ [_, CommandToken::Bracketed(variable), CommandToken::Plain(_sep), CommandToken::Bracketed(value)] => {\n+ Ok(Self::AssertValue(\n+ Variable::parse(variable.to_string())?,\n+ Value::parse(value.to_string())?,\n+ ))\n+ }\n+ _ => Err(anyhow::anyhow!(\"unexpected read command syntax\")),\n+ }\n+ }\n+\n+ fn parse_read(tokens: &[CommandToken]) -> anyhow::Result<Self> {\n+ match &tokens[..] {\n+ // TODO: enforce that the separator is 'to'\n+ [_, CommandToken::Bracketed(source), CommandToken::Plain(_sep), CommandToken::Bracketed(destination)] => {\n+ Ok(Self::Read(\n+ DataSource::parse(source.to_string())?,\n+ Variable::parse(destination.to_string())?,\n+ ))\n+ }\n+ _ => Err(anyhow::anyhow!(\"unexpected read command syntax\")),\n+ }\n+ }\n+\n+ fn parse_write(tokens: &[CommandToken]) -> anyhow::Result<Self> {\n+ match &tokens[..] {\n+ // TODO: enforce that the separator is 'to'\n+ [_, CommandToken::Bracketed(value), CommandToken::Plain(_sep), CommandToken::Bracketed(destination)] => {\n+ Ok(Self::Write(\n+ Value::parse(value.to_string())?,\n+ DataDestination::parse(destination.to_string())?,\n+ ))\n+ }\n+ _ => Err(anyhow::anyhow!(\"unexpected read command syntax\")),\n+ }\n+ }\n+}\n+\n+#[derive(Debug, PartialEq)]\n+pub enum DataSource {\n+ File(String),\n+ Env(String),\n+}\n+\n+#[derive(Debug, PartialEq)]\n+pub enum DataDestination {\n+ File(String),\n+ StdOut,\n+ StdErr,\n+}\n+\n+#[derive(Debug, PartialEq)]\n+pub enum Variable {\n+ Variable(String),\n+}\n+\n+#[derive(Debug, PartialEq)]\n+pub enum Value {\n+ Variable(String),\n+ Literal(String),\n+}\n+\n+impl DataSource {\n+ fn parse(text: String) -> anyhow::Result<Self> {\n+ let bits: Vec<&str> = text.split(':').collect();\n+ match bits[..] {\n+ [\"file\", f] => Ok(DataSource::File(f.to_string())),\n+ [\"env\", e] => Ok(DataSource::Env(e.to_string())),\n+ _ => Err(anyhow::anyhow!(\"invalid data source\")),\n+ }\n+ }\n+}\n+\n+impl DataDestination {\n+ fn parse(text: String) -> anyhow::Result<Self> {\n+ let bits: Vec<&str> = text.split(':').collect();\n+ match bits[..] {\n+ [\"file\", f] => Ok(DataDestination::File(f.to_string())),\n+ [\"stm\", \"stdout\"] => Ok(DataDestination::StdOut),\n+ [\"stm\", \"stderr\"] => Ok(DataDestination::StdErr),\n+ _ => Err(anyhow::anyhow!(\"invalid write destination\")),\n+ }\n+ }\n+}\n+\n+impl Variable {\n+ fn parse(text: String) -> anyhow::Result<Self> {\n+ let bits: Vec<&str> = text.split(':').collect();\n+ match bits[..] {\n+ [\"var\", v] => Ok(Variable::Variable(v.to_string())),\n+ _ => Err(anyhow::anyhow!(\"invalid variable reference\")),\n+ }\n+ }\n+}\n+\n+impl Value {\n+ fn parse(text: String) -> anyhow::Result<Self> {\n+ let bits: Vec<&str> = text.split(':').collect();\n+ match bits[..] {\n+ [\"var\", v] => Ok(Self::Variable(v.to_string())),\n+ [\"lit\", t] => Ok(Self::Literal(t.to_string())),\n+ _ => Err(anyhow::anyhow!(\"invalid value\")),\n+ }\n+ }\n+}\n+\n+#[derive(Debug, PartialEq)]\n+enum CommandToken {\n+ Plain(String),\n+ Bracketed(String),\n+}\n+\n+impl CommandToken {\n+ fn parse(text: String) -> anyhow::Result<Vec<Self>> {\n+ if text.starts_with('(') {\n+ match text.find(')') {\n+ None => Err(anyhow::anyhow!(\"unmatched opening parenthesis: {}\", text)),\n+ Some(close_index) => {\n+ let bracketed_text = &text[1..close_index];\n+ let rest = &text[close_index + 1..];\n+ let mut parsed_rest = if !rest.is_empty() {\n+ Self::parse(rest.to_string())?\n+ } else {\n+ Vec::new()\n+ };\n+ parsed_rest.insert(0, Self::Bracketed(bracketed_text.to_string()));\n+ Ok(parsed_rest)\n+ }\n+ }\n+ } else {\n+ match text.find('(') {\n+ None => Ok(vec![Self::Plain(text)]),\n+ Some(open_index) => {\n+ let plain_text = &text[0..open_index];\n+ let rest = &text[open_index..];\n+ let mut parsed_rest = Self::parse(rest.to_string())?;\n+ parsed_rest.insert(0, Self::Plain(plain_text.to_string()));\n+ Ok(parsed_rest)\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+#[cfg(test)]\n+mod tests {\n+ use super::*;\n+\n+ // We want to pass literal strings so having something that accepts &str\n+ // instead of String reduces clutter\n+ fn parse_command(text: &str) -> anyhow::Result<Command> {\n+ Command::parse(text.to_owned())\n+ }\n+ fn parse_tokens(text: &str) -> anyhow::Result<Vec<CommandToken>> {\n+ CommandToken::parse(text.to_owned())\n+ }\n+\n+ #[test]\n+ fn tokenise_one_plain() {\n+ let tokens = parse_tokens(\"fie\").expect(\"Unexpected parsing error\");\n+ assert_eq!(1, tokens.len());\n+ assert_eq!(CommandToken::Plain(\"fie\".to_owned()), tokens[0]);\n+ }\n+\n+ #[test]\n+ fn tokenise_one_bracketed() {\n+ let tokens = parse_tokens(\"(fie)\").expect(\"Unexpected parsing error\");\n+ assert_eq!(1, tokens.len());\n+ assert_eq!(CommandToken::Bracketed(\"fie\".to_owned()), tokens[0]);\n+ }\n+\n+ #[test]\n+ fn tokenise_two() {\n+ let tokens = parse_tokens(\"assert_exists(file:foo)\").expect(\"Unexpected parsing error\");\n+ assert_eq!(2, tokens.len());\n+ assert_eq!(CommandToken::Plain(\"assert_exists\".to_owned()), tokens[0]);\n+ assert_eq!(CommandToken::Bracketed(\"file:foo\".to_owned()), tokens[1]);\n+ }\n+\n+ #[test]\n+ fn tokenise_three() {\n+ let tokens = parse_tokens(\"foo(bar)quux\").expect(\"Unexpected parsing error\");\n+ assert_eq!(3, tokens.len());\n+ assert_eq!(CommandToken::Plain(\"foo\".to_owned()), tokens[0]);\n+ assert_eq!(CommandToken::Bracketed(\"bar\".to_owned()), tokens[1]);\n+ assert_eq!(CommandToken::Plain(\"quux\".to_owned()), tokens[2]);\n+ }\n+\n+ #[test]\n+ fn tokenise_four() {\n+ let tokens = parse_tokens(\"read(file:foo)to(var:ftext)\").expect(\"Unexpected parsing error\");\n+ assert_eq!(4, tokens.len());\n+ assert_eq!(CommandToken::Plain(\"read\".to_owned()), tokens[0]);\n+ assert_eq!(CommandToken::Bracketed(\"file:foo\".to_owned()), tokens[1]);\n+ assert_eq!(CommandToken::Plain(\"to\".to_owned()), tokens[2]);\n+ assert_eq!(CommandToken::Bracketed(\"var:ftext\".to_owned()), tokens[3]);\n+ }\n+\n+ #[test]\n+ fn parse_single_assert() {\n+ let command = parse_command(\"assert_exists(file:foo)\").expect(\"Unexpected parsing error\");\n+ match command {\n+ Command::AssertExists(DataSource::File(f)) => {\n+ assert_eq!(f, \"foo\", \"Expected file 'foo' but got {}\", f)\n+ }\n+ _ => assert!(false, \"Expected AssertExists but got {:?}\", command),\n+ }\n+ }\n+\n+ #[test]\n+ fn parse_single_read() {\n+ let command =\n+ parse_command(\"read(file:foo)to(var:ftext)\").expect(\"Unexpected parsing error\");\n+ match command {\n+ Command::Read(DataSource::File(f), Variable::Variable(v)) => {\n+ assert_eq!(f, \"foo\", \"Expected source file 'foo' but got {}\", f);\n+ assert_eq!(v, \"ftext\", \"Expected dest var 'ftext' but got {}\", v);\n+ }\n+ _ => assert!(false, \"Expected Read but got {:?}\", command),\n+ }\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
The wasmerciser (#303)
350,426
03.07.2020 11:23:47
18,000
45744b0cd67e58b0aa4da7b8159cce0893adb716
Basic KubeContainer wrapper
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/container/mod.rs", "new_path": "crates/kubelet/src/container/mod.rs", "diff": "//! `container` is a collection of utilities surrounding the Kubernetes container API.\n+\n+use k8s_openapi::api::core::v1::Container as KubeContainer;\n+use oci_distribution::Reference;\n+use std::convert::TryInto;\n+\nmod handle;\nmod status;\npub use handle::Handle;\npub use status::Status;\n+\n+/// Specifies how the store should check for module updates\n+#[derive(PartialEq, Debug)]\n+pub enum PullPolicy {\n+ /// Always return the module as it currently appears in the\n+ /// upstream registry\n+ Always,\n+ /// Return the module as it is currently cached in the local store if\n+ /// present; fetch it from the upstream registry only if it it not\n+ /// present in the local store\n+ IfNotPresent,\n+ /// Never fetch the module from the upstream registry; if it is not\n+ /// available locally then return an error\n+ Never,\n+}\n+\n+impl PullPolicy {\n+ /// Parses a module pull policy from a Kubernetes ImagePullPolicy string\n+ pub fn parse(name: Option<&String>) -> anyhow::Result<Option<Self>> {\n+ match name {\n+ None => Ok(None),\n+ Some(s) => Self::parse_str(s),\n+ }\n+ }\n+\n+ fn parse_str(name: &str) -> anyhow::Result<Option<Self>> {\n+ match name {\n+ \"Always\" => Ok(Some(Self::Always)),\n+ \"IfNotPresent\" => Ok(Some(Self::IfNotPresent)),\n+ \"Never\" => Ok(Some(Self::Never)),\n+ other => Err(anyhow::anyhow!(\"unrecognized pull policy {}\", other)),\n+ }\n+ }\n+}\n+\n+/// A Kubernetes Container\n+///\n+/// This is a new type around the k8s_openapi Container definition\n+/// providing convenient accessor methods\n+#[derive(Default, Debug, Clone)]\n+pub struct Container(KubeContainer);\n+\n+impl Container {\n+ /// Create new Container from KubeContainer\n+ pub fn new(container: &KubeContainer) -> Self {\n+ Container(container.clone())\n+ }\n+\n+ /// Get image of container as `oci_distribution::Reference`.\n+ pub fn image(&self) -> anyhow::Result<Option<Reference>> {\n+ match self.0.image.as_ref() {\n+ Some(s) => Some(s.clone().try_into()).transpose(),\n+ None => Ok(None),\n+ }\n+ }\n+\n+ /// Get name of container.\n+ pub fn name(&self) -> &str {\n+ &self.0.name\n+ }\n+\n+ /// Get image pull policy of container applying defaults if None from:\n+ /// https://kubernetes.io/docs/concepts/configuration/overview/#container-images\n+ pub fn image_pull_policy(&self) -> anyhow::Result<PullPolicy> {\n+ match PullPolicy::parse(self.0.image_pull_policy.as_ref())? {\n+ Some(policy) => Ok(policy),\n+ None => match self.image()? {\n+ Some(image) => match image.tag() {\n+ Some(\"latest\") | None => Ok(PullPolicy::Always),\n+ _ => Ok(PullPolicy::IfNotPresent),\n+ },\n+ None => Ok(PullPolicy::IfNotPresent),\n+ },\n+ }\n+ }\n+\n+ /// Get volume mounts of container.\n+ pub fn volume_mounts(&self) -> &Option<Vec<k8s_openapi::api::core::v1::VolumeMount>> {\n+ &self.0.volume_mounts\n+ }\n+\n+ /// Get arguments of container.\n+ pub fn args(&self) -> &Option<Vec<String>> {\n+ &self.0.args\n+ }\n+\n+ /// Get environment of container.\n+ pub fn env(&self) -> &Option<Vec<k8s_openapi::api::core::v1::EnvVar>> {\n+ &self.0.env\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "@@ -209,7 +209,7 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\nlet mut container_statuses = HashMap::new();\nfor container in pod.containers() {\ncontainer_statuses.insert(\n- container.name.clone(),\n+ container.name().to_string(),\nContainerStatus::Terminated {\ntimestamp: Utc::now(),\nmessage: \"Evicted on node shutdown.\".to_string(),\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/mod.rs", "new_path": "crates/kubelet/src/pod/mod.rs", "diff": "@@ -9,6 +9,7 @@ pub use status::{update_status, Phase, Status};\nuse std::collections::HashMap;\n+use crate::container::Container;\nuse chrono::{DateTime, Utc};\nuse k8s_openapi::api::core::v1::{\nContainer as KubeContainer, ContainerStatus as KubeContainerStatus, Pod as KubePod,\n@@ -203,12 +204,15 @@ impl Pod {\n}\n/// Get a pod's containers\n- pub fn containers(&self) -> &Vec<KubeContainer> {\n+ pub fn containers(&self) -> Vec<Container> {\nself.0\n.spec\n.as_ref()\n.map(|s| &s.containers)\n.unwrap_or_else(|| &EMPTY_VEC)\n+ .iter()\n+ .map(|c| Container::new(c))\n+ .collect()\n}\n/// Turn the Pod into the Kubernetes API version of a Pod\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider/mod.rs", "new_path": "crates/kubelet/src/provider/mod.rs", "diff": "use std::collections::HashMap;\nuse async_trait::async_trait;\n-use k8s_openapi::api::core::v1::{ConfigMap, Container, EnvVarSource, Pod as KubePod, Secret};\n+use k8s_openapi::api::core::v1::{ConfigMap, EnvVarSource, Pod as KubePod, Secret};\nuse kube::api::{Api, WatchEvent};\nuse log::{error, info};\nuse thiserror::Error;\n+use crate::container::Container;\nuse crate::log::Sender;\nuse crate::node::Builder;\nuse crate::pod::Pod;\n@@ -127,7 +128,7 @@ pub trait Provider {\nclient: &kube::Client,\n) -> HashMap<String, String> {\nlet mut env = HashMap::new();\n- let vars = match container.env.as_ref() {\n+ let vars = match container.env().as_ref() {\nSome(e) => e,\nNone => return env,\n};\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/store/mod.rs", "new_path": "crates/kubelet/src/store/mod.rs", "diff": "@@ -3,7 +3,6 @@ pub mod oci;\nuse oci_distribution::client::ImageData;\nuse std::collections::HashMap;\n-use std::convert::TryFrom;\nuse std::sync::Arc;\nuse tokio::sync::Mutex;\nuse tokio::sync::RwLock;\n@@ -12,43 +11,10 @@ use async_trait::async_trait;\nuse log::debug;\nuse oci_distribution::Reference;\n+use crate::container::PullPolicy;\nuse crate::pod::Pod;\nuse crate::store::oci::Client;\n-/// Specifies how the store should check for module updates\n-#[derive(PartialEq, Debug)]\n-pub enum PullPolicy {\n- /// Always return the module as it currently appears in the\n- /// upstream registry\n- Always,\n- /// Return the module as it is currently cached in the local store if\n- /// present; fetch it from the upstream registry only if it it not\n- /// present in the local store\n- IfNotPresent,\n- /// Never fetch the module from the upstream registry; if it is not\n- /// available locally then return an error\n- Never,\n-}\n-\n-impl PullPolicy {\n- /// Parses a module pull policy from a Kubernetes ImagePullPolicy string\n- pub fn parse(name: Option<String>) -> anyhow::Result<Option<Self>> {\n- match name {\n- None => Ok(None),\n- Some(n) => Self::parse_str(&n[..]),\n- }\n- }\n-\n- fn parse_str(name: &str) -> anyhow::Result<Option<Self>> {\n- match name {\n- \"Always\" => Ok(Some(Self::Always)),\n- \"IfNotPresent\" => Ok(Some(Self::IfNotPresent)),\n- \"Never\" => Ok(Some(Self::Never)),\n- other => Err(anyhow::anyhow!(\"unrecognized pull policy {}\", other)),\n- }\n- }\n-}\n-\n/// A store of container modules.\n///\n/// This provides the ability to get a module's bytes given an image [`Reference`].\n@@ -82,11 +48,7 @@ impl PullPolicy {\n#[async_trait]\npub trait Store {\n/// Get a module's data given its image `Reference`.\n- async fn get(\n- &self,\n- image_ref: &Reference,\n- pull_policy: Option<PullPolicy>,\n- ) -> anyhow::Result<Vec<u8>>;\n+ async fn get(&self, image_ref: &Reference, pull_policy: PullPolicy) -> anyhow::Result<Vec<u8>>;\n/// Fetch all container modules for a given `Pod` storing the name of the\n/// container and the module's data as key/value pairs in a hashmap.\n@@ -102,16 +64,18 @@ pub trait Store {\npod.name()\n);\n// Fetch all of the container modules in parallel\n- let container_module_futures = pod.containers().iter().map(move |container| {\n- let image = container\n- .image\n- .clone()\n+ let containers = pod.containers();\n+ let container_module_futures = containers.iter().map(move |container| {\n+ let reference = container\n+ .image()\n+ .expect(\"Could not parse image.\")\n.expect(\"FATAL ERROR: container must have an image\");\n- let reference = Reference::try_from(image).unwrap();\n- let pull_policy = PullPolicy::parse(container.image_pull_policy.clone()).unwrap();\n+ let pull_policy = container\n+ .image_pull_policy()\n+ .expect(\"Could not identify pull policy.\");\nasync move {\nOk((\n- container.name.clone(),\n+ container.name().to_string(),\nself.get(&reference, pull_policy).await?,\n))\n}\n@@ -147,18 +111,8 @@ impl<S: Storer, C: Client> LocalStore<S, C> {\n#[async_trait]\nimpl<S: Storer + Sync + Send, C: Client + Sync + Send> Store for LocalStore<S, C> {\n- async fn get(\n- &self,\n- image_ref: &Reference,\n- pull_policy: Option<PullPolicy>,\n- ) -> anyhow::Result<Vec<u8>> {\n- // Specification from https://kubernetes.io/docs/concepts/configuration/overview/#container-images):\n- let effective_pull_policy = pull_policy.unwrap_or(match image_ref.tag() {\n- Some(\"latest\") | None => PullPolicy::Always,\n- _ => PullPolicy::IfNotPresent,\n- });\n-\n- match effective_pull_policy {\n+ async fn get(&self, image_ref: &Reference, pull_policy: PullPolicy) -> anyhow::Result<Vec<u8>> {\n+ match pull_policy {\nPullPolicy::IfNotPresent => {\nif !self.storer.read().await.is_present(image_ref).await {\nself.pull(image_ref).await?\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -220,7 +220,7 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nfor container in pod.containers() {\nlet env = Self::env_vars(&container, &pod, &client).await;\nlet volume_bindings: Vec<VolumeBinding> =\n- if let Some(volume_mounts) = container.volume_mounts.as_ref() {\n+ if let Some(volume_mounts) = container.volume_mounts().as_ref() {\nvolume_mounts\n.iter()\n.map(|vm| -> anyhow::Result<VolumeBinding> {\n@@ -229,7 +229,7 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nanyhow::anyhow!(\n\"no volume with the name of {} found for container {}\",\nvm.name,\n- container.name\n+ container.name()\n)\n})?;\n// We can safely assume that this should be valid UTF-8 because it would have\n@@ -244,10 +244,10 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nvec![]\n};\n- debug!(\"Starting container {} on thread\", container.name);\n+ debug!(\"Starting container {} on thread\", container.name());\nlet module_data = modules\n- .remove(&container.name)\n+ .remove(container.name())\n.expect(\"FATAL ERROR: module map not properly populated\");\nlet lp = self.log_path.clone();\nlet (status_sender, status_recv) = watch::channel(ContainerStatus::Waiting {\n@@ -261,7 +261,7 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n.await?;\nmatch http_result {\nOk(handle) => {\n- container_handles.insert(container.name.clone(), handle);\n+ container_handles.insert(container.name().to_string(), handle);\nstatus_sender\n.broadcast(ContainerStatus::Running {\ntimestamp: chrono::Utc::now(),\n@@ -273,7 +273,7 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n// (it was never used in creating a runtime handle)\nlet mut container_statuses = HashMap::new();\ncontainer_statuses.insert(\n- container.name.clone(),\n+ container.name().to_string(),\nContainerStatus::Terminated {\ntimestamp: chrono::Utc::now(),\nfailed: true,\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/lib.rs", "new_path": "crates/wasi-provider/src/lib.rs", "diff": "@@ -110,12 +110,12 @@ impl<S: Store + Send + Sync> Provider for WasiProvider<S> {\ninfo!(\"Starting containers for pod {:?}\", pod_name);\nfor container in pod.containers() {\nlet env = Self::env_vars(&container, &pod, &client).await;\n- let args = container.args.clone().unwrap_or_default();\n+ let args = container.args().clone().unwrap_or_default();\nlet module_data = modules\n- .remove(&container.name)\n+ .remove(container.name())\n.expect(\"FATAL ERROR: module map not properly populated\");\nlet container_volumes: HashMap<PathBuf, Option<PathBuf>> =\n- if let Some(volume_mounts) = container.volume_mounts.as_ref() {\n+ if let Some(volume_mounts) = container.volume_mounts().as_ref() {\nvolume_mounts\n.iter()\n.map(|vm| -> anyhow::Result<(PathBuf, Option<PathBuf>)> {\n@@ -124,7 +124,7 @@ impl<S: Store + Send + Sync> Provider for WasiProvider<S> {\nanyhow::anyhow!(\n\"no volume with the name of {} found for container {}\",\nvm.name,\n- container.name\n+ container.name()\n)\n})?;\nlet mut guest_path = PathBuf::from(&vm.mount_path);\n@@ -149,9 +149,9 @@ impl<S: Store + Send + Sync> Provider for WasiProvider<S> {\n)\n.await?;\n- debug!(\"Starting container {} on thread\", container.name);\n+ debug!(\"Starting container {} on thread\", container.name());\nlet handle = runtime.start().await?;\n- container_handles.insert(container.name.clone(), handle);\n+ container_handles.insert(container.name().to_string(), handle);\n}\ninfo!(\n\"All containers started for pod {:?}. Updating status\",\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Basic KubeContainer wrapper
350,426
03.07.2020 12:13:12
18,000
f605e55f54c66d04b83dd716e151eb0a74da8f45
Full Container accessor coverage and fix tests.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/container/mod.rs", "new_path": "crates/kubelet/src/container/mod.rs", "diff": "@@ -11,7 +11,7 @@ pub use handle::Handle;\npub use status::Status;\n/// Specifies how the store should check for module updates\n-#[derive(PartialEq, Debug)]\n+#[derive(PartialEq, Debug, Clone, Copy)]\npub enum PullPolicy {\n/// Always return the module as it currently appears in the\n/// upstream registry\n@@ -26,8 +26,23 @@ pub enum PullPolicy {\n}\nimpl PullPolicy {\n+ /// Get image pull policy of container applying defaults if None from:\n+ /// https://kubernetes.io/docs/concepts/configuration/overview/#container-images\n+ pub fn parse_with_ref(policy: Option<&str>, image: Option<Reference>) -> anyhow::Result<Self> {\n+ match PullPolicy::parse(policy)? {\n+ Some(policy) => Ok(policy),\n+ None => match image {\n+ Some(image) => match image.tag() {\n+ Some(\"latest\") | None => Ok(PullPolicy::Always),\n+ _ => Ok(PullPolicy::IfNotPresent),\n+ },\n+ None => Ok(PullPolicy::IfNotPresent),\n+ },\n+ }\n+ }\n+\n/// Parses a module pull policy from a Kubernetes ImagePullPolicy string\n- pub fn parse(name: Option<&String>) -> anyhow::Result<Option<Self>> {\n+ pub fn parse(name: Option<&str>) -> anyhow::Result<Option<Self>> {\nmatch name {\nNone => Ok(None),\nSome(s) => Self::parse_str(s),\n@@ -57,6 +72,26 @@ impl Container {\nContainer(container.clone())\n}\n+ /// Get arguments of container.\n+ pub fn args(&self) -> &Option<Vec<String>> {\n+ &self.0.args\n+ }\n+\n+ /// Get command of container.\n+ pub fn command(&self) -> &Option<Vec<String>> {\n+ &self.0.command\n+ }\n+\n+ /// Get environment of container.\n+ pub fn env(&self) -> &Option<Vec<k8s_openapi::api::core::v1::EnvVar>> {\n+ &self.0.env\n+ }\n+\n+ /// Get environment of container.\n+ pub fn env_from(&self) -> &Option<Vec<k8s_openapi::api::core::v1::EnvFromSource>> {\n+ &self.0.env_from\n+ }\n+\n/// Get image of container as `oci_distribution::Reference`.\npub fn image(&self) -> anyhow::Result<Option<Reference>> {\nmatch self.0.image.as_ref() {\n@@ -65,24 +100,79 @@ impl Container {\n}\n}\n+ /// Get image pull policy of container.\n+ pub fn image_pull_policy(&self) -> anyhow::Result<PullPolicy> {\n+ PullPolicy::parse_with_ref(self.0.image_pull_policy.as_deref(), self.image()?)\n+ }\n+\n+ /// Get lifecycle of container.\n+ pub fn lifecycle(&self) -> Option<&k8s_openapi::api::core::v1::Lifecycle> {\n+ self.0.lifecycle.as_ref()\n+ }\n+\n+ /// Get liveness probe of container.\n+ pub fn liveness_probe(&self) -> Option<&k8s_openapi::api::core::v1::Probe> {\n+ self.0.liveness_probe.as_ref()\n+ }\n+\n/// Get name of container.\npub fn name(&self) -> &str {\n&self.0.name\n}\n- /// Get image pull policy of container applying defaults if None from:\n- /// https://kubernetes.io/docs/concepts/configuration/overview/#container-images\n- pub fn image_pull_policy(&self) -> anyhow::Result<PullPolicy> {\n- match PullPolicy::parse(self.0.image_pull_policy.as_ref())? {\n- Some(policy) => Ok(policy),\n- None => match self.image()? {\n- Some(image) => match image.tag() {\n- Some(\"latest\") | None => Ok(PullPolicy::Always),\n- _ => Ok(PullPolicy::IfNotPresent),\n- },\n- None => Ok(PullPolicy::IfNotPresent),\n- },\n+ /// Get ports of container.\n+ pub fn ports(&self) -> &Option<Vec<k8s_openapi::api::core::v1::ContainerPort>> {\n+ &self.0.ports\n+ }\n+\n+ /// Get readiness probe of container.\n+ pub fn readiness_probe(&self) -> Option<&k8s_openapi::api::core::v1::Probe> {\n+ self.0.readiness_probe.as_ref()\n}\n+\n+ /// Get resources of container.\n+ pub fn resources(&self) -> Option<&k8s_openapi::api::core::v1::ResourceRequirements> {\n+ self.0.resources.as_ref()\n+ }\n+\n+ /// Get security context of container.\n+ pub fn security_context(&self) -> Option<&k8s_openapi::api::core::v1::SecurityContext> {\n+ self.0.security_context.as_ref()\n+ }\n+\n+ /// Get startup probe of container.\n+ pub fn startup_probe(&self) -> Option<&k8s_openapi::api::core::v1::Probe> {\n+ self.0.startup_probe.as_ref()\n+ }\n+\n+ /// Get stdin flag of container.\n+ pub fn stdin(&self) -> Option<bool> {\n+ self.0.stdin\n+ }\n+\n+ /// Get stdin_once flag of container.\n+ pub fn stdin_once(&self) -> Option<bool> {\n+ self.0.stdin_once\n+ }\n+\n+ /// Get termination message path of container.\n+ pub fn termination_message_path(&self) -> Option<&String> {\n+ self.0.termination_message_path.as_ref()\n+ }\n+\n+ /// Get termination message policy of container.\n+ pub fn termination_message_policy(&self) -> Option<&String> {\n+ self.0.termination_message_policy.as_ref()\n+ }\n+\n+ /// Get tty flag of container.\n+ pub fn tty(&self) -> Option<bool> {\n+ self.0.tty\n+ }\n+\n+ /// Get volume devices of container.\n+ pub fn volume_devices(&self) -> &Option<Vec<k8s_openapi::api::core::v1::VolumeDevice>> {\n+ &self.0.volume_devices\n}\n/// Get volume mounts of container.\n@@ -90,13 +180,8 @@ impl Container {\n&self.0.volume_mounts\n}\n- /// Get arguments of container.\n- pub fn args(&self) -> &Option<Vec<String>> {\n- &self.0.args\n- }\n-\n- /// Get environment of container.\n- pub fn env(&self) -> &Option<Vec<k8s_openapi::api::core::v1::EnvVar>> {\n- &self.0.env\n+ /// Get working directory of container.\n+ pub fn working_dir(&self) -> Option<&String> {\n+ self.0.working_dir.as_ref()\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "@@ -279,9 +279,10 @@ async fn start_error_handler(\n#[cfg(test)]\nmod test {\nuse super::*;\n+ use crate::container::Container;\nuse crate::pod::Pod;\nuse k8s_openapi::api::core::v1::{\n- Container, EnvVar, EnvVarSource, ObjectFieldSelector, PodSpec, PodStatus,\n+ Container as KubeContainer, EnvVar, EnvVarSource, ObjectFieldSelector, PodSpec, PodStatus,\n};\nuse kube::api::ObjectMeta;\nuse std::collections::BTreeMap;\n@@ -319,7 +320,7 @@ mod test {\n#[tokio::test]\nasync fn test_env_vars() {\n- let container = Container {\n+ let container = Container::new(&KubeContainer {\nenv: Some(vec![\nEnvVar {\nname: \"first\".into(),\n@@ -394,7 +395,7 @@ mod test {\n},\n]),\n..Default::default()\n- };\n+ });\nlet name = \"my-name\".to_string();\nlet namespace = Some(\"my-namespace\".to_string());\nlet mut labels = BTreeMap::new();\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/store/mod.rs", "new_path": "crates/kubelet/src/store/mod.rs", "diff": "@@ -23,7 +23,7 @@ use crate::store::oci::Client;\n/// ```rust\n/// use async_trait::async_trait;\n/// use oci_distribution::Reference;\n-/// use kubelet::store::PullPolicy;\n+/// use kubelet::container::PullPolicy;\n/// use kubelet::store::Store;\n/// use std::collections::HashMap;\n///\n@@ -33,9 +33,9 @@ use crate::store::oci::Client;\n///\n/// #[async_trait]\n/// impl Store for InMemoryStore {\n-/// async fn get(&self, image_ref: &Reference, pull_policy: Option<PullPolicy>) -> anyhow::Result<Vec<u8>> {\n+/// async fn get(&self, image_ref: &Reference, pull_policy: PullPolicy) -> anyhow::Result<Vec<u8>> {\n/// match pull_policy {\n-/// Some(PullPolicy::Never) => (),\n+/// PullPolicy::Never => (),\n/// _ => todo!(\"Implement support for pull policies\"),\n/// }\n/// match self.modules.get(image_ref) {\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/store/oci/file.rs", "new_path": "crates/kubelet/src/store/oci/file.rs", "diff": "@@ -125,7 +125,7 @@ async fn file_content_is(path: PathBuf, text: String) -> bool {\n#[cfg(test)]\nmod test {\nuse super::*;\n- use crate::store::PullPolicy;\n+ use crate::container::PullPolicy;\nuse crate::store::Store;\nuse oci_distribution::client::ImageData;\nuse std::collections::HashMap;\n@@ -137,24 +137,18 @@ mod test {\nassert_eq!(None, PullPolicy::parse(None).unwrap());\nassert_eq!(\nPullPolicy::Always,\n- PullPolicy::parse(Some(\"Always\".to_owned()))\n- .unwrap()\n- .unwrap()\n+ PullPolicy::parse(Some(\"Always\")).unwrap().unwrap()\n);\nassert_eq!(\nPullPolicy::IfNotPresent,\n- PullPolicy::parse(Some(\"IfNotPresent\".to_owned()))\n- .unwrap()\n- .unwrap()\n+ PullPolicy::parse(Some(\"IfNotPresent\")).unwrap().unwrap()\n);\nassert_eq!(\nPullPolicy::Never,\n- PullPolicy::parse(Some(\"Never\".to_owned()))\n- .unwrap()\n- .unwrap()\n+ PullPolicy::parse(Some(\"Never\")).unwrap().unwrap()\n);\nassert!(\n- PullPolicy::parse(Some(\"IfMoonMadeOfGreenCheese\".to_owned())).is_err(),\n+ PullPolicy::parse(Some(\"IfMoonMadeOfGreenCheese\")).is_err(),\n\"Expected parse failure but didn't get one\"\n);\n}\n@@ -237,7 +231,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:1.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client, &scratch_dir.path);\n- let module_bytes = store.get(&fake_ref, Some(PullPolicy::IfNotPresent)).await?;\n+ let module_bytes = store.get(&fake_ref, PullPolicy::IfNotPresent).await?;\nassert_eq!(3, module_bytes.len());\nassert_eq!(2, module_bytes[1]);\nOk(())\n@@ -249,7 +243,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:1.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client, &scratch_dir.path);\n- let module_bytes = store.get(&fake_ref, Some(PullPolicy::Always)).await?;\n+ let module_bytes = store.get(&fake_ref, PullPolicy::Always).await?;\nassert_eq!(3, module_bytes.len());\nassert_eq!(2, module_bytes[1]);\nOk(())\n@@ -261,7 +255,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:1.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client, &scratch_dir.path);\n- let module_bytes = store.get(&fake_ref, Some(PullPolicy::Never)).await;\n+ let module_bytes = store.get(&fake_ref, PullPolicy::Never).await;\nassert!(\nmodule_bytes.is_err(),\n\"expected get with pull policy Never to fail but it worked\"\n@@ -275,9 +269,9 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:1.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client, &scratch_dir.path);\n- let prime_cache = store.get(&fake_ref, Some(PullPolicy::Always)).await;\n+ let prime_cache = store.get(&fake_ref, PullPolicy::Always).await;\nassert!(prime_cache.is_ok());\n- let module_bytes = store.get(&fake_ref, Some(PullPolicy::Never)).await?;\n+ let module_bytes = store.get(&fake_ref, PullPolicy::Never).await?;\nassert_eq!(3, module_bytes.len());\nassert_eq!(2, module_bytes[1]);\nOk(())\n@@ -290,11 +284,11 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:1.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let module_bytes_orig = store.get(&fake_ref, Some(PullPolicy::IfNotPresent)).await?;\n+ let module_bytes_orig = store.get(&fake_ref, PullPolicy::IfNotPresent).await?;\nassert_eq!(3, module_bytes_orig.len());\nassert_eq!(2, module_bytes_orig[1]);\nfake_client.update(\"foo/bar:1.0\", vec![4, 5, 6, 7], \"sha256:4567\");\n- let module_bytes_after = store.get(&fake_ref, Some(PullPolicy::IfNotPresent)).await?;\n+ let module_bytes_after = store.get(&fake_ref, PullPolicy::IfNotPresent).await?;\nassert_eq!(3, module_bytes_after.len());\nassert_eq!(2, module_bytes_after[1]);\nOk(())\n@@ -307,11 +301,11 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:1.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let module_bytes_orig = store.get(&fake_ref, Some(PullPolicy::IfNotPresent)).await?;\n+ let module_bytes_orig = store.get(&fake_ref, PullPolicy::IfNotPresent).await?;\nassert_eq!(3, module_bytes_orig.len());\nassert_eq!(2, module_bytes_orig[1]);\nfake_client.update(\"foo/bar:1.0\", vec![4, 5, 6, 7], \"sha256:4567\");\n- let module_bytes_after = store.get(&fake_ref, Some(PullPolicy::Always)).await?;\n+ let module_bytes_after = store.get(&fake_ref, PullPolicy::Always).await?;\nassert_eq!(4, module_bytes_after.len());\nassert_eq!(5, module_bytes_after[1]);\nOk(())\n@@ -323,7 +317,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client, &scratch_dir.path);\n- let module_bytes = store.get(&fake_ref, Some(PullPolicy::Always)).await?;\n+ let module_bytes = store.get(&fake_ref, PullPolicy::Always).await?;\nassert_eq!(2, module_bytes.len());\nassert_eq!(3, module_bytes[1]);\nOk(())\n@@ -336,12 +330,13 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:2.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let module_bytes_orig = store.get(&fake_ref, None).await?;\n+ let policy = PullPolicy::parse_with_ref(None, Some(fake_ref.clone()))?;\n+ let module_bytes_orig = store.get(&fake_ref, policy).await?;\nassert_eq!(3, module_bytes_orig.len());\nassert_eq!(7, module_bytes_orig[1]);\nfake_client.update(\"foo/bar:2.0\", vec![8, 9], \"sha256:89\");\n// But with no policy it should *not* re-fetch a tag that's in cache\n- let module_bytes_after = store.get(&fake_ref, None).await?;\n+ let module_bytes_after = store.get(&fake_ref, policy).await?;\nassert_eq!(3, module_bytes_after.len());\nassert_eq!(7, module_bytes_after[1]);\nOk(())\n@@ -355,11 +350,12 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:latest\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let module_bytes_orig = store.get(&fake_ref, None).await?;\n+ let policy = PullPolicy::parse_with_ref(None, Some(fake_ref.clone()))?;\n+ let module_bytes_orig = store.get(&fake_ref, policy).await?;\nassert_eq!(2, module_bytes_orig.len());\nassert_eq!(4, module_bytes_orig[1]);\nfake_client.update(\"foo/bar:latest\", vec![5, 6, 7], \"sha256:567\");\n- let module_bytes_after = store.get(&fake_ref, None).await?;\n+ let module_bytes_after = store.get(&fake_ref, policy).await?;\nassert_eq!(3, module_bytes_after.len());\nassert_eq!(6, module_bytes_after[1]);\nOk(())\n@@ -371,11 +367,12 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let module_bytes_orig = store.get(&fake_ref, None).await?;\n+ let policy = PullPolicy::parse_with_ref(None, Some(fake_ref.clone()))?;\n+ let module_bytes_orig = store.get(&fake_ref, policy).await?;\nassert_eq!(2, module_bytes_orig.len());\nassert_eq!(4, module_bytes_orig[1]);\nfake_client.update(\"foo/bar\", vec![5, 6, 7], \"sha256:567\");\n- let module_bytes_after = store.get(&fake_ref, None).await?;\n+ let module_bytes_after = store.get(&fake_ref, policy).await?;\nassert_eq!(3, module_bytes_after.len());\nassert_eq!(6, module_bytes_after[1]);\nOk(())\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Full Container accessor coverage and fix tests.
350,426
09.07.2020 06:32:25
18,000
adb7f3ac15bd684e890853cf6f1d8d64856f91ee
API Suggestions.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/container/mod.rs", "new_path": "crates/kubelet/src/container/mod.rs", "diff": "@@ -28,7 +28,7 @@ pub enum PullPolicy {\nimpl PullPolicy {\n/// Get image pull policy of container applying defaults if None from:\n/// https://kubernetes.io/docs/concepts/configuration/overview/#container-images\n- pub fn parse_with_ref(policy: Option<&str>, image: Option<Reference>) -> anyhow::Result<Self> {\n+ pub fn parse_effective(policy: Option<&str>, image: Option<Reference>) -> anyhow::Result<Self> {\nmatch PullPolicy::parse(policy)? {\nSome(policy) => Ok(policy),\nNone => match image {\n@@ -100,9 +100,9 @@ impl Container {\n}\n}\n- /// Get image pull policy of container.\n- pub fn image_pull_policy(&self) -> anyhow::Result<PullPolicy> {\n- PullPolicy::parse_with_ref(self.0.image_pull_policy.as_deref(), self.image()?)\n+ /// Get effective pull policy of container.\n+ pub fn effective_pull_policy(&self) -> anyhow::Result<PullPolicy> {\n+ PullPolicy::parse_effective(self.0.image_pull_policy.as_deref(), self.image()?)\n}\n/// Get lifecycle of container.\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/store/mod.rs", "new_path": "crates/kubelet/src/store/mod.rs", "diff": "@@ -71,7 +71,7 @@ pub trait Store {\n.expect(\"Could not parse image.\")\n.expect(\"FATAL ERROR: container must have an image\");\nlet pull_policy = container\n- .image_pull_policy()\n+ .effective_pull_policy()\n.expect(\"Could not identify pull policy.\");\nasync move {\nOk((\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/store/oci/file.rs", "new_path": "crates/kubelet/src/store/oci/file.rs", "diff": "@@ -330,7 +330,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:2.0\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let policy = PullPolicy::parse_with_ref(None, Some(fake_ref.clone()))?;\n+ let policy = PullPolicy::parse_effective(None, Some(fake_ref.clone()))?;\nlet module_bytes_orig = store.get(&fake_ref, policy).await?;\nassert_eq!(3, module_bytes_orig.len());\nassert_eq!(7, module_bytes_orig[1]);\n@@ -350,7 +350,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar:latest\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let policy = PullPolicy::parse_with_ref(None, Some(fake_ref.clone()))?;\n+ let policy = PullPolicy::parse_effective(None, Some(fake_ref.clone()))?;\nlet module_bytes_orig = store.get(&fake_ref, policy).await?;\nassert_eq!(2, module_bytes_orig.len());\nassert_eq!(4, module_bytes_orig[1]);\n@@ -367,7 +367,7 @@ mod test {\nlet fake_ref = Reference::try_from(\"foo/bar\")?;\nlet scratch_dir = create_temp_dir();\nlet store = FileStore::new(fake_client.clone(), &scratch_dir.path);\n- let policy = PullPolicy::parse_with_ref(None, Some(fake_ref.clone()))?;\n+ let policy = PullPolicy::parse_effective(None, Some(fake_ref.clone()))?;\nlet module_bytes_orig = store.get(&fake_ref, policy).await?;\nassert_eq!(2, module_bytes_orig.len());\nassert_eq!(4, module_bytes_orig[1]);\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
API Suggestions.
350,426
09.07.2020 07:13:45
18,000
0bfa64d7fef19f4a7c38105daf959489556af256
Rebase Master and Fix Tests.
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "#![deny(missing_docs)]\nuse async_trait::async_trait;\n-use k8s_openapi::api::core::v1::{\n- Container as KubeContainer, ContainerStatus as KubeContainerStatus, Pod as KubePod,\n-};\n+use k8s_openapi::api::core::v1::{ContainerStatus as KubeContainerStatus, Pod as KubePod};\nuse kube::{api::DeleteParams, Api};\n+use kubelet::container::Container;\nuse kubelet::container::{Handle as ContainerHandle, Status as ContainerStatus};\nuse kubelet::handle::StopHandler;\nuse kubelet::node::Builder;\n@@ -432,24 +431,24 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nfn validate_pod_runnable(pod: &Pod) -> anyhow::Result<()> {\nfor container in pod.containers() {\n- validate_container_runnable(container)?;\n+ validate_container_runnable(&container)?;\n}\nOk(())\n}\n-fn validate_container_runnable(container: &KubeContainer) -> anyhow::Result<()> {\n+fn validate_container_runnable(container: &Container) -> anyhow::Result<()> {\nif has_args(container) {\nreturn Err(anyhow::anyhow!(\n\"Cannot run {}: spec specifies container args which are not supported on wasCC\",\n- container.name\n+ container.name()\n));\n}\nOk(())\n}\n-fn has_args(container: &KubeContainer) -> bool {\n- match &container.args {\n+fn has_args(container: &Container) -> bool {\n+ match &container.args() {\nNone => false,\nSome(vec) => !vec.is_empty(),\n}\n@@ -590,6 +589,7 @@ fn wascc_run(\n#[cfg(test)]\nmod test {\nuse super::*;\n+ use k8s_openapi::api::core::v1::Container as KubeContainer;\nuse serde_json::json;\nfn make_pod_spec(containers: Vec<KubeContainer>) -> Pod {\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Rebase Master and Fix Tests.
350,405
10.07.2020 10:30:29
-43,200
3910ce3a9162153da6f7fae0e1133dfb693b85fd
Fix kubelet exit on module failure
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -290,13 +290,19 @@ dependencies = [\n[[package]]\nname = \"addr2line\"\n-version = \"0.12.1\"\n+version = \"0.13.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"a49806b9dadc843c61e7c97e72490ad7f7220ae249012fbda9ad0609457c0543\"\n+checksum = \"1b6a2d3371669ab3ca9797670853d61402b03d0b4b9ebf33d677dfa720203072\"\ndependencies = [\n- \"gimli 0.21.0\",\n+ \"gimli 0.22.0\",\n]\n+[[package]]\n+name = \"adler\"\n+version = \"0.2.2\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"ccc9a9dd069569f212bc4330af9f17c4afb5e8ce185e83dbb14f1349dda18b10\"\n+\n[[package]]\nname = \"adler32\"\nversion = \"1.0.4\"\n@@ -417,14 +423,15 @@ dependencies = [\n[[package]]\nname = \"backtrace\"\n-version = \"0.3.48\"\n+version = \"0.3.50\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"0df2f85c8a2abbe3b7d7e748052fdd9b76a0458fdeb16ad4223f5eca78c7c130\"\n+checksum = \"46254cf2fdcdf1badb5934448c1bcbe046a56537b3987d96c51a7afc5d03f293\"\ndependencies = [\n\"addr2line\",\n\"cfg-if\",\n\"libc\",\n- \"object 0.19.0\",\n+ \"miniz_oxide 0.4.0\",\n+ \"object 0.20.0\",\n\"rustc-demangle\",\n]\n@@ -690,7 +697,15 @@ version = \"0.63.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d4425bb6c3f3d2f581c650f1a1fdd3196a975490149cf59bea9d34c3bea79eda\"\ndependencies = [\n- \"cranelift-entity\",\n+ \"cranelift-entity 0.63.0\",\n+]\n+\n+[[package]]\n+name = \"cranelift-bforest\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"cranelift-entity 0.65.0\",\n]\n[[package]]\n@@ -700,13 +715,32 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"d166b289fd30062ee6de86284750fc3fe5d037c6b864b3326ce153239b0626e1\"\ndependencies = [\n\"byteorder\",\n- \"cranelift-bforest\",\n- \"cranelift-codegen-meta\",\n- \"cranelift-codegen-shared\",\n- \"cranelift-entity\",\n+ \"cranelift-bforest 0.63.0\",\n+ \"cranelift-codegen-meta 0.63.0\",\n+ \"cranelift-codegen-shared 0.63.0\",\n+ \"cranelift-entity 0.63.0\",\n\"gimli 0.20.0\",\n\"log 0.4.8\",\n- \"regalloc\",\n+ \"regalloc 0.0.21\",\n+ \"serde\",\n+ \"smallvec\",\n+ \"target-lexicon\",\n+ \"thiserror\",\n+]\n+\n+[[package]]\n+name = \"cranelift-codegen\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"byteorder\",\n+ \"cranelift-bforest 0.65.0\",\n+ \"cranelift-codegen-meta 0.65.0\",\n+ \"cranelift-codegen-shared 0.65.0\",\n+ \"cranelift-entity 0.65.0\",\n+ \"gimli 0.21.0\",\n+ \"log 0.4.8\",\n+ \"regalloc 0.0.26\",\n\"serde\",\n\"smallvec\",\n\"target-lexicon\",\n@@ -719,8 +753,17 @@ version = \"0.63.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"02c9fb2306a36d41c5facd4bf3400bc6c157185c43a96eaaa503471c34c5144b\"\ndependencies = [\n- \"cranelift-codegen-shared\",\n- \"cranelift-entity\",\n+ \"cranelift-codegen-shared 0.63.0\",\n+ \"cranelift-entity 0.63.0\",\n+]\n+\n+[[package]]\n+name = \"cranelift-codegen-meta\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"cranelift-codegen-shared 0.65.0\",\n+ \"cranelift-entity 0.65.0\",\n]\n[[package]]\n@@ -729,6 +772,11 @@ version = \"0.63.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"44e0cfe9b1f97d9f836bca551618106c7d53b93b579029ecd38e73daa7eb689e\"\n+[[package]]\n+name = \"cranelift-codegen-shared\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+\n[[package]]\nname = \"cranelift-entity\"\nversion = \"0.63.0\"\n@@ -738,13 +786,32 @@ dependencies = [\n\"serde\",\n]\n+[[package]]\n+name = \"cranelift-entity\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"serde\",\n+]\n+\n[[package]]\nname = \"cranelift-frontend\"\nversion = \"0.63.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e45f82e3446dd1ebb8c2c2f6a6b0e6cd6cd52965c7e5f7b1b35e9a9ace31ccde\"\ndependencies = [\n- \"cranelift-codegen\",\n+ \"cranelift-codegen 0.63.0\",\n+ \"log 0.4.8\",\n+ \"smallvec\",\n+ \"target-lexicon\",\n+]\n+\n+[[package]]\n+name = \"cranelift-frontend\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"cranelift-codegen 0.65.0\",\n\"log 0.4.8\",\n\"smallvec\",\n\"target-lexicon\",\n@@ -756,7 +823,17 @@ version = \"0.63.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"488b5d481bb0996a143e55a9d1739ef425efa20d4a5e5e98c859a8573c9ead9a\"\ndependencies = [\n- \"cranelift-codegen\",\n+ \"cranelift-codegen 0.63.0\",\n+ \"raw-cpuid\",\n+ \"target-lexicon\",\n+]\n+\n+[[package]]\n+name = \"cranelift-native\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"cranelift-codegen 0.65.0\",\n\"raw-cpuid\",\n\"target-lexicon\",\n]\n@@ -767,13 +844,27 @@ version = \"0.63.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"00aa8dde71fd9fdb1958e7b0ef8f524c1560e2c6165e4ea54bc302b40551c161\"\ndependencies = [\n- \"cranelift-codegen\",\n- \"cranelift-entity\",\n- \"cranelift-frontend\",\n+ \"cranelift-codegen 0.63.0\",\n+ \"cranelift-entity 0.63.0\",\n+ \"cranelift-frontend 0.63.0\",\n\"log 0.4.8\",\n\"serde\",\n\"thiserror\",\n- \"wasmparser\",\n+ \"wasmparser 0.51.4\",\n+]\n+\n+[[package]]\n+name = \"cranelift-wasm\"\n+version = \"0.65.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"cranelift-codegen 0.65.0\",\n+ \"cranelift-entity 0.65.0\",\n+ \"cranelift-frontend 0.65.0\",\n+ \"log 0.4.8\",\n+ \"serde\",\n+ \"thiserror\",\n+ \"wasmparser 0.58.0\",\n]\n[[package]]\n@@ -1112,7 +1203,7 @@ dependencies = [\n\"cfg-if\",\n\"crc32fast\",\n\"libc\",\n- \"miniz_oxide\",\n+ \"miniz_oxide 0.3.6\",\n]\n[[package]]\n@@ -1307,6 +1398,17 @@ name = \"gimli\"\nversion = \"0.21.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"bcc8e0c9bce37868955864dbecd2b1ab2bdf967e6f28066d65aaac620444b65c\"\n+dependencies = [\n+ \"fallible-iterator\",\n+ \"indexmap\",\n+ \"stable_deref_trait\",\n+]\n+\n+[[package]]\n+name = \"gimli\"\n+version = \"0.22.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"aaf91faf136cb47367fa430cd46e37a788775e7fa104f8b4bcb3861dc389b724\"\n[[package]]\nname = \"glob\"\n@@ -1883,6 +1985,15 @@ dependencies = [\n\"adler32\",\n]\n+[[package]]\n+name = \"miniz_oxide\"\n+version = \"0.4.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"be0f75932c1f6cfae3c04000e40114adf955636e19040f9c0a2c380702aa1c7f\"\n+dependencies = [\n+ \"adler\",\n+]\n+\n[[package]]\nname = \"mio\"\nversion = \"0.6.22\"\n@@ -2040,14 +2151,19 @@ checksum = \"e5666bbb90bc4d1e5bdcb26c0afda1822d25928341e9384ab187a9b37ab69e36\"\ndependencies = [\n\"flate2\",\n\"target-lexicon\",\n- \"wasmparser\",\n+ \"wasmparser 0.51.4\",\n]\n[[package]]\nname = \"object\"\n-version = \"0.19.0\"\n+version = \"0.20.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\n-checksum = \"9cbca9424c482ee628fa549d9c812e2cd22f1180b9222c9200fdfa6eb31aecb2\"\n+checksum = \"1ab52be62400ca80aa00285d25253d7f7c437b7375c4de678f5405d3afe82ca5\"\n+dependencies = [\n+ \"crc32fast\",\n+ \"indexmap\",\n+ \"wasmparser 0.57.0\",\n+]\n[[package]]\nname = \"oci-distribution\"\n@@ -2564,6 +2680,17 @@ dependencies = [\n\"smallvec\",\n]\n+[[package]]\n+name = \"regalloc\"\n+version = \"0.0.26\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"7c03092d79e0fd610932d89ed53895a38c0dd3bcd317a0046e69940de32f1d95\"\n+dependencies = [\n+ \"log 0.4.8\",\n+ \"rustc-hash\",\n+ \"smallvec\",\n+]\n+\n[[package]]\nname = \"regex\"\nversion = \"1.3.9\"\n@@ -3465,6 +3592,38 @@ version = \"0.3.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"e987b6bf443f4b5b3b6f38704195592cca41c5bb7aedd3c3693c7081f8289860\"\n+[[package]]\n+name = \"tracing\"\n+version = \"0.1.15\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"a41f40ed0e162c911ac6fcb53ecdc8134c46905fdbbae8c50add462a538b495f\"\n+dependencies = [\n+ \"cfg-if\",\n+ \"log 0.4.8\",\n+ \"tracing-attributes\",\n+ \"tracing-core\",\n+]\n+\n+[[package]]\n+name = \"tracing-attributes\"\n+version = \"0.1.9\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"f0693bf8d6f2bf22c690fc61a9d21ac69efdbb894a17ed596b9af0f01e64b84b\"\n+dependencies = [\n+ \"proc-macro2\",\n+ \"quote\",\n+ \"syn\",\n+]\n+\n+[[package]]\n+name = \"tracing-core\"\n+version = \"0.1.10\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"0aa83a9a47081cd522c09c81b31aec2c9273424976f922ad61c053b58350b715\"\n+dependencies = [\n+ \"lazy_static\",\n+]\n+\n[[package]]\nname = \"trust-dns-proto\"\nversion = \"0.18.0-alpha.2\"\n@@ -3710,9 +3869,9 @@ dependencies = [\n\"serde\",\n\"serde_derive\",\n\"serde_json\",\n- \"wasi-common\",\n- \"wasmtime\",\n- \"wasmtime-wasi\",\n+ \"wasi-common 0.16.0\",\n+ \"wasmtime 0.16.0\",\n+ \"wasmtime-wasi 0.16.0\",\n]\n[[package]]\n@@ -3881,11 +4040,32 @@ dependencies = [\n\"libc\",\n\"log 0.4.8\",\n\"thiserror\",\n- \"wig\",\n- \"wiggle\",\n+ \"wig 0.16.0\",\n+ \"wiggle 0.16.0\",\n\"winapi 0.3.8\",\n- \"winx\",\n- \"yanix\",\n+ \"winx 0.16.0\",\n+ \"yanix 0.16.0\",\n+]\n+\n+[[package]]\n+name = \"wasi-common\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"cfg-if\",\n+ \"cpu-time\",\n+ \"filetime\",\n+ \"getrandom\",\n+ \"lazy_static\",\n+ \"libc\",\n+ \"log 0.4.8\",\n+ \"thiserror\",\n+ \"wig 0.18.0\",\n+ \"wiggle 0.18.0\",\n+ \"winapi 0.3.8\",\n+ \"winx 0.18.0\",\n+ \"yanix 0.18.0\",\n]\n[[package]]\n@@ -3894,6 +4074,7 @@ version = \"0.3.0\"\ndependencies = [\n\"anyhow\",\n\"async-trait\",\n+ \"backtrace\",\n\"chrono\",\n\"futures\",\n\"k8s-openapi\",\n@@ -3903,9 +4084,9 @@ dependencies = [\n\"oci-distribution\",\n\"tempfile\",\n\"tokio\",\n- \"wasi-common\",\n- \"wasmtime\",\n- \"wasmtime-wasi\",\n+ \"wasi-common 0.18.0\",\n+ \"wasmtime 0.18.0\",\n+ \"wasmtime-wasi 0.18.0\",\n\"wat\",\n]\n@@ -3983,6 +4164,18 @@ version = \"0.51.4\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"aeb1956b19469d1c5e63e459d29e7b5aa0f558d9f16fcef09736f8a265e6c10a\"\n+[[package]]\n+name = \"wasmparser\"\n+version = \"0.57.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"32fddd575d477c6e9702484139cf9f23dcd554b06d185ed0f56c857dd3a47aa6\"\n+\n+[[package]]\n+name = \"wasmparser\"\n+version = \"0.58.0\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"721a8d79483738d7aef6397edcf8f04cd862640b1ad5973adf5bb50fc10e86db\"\n+\n[[package]]\nname = \"wasmtime\"\nversion = \"0.16.0\"\n@@ -3997,11 +4190,35 @@ dependencies = [\n\"region\",\n\"rustc-demangle\",\n\"target-lexicon\",\n- \"wasmparser\",\n- \"wasmtime-environ\",\n- \"wasmtime-jit\",\n- \"wasmtime-profiling\",\n- \"wasmtime-runtime\",\n+ \"wasmparser 0.51.4\",\n+ \"wasmtime-environ 0.16.0\",\n+ \"wasmtime-jit 0.16.0\",\n+ \"wasmtime-profiling 0.16.0\",\n+ \"wasmtime-runtime 0.16.0\",\n+ \"wat\",\n+ \"winapi 0.3.8\",\n+]\n+\n+[[package]]\n+name = \"wasmtime\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"backtrace\",\n+ \"cfg-if\",\n+ \"lazy_static\",\n+ \"libc\",\n+ \"log 0.4.8\",\n+ \"region\",\n+ \"rustc-demangle\",\n+ \"smallvec\",\n+ \"target-lexicon\",\n+ \"wasmparser 0.58.0\",\n+ \"wasmtime-environ 0.18.0\",\n+ \"wasmtime-jit 0.18.0\",\n+ \"wasmtime-profiling 0.18.0\",\n+ \"wasmtime-runtime 0.18.0\",\n\"wat\",\n\"winapi 0.3.8\",\n]\n@@ -4018,8 +4235,23 @@ dependencies = [\n\"more-asserts\",\n\"target-lexicon\",\n\"thiserror\",\n- \"wasmparser\",\n- \"wasmtime-environ\",\n+ \"wasmparser 0.51.4\",\n+ \"wasmtime-environ 0.16.0\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-debug\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"gimli 0.21.0\",\n+ \"more-asserts\",\n+ \"object 0.20.0\",\n+ \"target-lexicon\",\n+ \"thiserror\",\n+ \"wasmparser 0.58.0\",\n+ \"wasmtime-environ 0.18.0\",\n]\n[[package]]\n@@ -4031,9 +4263,39 @@ dependencies = [\n\"anyhow\",\n\"base64 0.12.1\",\n\"bincode\",\n- \"cranelift-codegen\",\n- \"cranelift-entity\",\n- \"cranelift-wasm\",\n+ \"cranelift-codegen 0.63.0\",\n+ \"cranelift-entity 0.63.0\",\n+ \"cranelift-wasm 0.63.0\",\n+ \"directories\",\n+ \"errno\",\n+ \"file-per-thread-logger\",\n+ \"indexmap\",\n+ \"libc\",\n+ \"log 0.4.8\",\n+ \"more-asserts\",\n+ \"rayon\",\n+ \"serde\",\n+ \"sha2\",\n+ \"thiserror\",\n+ \"toml\",\n+ \"wasmparser 0.51.4\",\n+ \"winapi 0.3.8\",\n+ \"zstd\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-environ\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"base64 0.12.1\",\n+ \"bincode\",\n+ \"cfg-if\",\n+ \"cranelift-codegen 0.65.0\",\n+ \"cranelift-entity 0.65.0\",\n+ \"cranelift-frontend 0.65.0\",\n+ \"cranelift-wasm 0.65.0\",\n\"directories\",\n\"errno\",\n\"file-per-thread-logger\",\n@@ -4046,7 +4308,7 @@ dependencies = [\n\"sha2\",\n\"thiserror\",\n\"toml\",\n- \"wasmparser\",\n+ \"wasmparser 0.58.0\",\n\"winapi 0.3.8\",\n\"zstd\",\n]\n@@ -4059,25 +4321,66 @@ checksum = \"8da8f32b1cc4c133612ff78e413213e24facb52f07748fc9f3c457b20918fa1d\"\ndependencies = [\n\"anyhow\",\n\"cfg-if\",\n- \"cranelift-codegen\",\n- \"cranelift-entity\",\n- \"cranelift-frontend\",\n- \"cranelift-native\",\n- \"cranelift-wasm\",\n+ \"cranelift-codegen 0.63.0\",\n+ \"cranelift-entity 0.63.0\",\n+ \"cranelift-frontend 0.63.0\",\n+ \"cranelift-native 0.63.0\",\n+ \"cranelift-wasm 0.63.0\",\n\"gimli 0.20.0\",\n\"log 0.4.8\",\n\"more-asserts\",\n\"region\",\n\"target-lexicon\",\n\"thiserror\",\n- \"wasmparser\",\n- \"wasmtime-debug\",\n- \"wasmtime-environ\",\n- \"wasmtime-profiling\",\n- \"wasmtime-runtime\",\n+ \"wasmparser 0.51.4\",\n+ \"wasmtime-debug 0.16.0\",\n+ \"wasmtime-environ 0.16.0\",\n+ \"wasmtime-profiling 0.16.0\",\n+ \"wasmtime-runtime 0.16.0\",\n\"winapi 0.3.8\",\n]\n+[[package]]\n+name = \"wasmtime-jit\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"cfg-if\",\n+ \"cranelift-codegen 0.65.0\",\n+ \"cranelift-entity 0.65.0\",\n+ \"cranelift-frontend 0.65.0\",\n+ \"cranelift-native 0.65.0\",\n+ \"cranelift-wasm 0.65.0\",\n+ \"gimli 0.21.0\",\n+ \"log 0.4.8\",\n+ \"more-asserts\",\n+ \"object 0.20.0\",\n+ \"region\",\n+ \"target-lexicon\",\n+ \"thiserror\",\n+ \"wasmparser 0.58.0\",\n+ \"wasmtime-debug 0.18.0\",\n+ \"wasmtime-environ 0.18.0\",\n+ \"wasmtime-obj\",\n+ \"wasmtime-profiling 0.18.0\",\n+ \"wasmtime-runtime 0.18.0\",\n+ \"winapi 0.3.8\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-obj\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"more-asserts\",\n+ \"object 0.20.0\",\n+ \"target-lexicon\",\n+ \"wasmtime-debug 0.18.0\",\n+ \"wasmtime-environ 0.18.0\",\n+]\n+\n[[package]]\nname = \"wasmtime-profiling\"\nversion = \"0.16.0\"\n@@ -4093,8 +4396,26 @@ dependencies = [\n\"scroll\",\n\"serde\",\n\"target-lexicon\",\n- \"wasmtime-environ\",\n- \"wasmtime-runtime\",\n+ \"wasmtime-environ 0.16.0\",\n+ \"wasmtime-runtime 0.16.0\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-profiling\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"cfg-if\",\n+ \"gimli 0.21.0\",\n+ \"lazy_static\",\n+ \"libc\",\n+ \"object 0.20.0\",\n+ \"scroll\",\n+ \"serde\",\n+ \"target-lexicon\",\n+ \"wasmtime-environ 0.18.0\",\n+ \"wasmtime-runtime 0.18.0\",\n]\n[[package]]\n@@ -4112,7 +4433,27 @@ dependencies = [\n\"more-asserts\",\n\"region\",\n\"thiserror\",\n- \"wasmtime-environ\",\n+ \"wasmtime-environ 0.16.0\",\n+ \"winapi 0.3.8\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-runtime\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"backtrace\",\n+ \"cc\",\n+ \"cfg-if\",\n+ \"indexmap\",\n+ \"lazy_static\",\n+ \"libc\",\n+ \"log 0.4.8\",\n+ \"memoffset\",\n+ \"more-asserts\",\n+ \"region\",\n+ \"thiserror\",\n+ \"wasmtime-environ 0.18.0\",\n\"winapi 0.3.8\",\n]\n@@ -4124,11 +4465,49 @@ checksum = \"952779cb796013af3468a865e4a07added91223eac61d18d4567f8e89be29592\"\ndependencies = [\n\"anyhow\",\n\"log 0.4.8\",\n- \"wasi-common\",\n- \"wasmtime\",\n- \"wasmtime-runtime\",\n- \"wig\",\n- \"wiggle\",\n+ \"wasi-common 0.16.0\",\n+ \"wasmtime 0.16.0\",\n+ \"wasmtime-runtime 0.16.0\",\n+ \"wig 0.16.0\",\n+ \"wiggle 0.16.0\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-wasi\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"log 0.4.8\",\n+ \"wasi-common 0.18.0\",\n+ \"wasmtime 0.18.0\",\n+ \"wasmtime-runtime 0.18.0\",\n+ \"wasmtime-wiggle\",\n+ \"wig 0.18.0\",\n+ \"wiggle 0.18.0\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-wiggle\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"wasmtime 0.18.0\",\n+ \"wasmtime-wiggle-macro\",\n+ \"wiggle 0.18.0\",\n+ \"witx 0.8.5 (git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e)\",\n+]\n+\n+[[package]]\n+name = \"wasmtime-wiggle-macro\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"proc-macro2\",\n+ \"quote\",\n+ \"syn\",\n+ \"wiggle-generate 0.18.0\",\n+ \"witx 0.8.5 (git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e)\",\n]\n[[package]]\n@@ -4202,7 +4581,18 @@ dependencies = [\n\"heck\",\n\"proc-macro2\",\n\"quote\",\n- \"witx\",\n+ \"witx 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+]\n+\n+[[package]]\n+name = \"wig\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"heck\",\n+ \"proc-macro2\",\n+ \"quote\",\n+ \"witx 0.8.5 (git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e)\",\n]\n[[package]]\n@@ -4212,8 +4602,19 @@ source = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"ba87f956932fb15ce9deaca86b94cf9695ad69be12861d009b1be626d20710c5\"\ndependencies = [\n\"thiserror\",\n- \"wiggle-macro\",\n- \"witx\",\n+ \"wiggle-macro 0.16.0\",\n+ \"witx 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+]\n+\n+[[package]]\n+name = \"wiggle\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"thiserror\",\n+ \"tracing\",\n+ \"wiggle-macro 0.18.0\",\n+ \"witx 0.8.5 (git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e)\",\n]\n[[package]]\n@@ -4227,7 +4628,20 @@ dependencies = [\n\"proc-macro2\",\n\"quote\",\n\"syn\",\n- \"witx\",\n+ \"witx 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+]\n+\n+[[package]]\n+name = \"wiggle-generate\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"heck\",\n+ \"proc-macro2\",\n+ \"quote\",\n+ \"syn\",\n+ \"witx 0.8.5 (git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e)\",\n]\n[[package]]\n@@ -4238,8 +4652,19 @@ checksum = \"91be3bbcc4c3be9c3384e93230bd2785bfa8a2c510609f879c283524229124ac\"\ndependencies = [\n\"quote\",\n\"syn\",\n- \"wiggle-generate\",\n- \"witx\",\n+ \"wiggle-generate 0.16.0\",\n+ \"witx 0.8.5 (registry+https://github.com/rust-lang/crates.io-index)\",\n+]\n+\n+[[package]]\n+name = \"wiggle-macro\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"quote\",\n+ \"syn\",\n+ \"wiggle-generate 0.18.0\",\n+ \"witx 0.8.5 (git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e)\",\n]\n[[package]]\n@@ -4314,6 +4739,27 @@ dependencies = [\n\"winapi 0.3.8\",\n]\n+[[package]]\n+name = \"winx\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"bitflags\",\n+ \"cvt\",\n+ \"winapi 0.3.8\",\n+]\n+\n+[[package]]\n+name = \"witx\"\n+version = \"0.8.5\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"anyhow\",\n+ \"log 0.4.8\",\n+ \"thiserror\",\n+ \"wast 11.0.0\",\n+]\n+\n[[package]]\nname = \"witx\"\nversion = \"0.8.5\"\n@@ -4369,6 +4815,18 @@ dependencies = [\n\"log 0.4.8\",\n]\n+[[package]]\n+name = \"yanix\"\n+version = \"0.18.0\"\n+source = \"git+https://github.com/bytecodealliance/wasmtime?rev=5c35a9631cdffc00a32b416f9cb0b80f182b716e#5c35a9631cdffc00a32b416f9cb0b80f182b716e\"\n+dependencies = [\n+ \"bitflags\",\n+ \"cfg-if\",\n+ \"filetime\",\n+ \"libc\",\n+ \"log 0.4.8\",\n+]\n+\n[[package]]\nname = \"yasna\"\nversion = \"0.3.2\"\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/Cargo.toml", "new_path": "crates/wasi-provider/Cargo.toml", "diff": "@@ -21,11 +21,12 @@ rustls-tls = [\"kube/rustls-tls\", \"kubelet/rustls-tls\"]\n[dependencies]\nanyhow = \"1.0\"\nasync-trait = \"0.1\"\n+backtrace = \"0.3.49\"\nkube = { version= \"0.35\", default-features = false }\nlog = \"0.4\"\n-wasmtime = \"0.16\"\n-wasmtime-wasi = \"0.16\"\n-wasi-common = \"0.16\"\n+wasmtime = { git = \"https://github.com/bytecodealliance/wasmtime\", rev = \"5c35a9631cdffc00a32b416f9cb0b80f182b716e\" }\n+wasmtime-wasi = { git = \"https://github.com/bytecodealliance/wasmtime\", rev = \"5c35a9631cdffc00a32b416f9cb0b80f182b716e\" }\n+wasi-common = { git = \"https://github.com/bytecodealliance/wasmtime\", rev = \"5c35a9631cdffc00a32b416f9cb0b80f182b716e\" }\ntempfile = \"3.1\"\nkubelet = { path = \"../kubelet\", version = \"0.3\", default-features = false }\nwat = \"1.0\"\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/wasi_runtime.rs", "new_path": "crates/wasi-provider/src/wasi_runtime.rs", "diff": "use anyhow::bail;\nuse log::{debug, error, info};\nuse std::collections::HashMap;\n+use std::convert::TryFrom;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n@@ -160,8 +161,8 @@ impl WasiRuntime {\nlet mut ctx_builder_snapshot = ctx_builder_snapshot\n.args(&data.args)\n.envs(&data.env)\n- .stdout(output_write.try_clone()?)\n- .stderr(output_write.try_clone()?);\n+ .stdout(wasi_common::OsFile::try_from(output_write.try_clone()?)?)\n+ .stderr(wasi_common::OsFile::try_from(output_write.try_clone()?)?);\nlet mut ctx_builder_unstable = wasi_common::old::snapshot_0::WasiCtxBuilder::new();\nlet mut ctx_builder_unstable = ctx_builder_unstable\n.args(&data.args)\n@@ -193,7 +194,7 @@ impl WasiRuntime {\nlet wasi_snapshot = Wasi::new(&store, wasi_ctx_snapshot);\nlet wasi_unstable = WasiUnstable::new(&store, wasi_ctx_unstable);\n- let module = match wasmtime::Module::new(&store, &data.module_data) {\n+ let module = match wasmtime::Module::new(&engine, &data.module_data) {\n// We can't map errors here or it moves the send channel, so we\n// do it in a match\nOk(m) => m,\n@@ -248,7 +249,7 @@ impl WasiRuntime {\n}\n};\n- let instance = match wasmtime::Instance::new(&module, &imports) {\n+ let instance = match wasmtime::Instance::new(&store, &module, &imports) {\n// We can't map errors here or it moves the send channel, so we\n// do it in a match\nOk(m) => m,\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -176,6 +176,7 @@ async fn verify_wasi_node(node: Node) -> () {\nconst SIMPLE_WASI_POD: &str = \"hello-wasi\";\nconst VERBOSE_WASI_POD: &str = \"hello-world-verbose\";\n+const FAILY_POD: &str = \"faily-pod\";\nasync fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\nlet pod_name = SIMPLE_WASI_POD;\n@@ -286,6 +287,43 @@ async fn create_fancy_schmancy_wasi_pod(\nwait_for_pod(client, pod_name).await\n}\n+async fn create_faily_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\n+ let pod_name = FAILY_POD;\n+ let p = serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Pod\",\n+ \"metadata\": {\n+ \"name\": pod_name\n+ },\n+ \"spec\": {\n+ \"containers\": [\n+ {\n+ \"name\": pod_name,\n+ \"image\": \"webassembly.azurecr.io/wasmerciser:v0.1.0\",\n+ \"args\": [ \"assert_exists(file:/nope.nope.nope.txt)\" ]\n+ },\n+ ],\n+ \"tolerations\": [\n+ {\n+ \"effect\": \"NoExecute\",\n+ \"key\": \"krustlet/arch\",\n+ \"operator\": \"Equal\",\n+ \"value\": \"wasm32-wasi\"\n+ },\n+ ]\n+ }\n+ }))?;\n+\n+ // TODO: Create a testing module to write to the path to actually check that writing and reading\n+ // from a host path volume works\n+\n+ let pod = pods.create(&PostParams::default(), &p).await?;\n+\n+ assert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n+\n+ wait_for_pod(client, pod_name).await\n+}\n+\nasync fn wait_for_pod(client: kube::Client, pod_name: &str) -> anyhow::Result<()> {\nlet api = Api::namespaced(client.clone(), \"default\");\nlet inf: Informer<Pod> = Informer::new(api).params(\n@@ -382,6 +420,9 @@ async fn clean_up_wasi_test_resources() -> () {\npods.delete(VERBOSE_WASI_POD, &DeleteParams::default())\n.await\n.expect(\"Failed to delete pod\");\n+ pods.delete(FAILY_POD, &DeleteParams::default())\n+ .await\n+ .expect(\"Failed to delete pod\");\n}\nstruct WasiTestResourceCleaner {}\n@@ -440,6 +481,16 @@ async fn test_wasi_provider() -> anyhow::Result<()> {\nassert_pod_log_contains(&pods, VERBOSE_WASI_POD, r#\"Args are: [\"arg1\", \"arg2\"]\"#).await?;\n+ create_faily_pod(client.clone(), &pods).await?;\n+\n+ assert_pod_exited_with_failure(&pods, FAILY_POD).await?;\n+ assert_pod_log_contains(\n+ &pods,\n+ FAILY_POD,\n+ r#\"ERR: Failed with File /nope.nope.nope.txt was expected to exist but did not\"#,\n+ )\n+ .await?;\n+\nOk(())\n}\n@@ -501,6 +552,22 @@ async fn assert_pod_exited_successfully(pods: &Api<Pod>, pod_name: &str) -> anyh\nOk(())\n}\n+async fn assert_pod_exited_with_failure(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\n+ let pod = pods.get(pod_name).await?;\n+\n+ let state = (|| {\n+ pod.status?.container_statuses?[0]\n+ .state\n+ .as_ref()?\n+ .terminated\n+ .clone()\n+ })()\n+ .expect(\"Could not fetch terminated states\");\n+ assert_eq!(state.exit_code, 1);\n+\n+ Ok(())\n+}\n+\nasync fn assert_container_file_contains(\ncontainer_file_path: &str,\nexpected_content: &str,\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix kubelet exit on module failure (#319)
350,416
12.07.2020 00:43:58
25,200
1c1efafd2b42ed1cac78538cfc43e30753ef8d6c
Update microk8s howto docs
[ { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-microk8s.md", "new_path": "docs/howto/krustlet-on-microk8s.md", "diff": "@@ -9,6 +9,20 @@ MicroK8s and the Krustlet, on a single machine. `kubectl` is required but is ins\nas `microk8s.kubectl`. The following instructions use `microk8s.kubectl` for simplicity.\nYou may use a standlone `kubectl` if you prefer.\n+In order for the bootstrap authentication token to work, your kube-apiserver needs to have\n+the `--enable-bootstrap-token-auth`\n+(see [bootstrap-tokens](https://kubernetes.io/docs/reference/access-authn-authz/bootstrap-tokens/)).\n+To verify you have it enabled, check the process args:\n+```bash\n+$ ps -ef | grep kube-apiserver | grep \"enable-bootstrap-token-auth\"\n+```\n+If it doesn't show up and you installed using `snap` you can find the startup args in\n+`/var/snap/microk8s/current/args/kube-apiserver` and add the flag. Now you need to\n+[restart](https://microk8s.io/docs/configuring-services) the kube-apiserver with the command:\n+```bash\n+systemctl restart snap.microk8s.daemon-apiserver\n+```\n+\n## Step 1: Get a bootstrap config\nKrustlet requires a bootstrap token and config the first time it runs. Follow the guide\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Update microk8s howto docs
350,416
13.07.2020 17:17:11
25,200
f0720180fd6e81c8773e6691cde8e75e3c26aa06
Addressed incorrect usage of markdown. Addressed incorrect grammar.
[ { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-microk8s.md", "new_path": "docs/howto/krustlet-on-microk8s.md", "diff": "@@ -10,17 +10,24 @@ as `microk8s.kubectl`. The following instructions use `microk8s.kubectl` for sim\nYou may use a standlone `kubectl` if you prefer.\nIn order for the bootstrap authentication token to work, your kube-apiserver needs to have\n-the `--enable-bootstrap-token-auth`\n-(see [bootstrap-tokens](https://kubernetes.io/docs/reference/access-authn-authz/bootstrap-tokens/)).\n-To verify you have it enabled, check the process args:\n-```bash\n+the `--enable-bootstrap-token-auth` feature flag enabled.\n+See [bootstrap-tokens](https://kubernetes.io/docs/reference/access-authn-authz/bootstrap-tokens/)\n+for more information.\n+\n+To verify you have the bootstrap authentication feature enabled, check the process args:\n+\n+```console\n$ ps -ef | grep kube-apiserver | grep \"enable-bootstrap-token-auth\"\n```\n-If it doesn't show up and you installed using `snap` you can find the startup args in\n-`/var/snap/microk8s/current/args/kube-apiserver` and add the flag. Now you need to\n+\n+If it doesn't show up and you installed using `snap`, you can find the startup args in\n+`/var/snap/microk8s/current/args/kube-apiserver` and add the flag.\n+\n+Now you need to\n[restart](https://microk8s.io/docs/configuring-services) the kube-apiserver with the command:\n-```bash\n-systemctl restart snap.microk8s.daemon-apiserver\n+\n+```console\n+$ systemctl restart snap.microk8s.daemon-apiserver\n```\n## Step 1: Get a bootstrap config\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Addressed incorrect usage of markdown. Addressed incorrect grammar.
350,443
30.06.2020 21:28:39
25,200
b38566069ac7e591bc46af7a875cdfe1412b6c56
code clean up and use Result types to return errors
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -44,6 +44,8 @@ use kubelet::provider::ProviderError;\nuse kubelet::store::Store;\nuse kubelet::volume::Ref;\nuse log::{debug, error, info, trace};\n+use std::error::Error;\n+use std::fmt;\nuse tempfile::NamedTempFile;\nuse tokio::sync::watch::{self, Receiver};\nuse tokio::sync::RwLock;\n@@ -222,35 +224,24 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nlet client = kube::Client::new(self.kubeconfig.clone());\nlet volumes = Ref::volumes_from_pod(&self.volume_path, &pod, &client).await?;\nfor container in pod.containers() {\n- //switch code to here, before env var gets set\nlet mut port_assigned: i32 = 0;\n+ info!(\n+ \"The following ports are already taken: {:?}\",\n+ self.port_set.lock().unwrap()\n+ );\nif let Some(container_vec) = container.ports.as_ref() {\nfor c_port in container_vec.iter() {\nlet container_port = c_port.container_port;\nlet host_port = c_port.host_port;\n- //self.port_set.lock().unwrap().insert(30000);\nif c_port.host_port.is_none() {\n- println!(\"host port is not specified\");\nif container_port >= 0 && container_port <= 65536 {\n- //find a port that's not taken and assign it\n- port_assigned = find_available_port(&self.port_set);\n- if port_assigned == -1 {\n- error!(\"Failed to assign port {}, all ports between 30000 and 32767 are taken\", &host_port.unwrap());\n- return Err(anyhow::anyhow!(\n- \"All ports between 30000 and 32767 are taken\"\n- ));\n- }\n+ port_assigned = find_available_port(&self.port_set)?;\n}\n} else {\n- println!(\"host port is specified\");\n-\nif !self.port_set.lock().unwrap().contains(&host_port.unwrap()) {\n- //not taken, assign that port\nport_assigned = host_port.unwrap();\n- println!(\"host port is available, so assign it\");\nself.port_set.lock().unwrap().insert(port_assigned);\n} else {\n- //port is taken, error\nerror!(\n\"Failed to assign hostport {}, because it's taken\",\n&host_port.unwrap()\n@@ -263,12 +254,7 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n}\n}\n}\n- println!(\n- \"ports that are already taken: {:?}\",\n- self.port_set.lock().unwrap()\n- );\n- println!(\"new port assigned is: {}\", port_assigned);\n- //container.env\n+ debug!(\"New port assigned is: {}\", port_assigned);\nlet env = Self::env_vars(&container, &pod, &client).await;\nlet volume_bindings: Vec<VolumeBinding> =\nif let Some(volume_mounts) = container.volume_mounts().as_ref() {\n@@ -307,7 +293,6 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n});\nlet host = self.host.clone();\nlet http_result = tokio::task::spawn_blocking(move || {\n- println!(\"wascc run http\");\nwascc_run_http(\nhost,\nmodule_data,\n@@ -544,7 +529,26 @@ fn wascc_run_http(\nwascc_run(host, data, &mut caps, volumes, log_path, status_recv)\n}\n-fn find_available_port(port_set: &Arc<Mutex<HashSet<i32>>>) -> i32 {\n+#[derive(Debug)]\n+struct PortAllocationError {}\n+\n+impl PortAllocationError {\n+ fn new() -> PortAllocationError {\n+ PortAllocationError {}\n+ }\n+}\n+impl fmt::Display for PortAllocationError {\n+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n+ write!(f, \"all ports are currently in use\")\n+ }\n+}\n+impl Error for PortAllocationError {\n+ fn description(&self) -> &str {\n+ \"all ports are currently in use\"\n+ }\n+}\n+\n+fn find_available_port(port_set: &Arc<Mutex<HashSet<i32>>>) -> Result<i32, PortAllocationError> {\nlet mut range = rand::thread_rng();\nlet mut port: i32 = -1;\n@@ -557,7 +561,11 @@ fn find_available_port(port_set: &Arc<Mutex<HashSet<i32>>>) -> i32 {\nbreak;\n}\n}\n- port\n+\n+ if port == -1 {\n+ return Err(PortAllocationError::new());\n+ }\n+ Ok(port)\n}\n/// Capability describes a waSCC capability.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
code clean up and use Result types to return errors
350,443
09.07.2020 16:21:02
25,200
a008a1a6b2787ed5c7a832795efe9d4ae417c315
fixed e2e test and removed the port allocation when a pod is deleted
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -132,7 +132,7 @@ pub struct WasccProvider<S> {\nlog_path: PathBuf,\nkubeconfig: kube::Config,\nhost: Arc<Mutex<WasccHost>>,\n- port_set: Arc<Mutex<HashSet<i32>>>,\n+ port_set: Arc<Mutex<HashMap<i32, String>>>,\n}\nimpl<S: Store + Send + Sync> WasccProvider<S> {\n@@ -146,7 +146,7 @@ impl<S: Store + Send + Sync> WasccProvider<S> {\nlet host = Arc::new(Mutex::new(WasccHost::new()));\nlet log_path = config.data_dir.join(LOG_DIR_NAME);\nlet volume_path = config.data_dir.join(VOLUME_DIR);\n- let port_set = Arc::new(Mutex::new(HashSet::<i32>::new()));\n+ let port_set = Arc::new(Mutex::new(HashMap::<i32, String>::new()));\ntokio::fs::create_dir_all(&log_path).await?;\ntokio::fs::create_dir_all(&volume_path).await?;\n@@ -227,29 +227,30 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nlet mut port_assigned: i32 = 0;\ninfo!(\n\"The following ports are already taken: {:?}\",\n- self.port_set.lock().unwrap()\n+ self.port_set.lock().unwrap().keys()\n);\n+\nif let Some(container_vec) = container.ports.as_ref() {\nfor c_port in container_vec.iter() {\nlet container_port = c_port.container_port;\n- let host_port = c_port.host_port;\n- if c_port.host_port.is_none() {\n- if container_port >= 0 && container_port <= 65536 {\n- port_assigned = find_available_port(&self.port_set)?;\n- }\n- } else {\n- if !self.port_set.lock().unwrap().contains(&host_port.unwrap()) {\n- port_assigned = host_port.unwrap();\n- self.port_set.lock().unwrap().insert(port_assigned);\n+ if let Some(host_port) = c_port.host_port {\n+ if !self.port_set.lock().unwrap().contains_key(&host_port) {\n+ port_assigned = host_port;\n+ self.port_set\n+ .lock()\n+ .unwrap()\n+ .insert(port_assigned, pod.name().to_string());\n} else {\nerror!(\n\"Failed to assign hostport {}, because it's taken\",\n- &host_port.unwrap()\n+ &host_port\n);\n- return Err(anyhow::anyhow!(\n- \"Port {} is currently in use\",\n- port_assigned\n- ));\n+ return Err(anyhow::anyhow!(\"Port {} is currently in use\", &host_port));\n+ }\n+ } else {\n+ if container_port >= 0 && container_port <= 65536 {\n+ port_assigned =\n+ find_available_port(&self.port_set, pod.name().to_string())?;\n}\n}\n}\n@@ -442,6 +443,13 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n}\nasync fn delete(&self, pod: Pod) -> anyhow::Result<()> {\n+ let mut delete_key: i32 = 0;\n+ for (key, val) in self.port_set.lock().unwrap().iter() {\n+ if val == pod.name() {\n+ delete_key = *key\n+ }\n+ }\n+ self.port_set.lock().unwrap().remove(&delete_key);\nlet mut handles = self.handles.write().await;\nmatch handles.remove(&key_from_pod(&pod)) {\nSome(_) => debug!(\n@@ -548,7 +556,10 @@ impl Error for PortAllocationError {\n}\n}\n-fn find_available_port(port_set: &Arc<Mutex<HashSet<i32>>>) -> Result<i32, PortAllocationError> {\n+fn find_available_port(\n+ port_set: &Arc<Mutex<HashMap<i32, String>>>,\n+ pod_name: String,\n+) -> Result<i32, PortAllocationError> {\nlet mut range = rand::thread_rng();\nlet mut port: i32 = -1;\n@@ -556,8 +567,8 @@ fn find_available_port(port_set: &Arc<Mutex<HashSet<i32>>>) -> Result<i32, PortA\nwhile empty_port.len() < 2768 {\nport = range.gen_range(30000, 32768);\nempty_port.insert(port);\n- if !port_set.lock().unwrap().contains(&port) {\n- port_set.lock().unwrap().insert(port);\n+ if !port_set.lock().unwrap().contains_key(&port) {\n+ port_set.lock().unwrap().insert(port, pod_name);\nbreak;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -67,6 +67,12 @@ async fn test_wascc_provider() -> Result<(), Box<dyn std::error::Error>> {\n{\n\"name\": \"greet-wascc\",\n\"image\": \"webassembly.azurecr.io/greet-wascc:v0.4\",\n+ \"ports\": [\n+ {\n+ \"containerPort\": 8080,\n+ \"hostPort\": 30000\n+ }\n+ ],\n},\n],\n\"tolerations\": [\n@@ -83,7 +89,6 @@ async fn test_wascc_provider() -> Result<(), Box<dyn std::error::Error>> {\nlet pod = pods.create(&PostParams::default(), &p).await?;\nassert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n-\nlet api = Api::namespaced(client, \"default\");\nlet inf: Informer<Pod> = Informer::new(api).params(\nListParams::default()\n@@ -112,7 +117,7 @@ async fn test_wascc_provider() -> Result<(), Box<dyn std::error::Error>> {\nassert!(went_ready, \"pod never went ready\");\n// Send a request to the pod to trigger some logging\n- reqwest::get(\"http://127.0.0.1:8080\")\n+ reqwest::get(\"http://127.0.0.1:30000\")\n.await\n.expect(\"unable to perform request to test pod\");\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
fixed e2e test and removed the port allocation when a pod is deleted
350,443
14.07.2020 11:56:26
25,200
6ee9c3899ddff2edcfb1a514efba73916a538d95
added some changes suggested by code reviews
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -60,6 +60,7 @@ use std::collections::{HashMap, HashSet};\nuse std::ops::Deref;\nuse std::path::{Path, PathBuf};\nuse std::sync::{Arc, Mutex};\n+use tokio::sync::Mutex as TokioMutex;\n/// The architecture that the pod targets.\nconst TARGET_WASM32_WASCC: &str = \"wasm32-wascc\";\n@@ -132,7 +133,7 @@ pub struct WasccProvider<S> {\nlog_path: PathBuf,\nkubeconfig: kube::Config,\nhost: Arc<Mutex<WasccHost>>,\n- port_set: Arc<Mutex<HashMap<i32, String>>>,\n+ port_map: Arc<TokioMutex<HashMap<i32, String>>>,\n}\nimpl<S: Store + Send + Sync> WasccProvider<S> {\n@@ -146,7 +147,7 @@ impl<S: Store + Send + Sync> WasccProvider<S> {\nlet host = Arc::new(Mutex::new(WasccHost::new()));\nlet log_path = config.data_dir.join(LOG_DIR_NAME);\nlet volume_path = config.data_dir.join(VOLUME_DIR);\n- let port_set = Arc::new(Mutex::new(HashMap::<i32, String>::new()));\n+ let port_map = Arc::new(TokioMutex::new(HashMap::<i32, String>::new()));\ntokio::fs::create_dir_all(&log_path).await?;\ntokio::fs::create_dir_all(&volume_path).await?;\n@@ -194,7 +195,7 @@ impl<S: Store + Send + Sync> WasccProvider<S> {\nlog_path,\nkubeconfig,\nhost,\n- port_set,\n+ port_map,\n})\n}\n}\n@@ -225,21 +226,14 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nlet volumes = Ref::volumes_from_pod(&self.volume_path, &pod, &client).await?;\nfor container in pod.containers() {\nlet mut port_assigned: i32 = 0;\n- info!(\n- \"The following ports are already taken: {:?}\",\n- self.port_set.lock().unwrap().keys()\n- );\n-\nif let Some(container_vec) = container.ports.as_ref() {\nfor c_port in container_vec.iter() {\nlet container_port = c_port.container_port;\nif let Some(host_port) = c_port.host_port {\n- if !self.port_set.lock().unwrap().contains_key(&host_port) {\n+ let mut lock = self.port_map.lock().await;\n+ if !lock.contains_key(&host_port) {\nport_assigned = host_port;\n- self.port_set\n- .lock()\n- .unwrap()\n- .insert(port_assigned, pod.name().to_string());\n+ lock.insert(port_assigned, pod.name().to_string());\n} else {\nerror!(\n\"Failed to assign hostport {}, because it's taken\",\n@@ -250,12 +244,13 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n} else {\nif container_port >= 0 && container_port <= 65536 {\nport_assigned =\n- find_available_port(&self.port_set, pod.name().to_string())?;\n+ find_available_port(&self.port_map, pod.name().to_string()).await?;\n}\n}\n}\n}\ndebug!(\"New port assigned is: {}\", port_assigned);\n+\nlet env = Self::env_vars(&container, &pod, &client).await;\nlet volume_bindings: Vec<VolumeBinding> =\nif let Some(volume_mounts) = container.volume_mounts().as_ref() {\n@@ -444,12 +439,13 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nasync fn delete(&self, pod: Pod) -> anyhow::Result<()> {\nlet mut delete_key: i32 = 0;\n- for (key, val) in self.port_set.lock().unwrap().iter() {\n+ let mut lock = self.port_map.lock().await;\n+ for (key, val) in lock.iter() {\nif val == pod.name() {\ndelete_key = *key\n}\n}\n- self.port_set.lock().unwrap().remove(&delete_key);\n+ lock.remove(&delete_key);\nlet mut handles = self.handles.write().await;\nmatch handles.remove(&key_from_pod(&pod)) {\nSome(_) => debug!(\n@@ -519,7 +515,7 @@ struct VolumeBinding {\nfn wascc_run_http(\nhost: Arc<Mutex<WasccHost>>,\ndata: Vec<u8>,\n- _env: EnvVars,\n+ mut env: EnvVars,\nvolumes: Vec<VolumeBinding>,\nlog_path: &Path,\nstatus_recv: Receiver<ContainerStatus>,\n@@ -527,12 +523,11 @@ fn wascc_run_http(\n) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> {\nlet mut caps: Vec<Capability> = Vec::new();\n- let mut env_map: HashMap<String, String> = HashMap::new();\n- env_map.insert(\"PORT\".to_string(), port_assigned.to_string());\n+ env.insert(\"PORT\".to_string(), port_assigned.to_string());\ncaps.push(Capability {\nname: HTTP_CAPABILITY,\nbinding: None,\n- env: env_map, //replaced _env\n+ env,\n});\nwascc_run(host, data, &mut caps, volumes, log_path, status_recv)\n}\n@@ -556,27 +551,24 @@ impl Error for PortAllocationError {\n}\n}\n-fn find_available_port(\n- port_set: &Arc<Mutex<HashMap<i32, String>>>,\n+async fn find_available_port(\n+ port_map: &Arc<TokioMutex<HashMap<i32, String>>>,\npod_name: String,\n) -> Result<i32, PortAllocationError> {\n- let mut range = rand::thread_rng();\n- let mut port: i32 = -1;\n-\n+ let mut port: Option<i32> = None;\nlet mut empty_port: HashSet<i32> = HashSet::new();\n+ let mut lock = port_map.lock().await;\nwhile empty_port.len() < 2768 {\n- port = range.gen_range(30000, 32768);\n- empty_port.insert(port);\n- if !port_set.lock().unwrap().contains_key(&port) {\n- port_set.lock().unwrap().insert(port, pod_name);\n+ let generated_port: i32 = rand::thread_rng().gen_range(30000, 32768);\n+ port.replace(generated_port);\n+ empty_port.insert(port.unwrap());\n+\n+ if !lock.contains_key(&port.unwrap()) {\n+ lock.insert(port.unwrap(), pod_name);\nbreak;\n}\n}\n-\n- if port == -1 {\n- return Err(PortAllocationError::new());\n- }\n- Ok(port)\n+ port.ok_or(PortAllocationError::new())\n}\n/// Capability describes a waSCC capability.\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/fileserver/README.md", "new_path": "demos/wascc/fileserver/README.md", "diff": "@@ -21,6 +21,9 @@ Create the pod and configmap with `kubectl`:\n$ kubectl create -f k8s.yaml\n```\n+If the container port is specified in the yaml file, but host port is not. A random port will be assigned. Look for **New port assigned is: xxxxx\"** in the logs. Then, run **curl localhost:xxxxx** with the assigned port number.\n+To assign a specific host port, add **hostPort: xxxxx** in the yaml files in a new line under containerPort: 8080\n+\n## Building the example\nTo set up your development environment, you'll need the following tools:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/fileserver/k8s.yaml", "new_path": "demos/wascc/fileserver/k8s.yaml", "diff": "@@ -11,7 +11,6 @@ spec:\nname: fileserver-wascc\nenv:\n- name: PORT\n- value: \"8080\"\nports:\n- containerPort: 8080\nvolumeMounts:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/greet/README.md", "new_path": "demos/wascc/greet/README.md", "diff": "@@ -14,3 +14,6 @@ Create the pod and configmap with `kubectl`:\n```shell\n$ kubectl apply -f greet-wascc.yaml\n```\n+\n+If the container port is specified in the yaml file, but host port is not. A random port will be assigned. Look for **New port assigned is: xxxxx\"** in the logs. Then, run **curl localhost:xxxxx** with the assigned port number.\n+To assign a specific host port, add **hostPort: xxxxx** in the yaml files in a new line under containerPort: 8080\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/greet/greet-wascc.yaml", "new_path": "demos/wascc/greet/greet-wascc.yaml", "diff": "@@ -11,7 +11,6 @@ spec:\nname: greet\nenv:\n- name: PORT\n- value: \"8080\"\nports:\n- containerPort: 8080\nnodeSelector:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/hello-world-assemblyscript/README.md", "new_path": "demos/wascc/hello-world-assemblyscript/README.md", "diff": "@@ -16,6 +16,9 @@ Create the pod and configmap with `kubectl`:\n$ kubectl apply -f k8s.yaml\n```\n+If the container port is specified in the yaml file, but host port is not. A random port will be assigned. Look for **New port assigned is: xxxxx\"** in the logs. Then, run **curl localhost:xxxxx** with the assigned port number.\n+To assign a specific host port, add **hostPort: xxxxx** in the yaml files in a new line under containerPort: 8080\n+\n## Building from Source\nIf you want to compile the demo and inspect it, you'll need to do the following.\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/hello-world-assemblyscript/k8s.yaml", "new_path": "demos/wascc/hello-world-assemblyscript/k8s.yaml", "diff": "@@ -8,7 +8,6 @@ spec:\nimage: webassembly.azurecr.io/hello-world-wascc-assemblyscript:v0.1.0\nenv:\n- name: PORT\n- value: \"8080\"\nports:\n- containerPort: 8080\nnodeSelector:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/uppercase/README.md", "new_path": "demos/wascc/uppercase/README.md", "diff": "@@ -18,3 +18,6 @@ Create the pod and configmap with `kubectl`:\n```shell\n$ kubectl apply -f uppercase-wascc.yaml\n```\n+\n+If the container port is specified in the yaml file, but host port is not. A random port will be assigned. Look for **New port assigned is: xxxxx\"** in the logs. Then, run **curl localhost:xxxxx** with the assigned port number.\n+To assign a specific host port, add **hostPort: xxxxx** in the yaml files in a new line under containerPort: 8080\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/uppercase/uppercase-wascc.yaml", "new_path": "demos/wascc/uppercase/uppercase-wascc.yaml", "diff": "@@ -11,7 +11,6 @@ spec:\nname: uppercase\nenv:\n- name: PORT\n- value: \"8080\"\nports:\n- containerPort: 8080\nnodeSelector:\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
added some changes suggested by code reviews
350,443
14.07.2020 12:32:01
25,200
55c0d1d3d4082807d31b23e309c07b9f6238dea4
removed env from yamls
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -562,7 +562,6 @@ async fn find_available_port(\nlet generated_port: i32 = rand::thread_rng().gen_range(30000, 32768);\nport.replace(generated_port);\nempty_port.insert(port.unwrap());\n-\nif !lock.contains_key(&port.unwrap()) {\nlock.insert(port.unwrap(), pod_name);\nbreak;\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/fileserver/k8s.yaml", "new_path": "demos/wascc/fileserver/k8s.yaml", "diff": "@@ -9,8 +9,6 @@ spec:\n- image: webassembly.azurecr.io/fileserver-wascc:v0.2.0\nimagePullPolicy: Always\nname: fileserver-wascc\n- env:\n- - name: PORT\nports:\n- containerPort: 8080\nvolumeMounts:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/greet/greet-wascc.yaml", "new_path": "demos/wascc/greet/greet-wascc.yaml", "diff": "@@ -9,8 +9,6 @@ spec:\n- image: webassembly.azurecr.io/greet-wascc:v0.5\nimagePullPolicy: Always\nname: greet\n- env:\n- - name: PORT\nports:\n- containerPort: 8080\nnodeSelector:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/hello-world-assemblyscript/k8s.yaml", "new_path": "demos/wascc/hello-world-assemblyscript/k8s.yaml", "diff": "@@ -6,8 +6,6 @@ spec:\ncontainers:\n- name: hello-world-wascc-assemblyscript\nimage: webassembly.azurecr.io/hello-world-wascc-assemblyscript:v0.1.0\n- env:\n- - name: PORT\nports:\n- containerPort: 8080\nnodeSelector:\n" }, { "change_type": "MODIFY", "old_path": "demos/wascc/uppercase/uppercase-wascc.yaml", "new_path": "demos/wascc/uppercase/uppercase-wascc.yaml", "diff": "@@ -9,8 +9,6 @@ spec:\n- image: webassembly.azurecr.io/uppercase-wascc:v0.3\nimagePullPolicy: Always\nname: uppercase\n- env:\n- - name: PORT\nports:\n- containerPort: 8080\nnodeSelector:\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
removed env from yamls
350,443
14.07.2020 14:01:40
25,200
a1944a0726fac01858767b56cbe443f7698d4641
rebase wascc-provider
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -226,7 +226,7 @@ impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\nlet volumes = Ref::volumes_from_pod(&self.volume_path, &pod, &client).await?;\nfor container in pod.containers() {\nlet mut port_assigned: i32 = 0;\n- if let Some(container_vec) = container.ports.as_ref() {\n+ if let Some(container_vec) = container.ports().as_ref() {\nfor c_port in container_vec.iter() {\nlet container_port = c_port.container_port;\nif let Some(host_port) = c_port.host_port {\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
rebase wascc-provider
350,405
16.07.2020 17:49:16
-43,200
80cdd5518b732426f9d273864fcbc31fdb827493
Option to load modules from local filesystem
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/config.rs", "new_path": "crates/kubelet/src/config.rs", "diff": "@@ -53,6 +53,9 @@ pub struct Config {\npub max_pods: u16,\n/// The location of the tls bootstrapping file\npub bootstrap_file: PathBuf,\n+ /// Whether to allow modules to be loaded directly from local\n+ /// filesystem paths, as well as from registries\n+ pub allow_local_modules: bool,\n}\n/// The configuration for the Kubelet server.\n#[derive(Clone, Debug)]\n@@ -106,6 +109,8 @@ struct ConfigBuilder {\npub server_tls_cert_file: Option<PathBuf>,\n#[serde(default, rename = \"tlsPrivateKeyFile\")]\npub server_tls_private_key_file: Option<PathBuf>,\n+ #[serde(default, rename = \"allowLocalModules\")]\n+ pub allow_local_modules: Option<bool>,\n}\nstruct ConfigBuilderFallbacks {\n@@ -136,6 +141,7 @@ impl Config {\ndata_dir,\nmax_pods: DEFAULT_MAX_PODS,\nbootstrap_file: PathBuf::from(BOOTSTRAP_FILE),\n+ allow_local_modules: false,\nserver_config: ServerConfig {\naddr: match preferred_ip_family {\n// Just unwrap these because they are programmer error if they\n@@ -259,6 +265,7 @@ impl ConfigBuilder {\nhostname: opts.hostname,\ndata_dir: opts.data_dir,\nmax_pods: ok_result_of(opts.max_pods),\n+ allow_local_modules: opts.allow_local_modules,\nserver_addr: ok_result_of(opts.addr),\nserver_port: ok_result_of(opts.port),\nserver_tls_cert_file: opts.cert_file,\n@@ -293,6 +300,7 @@ impl ConfigBuilder {\nserver_port: other.server_port.or(self.server_port),\nserver_tls_cert_file: other.server_tls_cert_file.or(self.server_tls_cert_file),\nbootstrap_file: other.bootstrap_file.or(self.bootstrap_file),\n+ allow_local_modules: other.allow_local_modules.or(self.allow_local_modules),\nserver_tls_private_key_file: other\n.server_tls_private_key_file\n.or(self.server_tls_private_key_file),\n@@ -339,6 +347,7 @@ impl ConfigBuilder {\ndata_dir,\nmax_pods,\nbootstrap_file,\n+ allow_local_modules: self.allow_local_modules.unwrap_or(false),\nserver_config: ServerConfig {\ncert_file: server_tls_cert_file,\nprivate_key_file: server_tls_private_key_file,\n@@ -466,6 +475,13 @@ pub struct Opts {\ndefault_value = BOOTSTRAP_FILE\n)]\nbootstrap_file: PathBuf,\n+\n+ #[structopt(\n+ long = \"x-allow-local-modules\",\n+ env = \"KRUSTLET_ALLOW_LOCAL_MODULES\",\n+ help = \"(Experimental) Whether to allow loading modules directly from the filesystem\"\n+ )]\n+ allow_local_modules: Option<bool>,\n}\nfn default_hostname() -> anyhow::Result<String> {\n@@ -590,7 +606,8 @@ mod test {\n\"nodeName\": \"krusty-node\",\n\"tlsCertificateFile\": \"/my/secure/cert.pfx\",\n\"tlsPrivateKeyFile\": \"/the/key\",\n- \"bootstrapFile\": \"/the/bootstrap/file.txt\"\n+ \"bootstrapFile\": \"/the/bootstrap/file.txt\",\n+ \"allowLocalModules\": true\n}\"#,\n);\nlet config = config_builder.unwrap().build(fallbacks()).unwrap();\n@@ -613,6 +630,7 @@ mod test {\nassert_eq!(config.data_dir.to_string_lossy(), \"/krusty/data/dir\");\nassert_eq!(format!(\"{}\", config.node_ip), \"173.183.193.2\");\nassert_eq!(config.max_pods, 400);\n+ assert_eq!(config.allow_local_modules, true);\nassert_eq!(config.node_labels.len(), 2);\nassert_eq!(config.node_labels.get(\"label1\"), Some(&(\"val1\".to_owned())));\n}\n@@ -669,6 +687,7 @@ mod test {\nassert_eq!(config.hostname, \"fallback-hostname\");\nassert_eq!(config.data_dir.to_string_lossy(), \"/fallback/data/dir\");\nassert_eq!(format!(\"{}\", config.node_ip), \"4.4.4.4\");\n+ assert_eq!(config.allow_local_modules, false);\nassert_eq!(config.node_labels.len(), 0);\n}\n@@ -699,6 +718,7 @@ mod test {\n\"label2\": \"val2\"\n},\n\"nodeName\": \"krusty-node\",\n+ \"allowLocalModules\": true,\n\"tlsCertificateFile\": \"/my/secure/cert.pfx\",\n\"tlsPrivateKeyFile\": \"/the/key\"\n}\"#,\n@@ -716,6 +736,7 @@ mod test {\n\"label22\": \"val22\"\n},\n\"nodeName\": \"krusty-node-2\",\n+ \"allowLocalModules\": false,\n\"tlsCertificateFile\": \"/my/secure/cert-2.pfx\",\n\"tlsPrivateKeyFile\": \"/the/2nd/key\"\n}\"#,\n@@ -737,6 +758,7 @@ mod test {\nassert_eq!(config.max_pods, 30);\nassert_eq!(config.data_dir.to_string_lossy(), \"/krusty/data/dir/2\");\nassert_eq!(format!(\"{}\", config.node_ip), \"173.183.193.22\");\n+ assert_eq!(config.allow_local_modules, false);\nassert_eq!(config.node_labels.len(), 2);\nassert_eq!(\nconfig.node_labels.get(\"label21\"),\n@@ -758,6 +780,7 @@ mod test {\n\"label2\": \"val2\"\n},\n\"nodeName\": \"krusty-node\",\n+ \"allowLocalModules\": true,\n\"tlsCertificateFile\": \"/my/secure/cert.pfx\",\n\"tlsPrivateKeyFile\": \"/the/key\"\n}\"#,\n@@ -785,6 +808,7 @@ mod test {\nassert_eq!(config.hostname, \"krusty-host\");\nassert_eq!(config.data_dir.to_string_lossy(), \"/krusty/data/dir\");\nassert_eq!(format!(\"{}\", config.node_ip), \"173.183.193.2\");\n+ assert_eq!(config.allow_local_modules, true);\nassert_eq!(config.node_labels.len(), 2);\nassert_eq!(config.node_labels.get(\"label1\"), Some(&(\"val1\".to_owned())));\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "@@ -744,6 +744,7 @@ mod test {\nprivate_key_file: PathBuf::new(),\n},\nbootstrap_file: \"doesnt/matter\".into(),\n+ allow_local_modules: false,\ndata_dir: PathBuf::new(),\nnode_labels,\nmax_pods: 110,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/store/composite/mod.rs", "diff": "+//! `composite` implements building complex stores from simpler ones.\n+\n+use crate::store::PullPolicy;\n+use crate::store::Store;\n+use async_trait::async_trait;\n+use oci_distribution::Reference;\n+use std::sync::Arc;\n+\n+/// A `Store` that has additional logic to determine if it can satisfy\n+/// a particular reference. An `InterceptingStore` can be composed with\n+/// another Store to satisfy specific requests in a custom way.\n+pub trait InterceptingStore: Store {\n+ /// Whether this `InterceptingStore` can satisfy the given reference.\n+ fn intercepts(&self, image_ref: &Reference) -> bool;\n+}\n+\n+/// Provides a way to overlay an `InterceptingStore` so that the\n+/// interceptor handles the references it can, and the base store\n+/// handles all other references.\n+pub trait ComposableStore {\n+ /// Creates a `Store` identical to the implementer except that\n+ /// 'get' requests are offered to the interceptor first.\n+ fn with_override(\n+ self,\n+ interceptor: Arc<dyn InterceptingStore + Send + Sync>,\n+ ) -> Arc<dyn Store + Send + Sync>;\n+}\n+\n+impl ComposableStore for Arc<dyn Store + Send + Sync> {\n+ fn with_override(\n+ self,\n+ interceptor: Arc<dyn InterceptingStore + Send + Sync>,\n+ ) -> Arc<dyn Store + Send + Sync> {\n+ Arc::new(CompositeStore {\n+ base: self,\n+ interceptor,\n+ })\n+ }\n+}\n+\n+impl<S> ComposableStore for Arc<S>\n+where\n+ S: Store + Send + Sync + 'static,\n+{\n+ fn with_override(\n+ self,\n+ interceptor: Arc<dyn InterceptingStore + Send + Sync>,\n+ ) -> Arc<dyn Store + Send + Sync> {\n+ Arc::new(CompositeStore {\n+ base: self,\n+ interceptor,\n+ })\n+ }\n+}\n+\n+struct CompositeStore {\n+ base: Arc<dyn Store + Send + Sync>,\n+ interceptor: Arc<dyn InterceptingStore + Send + Sync>,\n+}\n+\n+#[async_trait]\n+impl Store for CompositeStore {\n+ async fn get(&self, image_ref: &Reference, pull_policy: PullPolicy) -> anyhow::Result<Vec<u8>> {\n+ if self.interceptor.intercepts(image_ref) {\n+ self.interceptor.get(image_ref, pull_policy).await\n+ } else {\n+ self.base.get(image_ref, pull_policy).await\n+ }\n+ }\n+}\n+\n+#[cfg(test)]\n+mod test {\n+ use super::*;\n+ use std::convert::TryFrom;\n+\n+ struct FakeBase {}\n+ struct FakeInterceptor {}\n+\n+ #[async_trait]\n+ impl Store for FakeBase {\n+ async fn get(\n+ &self,\n+ _image_ref: &Reference,\n+ _pull_policy: PullPolicy,\n+ ) -> anyhow::Result<Vec<u8>> {\n+ Ok(vec![11, 10, 5, 14])\n+ }\n+ }\n+\n+ #[async_trait]\n+ impl Store for FakeInterceptor {\n+ async fn get(\n+ &self,\n+ _image_ref: &Reference,\n+ _pull_policy: PullPolicy,\n+ ) -> anyhow::Result<Vec<u8>> {\n+ Ok(vec![1, 2, 3])\n+ }\n+ }\n+\n+ impl InterceptingStore for FakeInterceptor {\n+ fn intercepts(&self, image_ref: &Reference) -> bool {\n+ image_ref.whole().starts_with(\"int\")\n+ }\n+ }\n+\n+ #[tokio::test]\n+ async fn if_interceptor_matches_then_composite_store_returns_intercepting_value() {\n+ let store = Arc::new(FakeBase {}).with_override(Arc::new(FakeInterceptor {}));\n+ let result = store\n+ .get(&Reference::try_from(\"int/foo\").unwrap(), PullPolicy::Never)\n+ .await\n+ .unwrap();\n+ assert_eq!(3, result.len());\n+ assert_eq!(1, result[0]);\n+ }\n+\n+ #[tokio::test]\n+ async fn if_interceptor_does_not_match_then_composite_store_returns_base_value() {\n+ let store = Arc::new(FakeBase {}).with_override(Arc::new(FakeInterceptor {}));\n+ let result = store\n+ .get(&Reference::try_from(\"mint/foo\").unwrap(), PullPolicy::Never)\n+ .await\n+ .unwrap();\n+ assert_eq!(4, result.len());\n+ assert_eq!(11, result[0]);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/store/fs/mod.rs", "diff": "+//! `fs` implements fetching modules from the local file system.\n+\n+use crate::store::composite::InterceptingStore;\n+use crate::store::{PullPolicy, Store};\n+use async_trait::async_trait;\n+use oci_distribution::Reference;\n+use std::path::PathBuf;\n+\n+/// A `Store` which fetches modules only from the local filesystem,\n+/// not a remote registry. References must be of the form\n+/// fs/<path>, e.g. fs//wasm/mymodule.wasm or fs/./out/mymodule.wasm.\n+/// Version tags are ignored.\n+///\n+/// FileSystemStore can be composed with another Store to support hybrid retrieval -\n+/// typically a developer scenario where you want the application under\n+/// test to be your local build, but all other modules to be retrieved from\n+/// their production registries.\n+pub struct FileSystemStore {}\n+\n+#[async_trait]\n+impl Store for FileSystemStore {\n+ async fn get(\n+ &self,\n+ image_ref: &Reference,\n+ _pull_policy: PullPolicy,\n+ ) -> anyhow::Result<Vec<u8>> {\n+ let path = PathBuf::from(image_ref.repository());\n+ Ok(tokio::fs::read(&path).await?)\n+ }\n+}\n+\n+impl InterceptingStore for FileSystemStore {\n+ fn intercepts(&self, image_ref: &Reference) -> bool {\n+ image_ref.registry() == \"fs\"\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/store/mod.rs", "new_path": "crates/kubelet/src/store/mod.rs", "diff": "//! `store` contains logic around fetching and storing modules.\n+pub mod composite;\n+pub mod fs;\npub mod oci;\nuse oci_distribution::client::ImageData;\n@@ -46,7 +48,7 @@ use crate::store::oci::Client;\n/// }\n/// ```\n#[async_trait]\n-pub trait Store {\n+pub trait Store: Sync {\n/// Get a module's data given its image `Reference`.\nasync fn get(&self, image_ref: &Reference, pull_policy: PullPolicy) -> anyhow::Result<Vec<u8>>;\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "//! ```rust,no_run\n//! use kubelet::{Kubelet, config::Config};\n//! use kubelet::store::oci::FileStore;\n+//! use std::sync::Arc;\n//! use wascc_provider::WasccProvider;\n//!\n//! async fn start() {\n//! // Get a configuration for the Kubelet\n//! let kubelet_config = Config::default();\n//! let client = oci_distribution::Client::default();\n-//! let store = FileStore::new(client, &std::path::PathBuf::from(\"\"));\n+//! let store = Arc::new(FileStore::new(client, &std::path::PathBuf::from(\"\")));\n//!\n//! // Load a kubernetes configuration\n//! let kubeconfig = kube::Config::infer().await.unwrap();\n@@ -128,9 +129,9 @@ impl StopHandler for ActorHandle {\n/// TODO: In the future, we will look at loading capabilities using the \"sidecar\" metaphor\n/// from Kubernetes.\n#[derive(Clone)]\n-pub struct WasccProvider<S> {\n+pub struct WasccProvider {\nhandles: Arc<RwLock<HashMap<String, Handle<ActorHandle, LogHandleFactory>>>>,\n- store: S,\n+ store: Arc<dyn Store + Sync + Send>,\nvolume_path: PathBuf,\nlog_path: PathBuf,\nkubeconfig: kube::Config,\n@@ -138,11 +139,11 @@ pub struct WasccProvider<S> {\nport_map: Arc<TokioMutex<HashMap<i32, String>>>,\n}\n-impl<S: Store + Send + Sync> WasccProvider<S> {\n+impl WasccProvider {\n/// Returns a new wasCC provider configured to use the proper data directory\n/// (including creating it if necessary)\npub async fn new(\n- store: S,\n+ store: Arc<dyn Store + Sync + Send>,\nconfig: &kubelet::config::Config,\nkubeconfig: kube::Config,\n) -> anyhow::Result<Self> {\n@@ -328,7 +329,7 @@ struct ModuleRunContext<'a> {\n}\n#[async_trait]\n-impl<S: Store + Send + Sync> Provider for WasccProvider<S> {\n+impl Provider for WasccProvider {\nconst ARCH: &'static str = TARGET_WASM32_WASCC;\nasync fn node(&self, builder: &mut Builder) -> anyhow::Result<()> {\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/lib.rs", "new_path": "crates/wasi-provider/src/lib.rs", "diff": "//! ```rust,no_run\n//! use kubelet::{Kubelet, config::Config};\n//! use kubelet::store::oci::FileStore;\n+//! use std::sync::Arc;\n//! use wasi_provider::WasiProvider;\n//!\n//! async {\n//! // Get a configuration for the Kubelet\n//! let kubelet_config = Config::default();\n//! let client = oci_distribution::Client::default();\n-//! let store = FileStore::new(client, &std::path::PathBuf::from(\"\"));\n+//! let store = Arc::new(FileStore::new(client, &std::path::PathBuf::from(\"\")));\n//!\n//! // Load a kubernetes configuration\n//! let kubeconfig = kube::Config::infer().await.unwrap();\n@@ -59,9 +60,9 @@ const VOLUME_DIR: &str = \"volumes\";\n/// WasiProvider provides a Kubelet runtime implementation that executes WASM\n/// binaries conforming to the WASI spec\n#[derive(Clone)]\n-pub struct WasiProvider<S> {\n+pub struct WasiProvider {\nhandles: Arc<RwLock<HashMap<String, Handle<Runtime, wasi_runtime::HandleFactory>>>>,\n- store: S,\n+ store: Arc<dyn Store + Sync + Send>,\nlog_path: PathBuf,\nkubeconfig: kube::Config,\nvolume_path: PathBuf,\n@@ -72,10 +73,10 @@ struct ContainerTerminationResult {\nmessage: String,\n}\n-impl<S: Store + Send + Sync> WasiProvider<S> {\n+impl WasiProvider {\n/// Create a new wasi provider from a module store and a kubelet config\npub async fn new(\n- store: S,\n+ store: Arc<dyn Store + Sync + Send>,\nconfig: &kubelet::config::Config,\nkubeconfig: kube::Config,\n) -> anyhow::Result<Self> {\n@@ -266,7 +267,7 @@ impl<S: Store + Send + Sync> WasiProvider<S> {\n}\n#[async_trait::async_trait]\n-impl<S: Store + Send + Sync> Provider for WasiProvider<S> {\n+impl Provider for WasiProvider {\nconst ARCH: &'static str = TARGET_WASM32_WASI;\nasync fn node(&self, builder: &mut Builder) -> anyhow::Result<()> {\n" }, { "change_type": "MODIFY", "old_path": "docs/topics/configuration.md", "new_path": "docs/topics/configuration.md", "diff": "@@ -8,6 +8,10 @@ these methods to support, or may choose to bypass `kubelet`'s built-in\nconfiguration system in favour of their own. `krustlet-wascc` and\n`krustlet-wasi` use standard configuration and support all configuration methods.\n+**NOTE:** Certain flags must be handled at the provider or custom kubelet level. If you\n+are building a custom kubelet using the `kubelet` crate, please see the \"Notes to\n+kubelet implementers\" section below.\n+\n## Configuration values\n| Command line | Environment variable | Configuration file | Description |\n@@ -22,6 +26,7 @@ configuration system in favour of their own. `krustlet-wascc` and\n| -p, --port | KRUSTLET_PORT | listenerPort | The port on which the kubelet should listen. The default is 3000 |\n| --cert-file | KRUSTLET_CERT_FILE | tlsCertificateFile | The path to the TLS certificate for the kubelet. The default is `(data directory)/config/krustlet.crt` |\n| --private-key-file | KRUSTLET_PRIVATE_KEY_FILE | tlsPrivateKeyFile | The path to the private key for the TLS certificate. The default is `(data directory)/config/krustlet.key` |\n+| --x-allow-local-modules | KRUSTLET_ALLOW_LOCAL_MODULES | allowLocalModules | If true, the kubelet should recognise references prefixed with 'fs' as indicating a filesystem path rather than a registry location. This is an experimental flag for use in development scenarios where you don't want to repeatedly push your local builds to a registry; it is likely to be removed in a future version when we have a more comprehensive toolchain for local development. |\n## Node labels format\n@@ -70,3 +75,19 @@ configuration file, for example by writing `MAX_PODS=200 krustlet-wascc` or\nIf you specify node labels in multiple places, the collections are _not_\ncombined: the place with the highest precedence takes effect and all others\nare ignored.\n+\n+## Notes to kubelet implementers\n+\n+Some flags require you to support them in your provider or main code - they are\n+not implemented automatically by the kubelet core. These flags are as follows:\n+\n+* `--bootstrap-file` - should be passed to `kubelet::bootstrap` if you use the\n+ bootstrapping feature\n+* `--data-dir` - this should be used to construct the `FileStore` if you use one\n+* `--x-allow-local-modules` - if specified you should compose a `FileSystemStore`\n+ onto your normal store\n+\n+See the `krustlet-wasi.rs` file for examples of how to honour these flags.\n+\n+If you can't honour a flag value in your particular scenario, then you should\n+still check for it and return an error, rather than silently ignoring it.\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wascc.rs", "new_path": "src/krustlet-wascc.rs", "diff": "use kubelet::config::Config;\n+use kubelet::store::composite::ComposableStore;\nuse kubelet::store::oci::FileStore;\nuse kubelet::Kubelet;\n+use std::sync::Arc;\nuse wascc_provider::WasccProvider;\n#[tokio::main]\n@@ -14,12 +16,22 @@ async fn main() -> anyhow::Result<()> {\nlet kubeconfig = kubelet::bootstrap(&config, &config.bootstrap_file).await?;\n- let client = oci_distribution::Client::default();\n- let mut store_path = config.data_dir.join(\".oci\");\n- store_path.push(\"modules\");\n- let store = FileStore::new(client, &store_path);\n+ let store = make_store(&config);\nlet provider = WasccProvider::new(store, &config, kubeconfig.clone()).await?;\nlet kubelet = Kubelet::new(provider, kubeconfig, config).await?;\nkubelet.start().await\n}\n+\n+fn make_store(config: &Config) -> Arc<dyn kubelet::store::Store + Send + Sync> {\n+ let client = oci_distribution::Client::default();\n+ let mut store_path = config.data_dir.join(\".oci\");\n+ store_path.push(\"modules\");\n+ let file_store = Arc::new(FileStore::new(client, &store_path));\n+\n+ if config.allow_local_modules {\n+ file_store.with_override(Arc::new(kubelet::store::fs::FileSystemStore {}))\n+ } else {\n+ file_store\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wasi.rs", "new_path": "src/krustlet-wasi.rs", "diff": "use kubelet::config::Config;\n+use kubelet::store::composite::ComposableStore;\nuse kubelet::store::oci::FileStore;\nuse kubelet::Kubelet;\n+use std::sync::Arc;\nuse wasi_provider::WasiProvider;\n#[tokio::main]\n@@ -14,12 +16,22 @@ async fn main() -> anyhow::Result<()> {\nlet kubeconfig = kubelet::bootstrap(&config, &config.bootstrap_file).await?;\n- let client = oci_distribution::Client::default();\n- let mut store_path = config.data_dir.join(\".oci\");\n- store_path.push(\"modules\");\n- let store = FileStore::new(client, &store_path);\n+ let store = make_store(&config);\nlet provider = WasiProvider::new(store, &config, kubeconfig.clone()).await?;\nlet kubelet = Kubelet::new(provider, kubeconfig, config).await?;\nkubelet.start().await\n}\n+\n+fn make_store(config: &Config) -> Arc<dyn kubelet::store::Store + Send + Sync> {\n+ let client = oci_distribution::Client::default();\n+ let mut store_path = config.data_dir.join(\".oci\");\n+ store_path.push(\"modules\");\n+ let file_store = Arc::new(FileStore::new(client, &store_path));\n+\n+ if config.allow_local_modules {\n+ file_store.with_override(Arc::new(kubelet::store::fs::FileSystemStore {}))\n+ } else {\n+ file_store\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Option to load modules from local filesystem (#316)
350,405
17.07.2020 11:01:45
-43,200
feb3101edd9711df5964554641f075e8951e6af6
Fix reporting of init container statuses
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/container/handle.rs", "new_path": "crates/kubelet/src/container/handle.rs", "diff": "@@ -3,7 +3,7 @@ use std::io::SeekFrom;\nuse tokio::io::{AsyncRead, AsyncSeek, AsyncSeekExt};\nuse tokio::sync::watch::Receiver;\n-use crate::container::Status;\n+use crate::container::{ContainerMap, Status};\nuse crate::handle::StopHandler;\nuse crate::log::{stream, HandleFactory, Sender};\n@@ -64,3 +64,6 @@ impl<H: StopHandler, F> Handle<H, F> {\nself.handle.wait().await\n}\n}\n+\n+/// A map from containers to container handles.\n+pub type HandleMap<H, F> = ContainerMap<Handle<H, F>>;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/container/mod.rs", "new_path": "crates/kubelet/src/container/mod.rs", "diff": "use k8s_openapi::api::core::v1::Container as KubeContainer;\nuse oci_distribution::Reference;\nuse std::convert::TryInto;\n+use std::fmt::Display;\nmod handle;\nmod status;\n-pub use handle::Handle;\n+pub use handle::{Handle, HandleMap};\npub use status::Status;\n/// Specifies how the store should check for module updates\n@@ -59,6 +60,69 @@ impl PullPolicy {\n}\n}\n+/// Identifies a container by name and phase.\n+#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n+pub enum ContainerKey {\n+ /// An init container with the given name\n+ Init(String),\n+ /// An application container with the given name\n+ App(String),\n+}\n+\n+impl ContainerKey {\n+ /// Gets the container name\n+ pub fn name(&self) -> String {\n+ match self {\n+ Self::Init(name) | Self::App(name) => name.to_string(),\n+ }\n+ }\n+\n+ /// Whether the key identifies an app container\n+ pub fn is_app(&self) -> bool {\n+ matches!(self, Self::App(_))\n+ }\n+\n+ /// Whether the key identifies an init container\n+ pub fn is_init(&self) -> bool {\n+ matches!(self, Self::Init(_))\n+ }\n+}\n+\n+impl Display for ContainerKey {\n+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {\n+ self.name().fmt(formatter)\n+ }\n+}\n+\n+/// A `HashMap` where the keys are `ContainerKey`s.\n+pub type ContainerMap<V> = std::collections::HashMap<ContainerKey, V>;\n+\n+/// Provides methods for accessing `ContainerMap` elements by name.\n+pub trait ContainerMapByName<V> {\n+ /// Gets a mutable reference to the value associated with the container\n+ /// with the given name.\n+ fn get_mut_by_name(&mut self, name: String) -> Option<&mut V>;\n+ /// Whether the map contains a `ContainerKey` with the given name.\n+ fn contains_key_name(&self, name: &str) -> bool;\n+}\n+\n+impl<V> ContainerMapByName<V> for ContainerMap<V> {\n+ fn get_mut_by_name(&mut self, name: String) -> Option<&mut V> {\n+ // TODO: borrow checker objected to any of the more natural forms\n+ let app_key = ContainerKey::App(name.clone());\n+ if self.contains_key(&app_key) {\n+ self.get_mut(&app_key)\n+ } else {\n+ self.get_mut(&ContainerKey::Init(name))\n+ }\n+ }\n+\n+ fn contains_key_name(&self, name: &str) -> bool {\n+ self.contains_key(&ContainerKey::App(name.to_owned()))\n+ || self.contains_key(&ContainerKey::Init(name.to_owned()))\n+ }\n+}\n+\n/// A Kubernetes Container\n///\n/// This is a new type around the k8s_openapi Container definition\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "//! `node` contains wrappers around the Kubernetes node API, containing ways to create and update\n//! nodes operating within the cluster.\nuse crate::config::Config;\n-use crate::container::Status as ContainerStatus;\n+use crate::container::{ContainerKey, ContainerMap, Status as ContainerStatus};\nuse crate::pod::Pod;\nuse crate::pod::{Status as PodStatus, StatusMessage as PodStatusMessage};\nuse crate::provider::Provider;\n@@ -206,17 +206,8 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\ninfo!(\"Skipping eviction of DaemonSet '{}'\", pod.name());\ncontinue;\n} else if pod.is_static() {\n- let mut container_statuses = HashMap::new();\n- for container in pod.containers() {\n- container_statuses.insert(\n- container.name().to_string(),\n- ContainerStatus::Terminated {\n- timestamp: Utc::now(),\n- message: \"Evicted on node shutdown.\".to_string(),\n- failed: false,\n- },\n- );\n- }\n+ let container_statuses = all_terminated_due_to_shutdown(&pod.all_containers());\n+\nlet status = PodStatus {\nmessage: PodStatusMessage::Message(\"Evicted on node shutdown.\".to_string()),\ncontainer_statuses,\n@@ -237,6 +228,23 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\nOk(())\n}\n+fn all_terminated_due_to_shutdown(\n+ container_keys: &[ContainerKey],\n+) -> ContainerMap<ContainerStatus> {\n+ let mut container_statuses = HashMap::new();\n+ for container_key in container_keys {\n+ container_statuses.insert(\n+ container_key.clone(),\n+ ContainerStatus::Terminated {\n+ timestamp: Utc::now(),\n+ message: \"Evicted on node shutdown.\".to_string(),\n+ failed: false,\n+ },\n+ );\n+ }\n+ container_statuses\n+}\n+\ntype PodStream = std::pin::Pin<\nBox<\ndyn futures::Stream<Item = Result<kube::api::WatchEvent<KubePod>, kube::error::Error>>\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/handle.rs", "new_path": "crates/kubelet/src/pod/handle.rs", "diff": "@@ -6,7 +6,7 @@ use tokio::stream::{StreamExt, StreamMap};\nuse tokio::sync::RwLock;\nuse tokio::task::JoinHandle;\n-use crate::container::Handle as ContainerHandle;\n+use crate::container::{ContainerMapByName, HandleMap as ContainerHandleMap};\nuse crate::handle::StopHandler;\nuse crate::log::{HandleFactory, Sender};\nuse crate::pod::Pod;\n@@ -18,7 +18,7 @@ use crate::volume::Ref;\n/// statuses for the containers in the pod and can be used to stop the pod and\n/// access logs\npub struct Handle<H, F> {\n- container_handles: RwLock<HashMap<String, ContainerHandle<H, F>>>,\n+ container_handles: RwLock<ContainerHandleMap<H, F>>,\nstatus_handle: JoinHandle<()>,\npod: Pod,\n// Storage for the volume references so they don't get dropped until the runtime handle is\n@@ -33,19 +33,19 @@ impl<H: StopHandler, F> Handle<H, F> {\n/// parameter allows a caller to pass a map of volumes to keep reference to (so that they will\n/// be dropped along with the pod)\npub async fn new(\n- container_handles: HashMap<String, ContainerHandle<H, F>>,\n+ container_handles: ContainerHandleMap<H, F>,\npod: Pod,\nclient: kube::Client,\nvolumes: Option<HashMap<String, Ref>>,\ninitial_message: Option<String>,\n) -> anyhow::Result<Self> {\n- let container_names: Vec<_> = container_handles.keys().collect();\n- pod.initialise_status(&client, &container_names, initial_message)\n+ let container_keys: Vec<_> = container_handles.keys().cloned().collect();\n+ pod.initialise_status(&client, &container_keys, initial_message)\n.await;\nlet mut channel_map = StreamMap::with_capacity(container_handles.len());\n- for (name, handle) in container_handles.iter() {\n- channel_map.insert(name.clone(), handle.status());\n+ for (key, handle) in container_handles.iter() {\n+ channel_map.insert(key.clone(), handle.status());\n}\n// TODO: This does not allow for restarting single containers because we\n// move the stream map and lose the ability to insert a new channel for\n@@ -89,9 +89,8 @@ impl<H: StopHandler, F> Handle<H, F> {\nF: HandleFactory<R>,\n{\nlet mut handles = self.container_handles.write().await;\n- let handle =\n- handles\n- .get_mut(container_name)\n+ let handle = handles\n+ .get_mut_by_name(container_name.to_owned())\n.ok_or_else(|| ProviderError::ContainerNotFound {\npod_name: self.pod.name().to_owned(),\ncontainer_name: container_name.to_owned(),\n@@ -105,14 +104,14 @@ impl<H: StopHandler, F> Handle<H, F> {\npub async fn stop(&mut self) -> anyhow::Result<()> {\n{\nlet mut handles = self.container_handles.write().await;\n- for (name, handle) in handles.iter_mut() {\n- info!(\"Stopping container: {}\", name);\n+ for (key, handle) in handles.iter_mut() {\n+ info!(\"Stopping container: {}\", key);\nmatch handle.stop().await {\n- Ok(_) => debug!(\"Successfully stopped container {}\", name),\n+ Ok(_) => debug!(\"Successfully stopped container {}\", key),\n// NOTE: I am not sure what recovery or retry steps should be\n// done here, but we should definitely continue and try to stop\n// the other containers\n- Err(e) => error!(\"Error while trying to stop pod {}: {:?}\", name, e),\n+ Err(e) => error!(\"Error while trying to stop pod {}: {:?}\", key, e),\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/mod.rs", "new_path": "crates/kubelet/src/pod/mod.rs", "diff": "@@ -9,7 +9,7 @@ pub use status::{update_status, Phase, Status, StatusMessage};\nuse std::collections::HashMap;\n-use crate::container::Container;\n+use crate::container::{Container, ContainerKey, ContainerMap};\nuse chrono::{DateTime, Utc};\nuse k8s_openapi::api::core::v1::{\nContainer as KubeContainer, ContainerStatus as KubeContainerStatus, Pod as KubePod,\n@@ -123,10 +123,10 @@ impl Pod {\n}\n/// Patch the pod status using the given status information.\n- pub async fn patch_status(&self, client: kube::Client, status: Status) {\n+ pub async fn patch_status(&self, client: kube::Client, status_changes: Status) {\nlet name = self.name();\nlet api: Api<KubePod> = Api::namespaced(client, self.namespace());\n- let current_status = match api.get(name).await {\n+ let current_k8s_status = match api.get(name).await {\nOk(p) => match p.status {\nSome(s) => s,\nNone => {\n@@ -142,24 +142,37 @@ impl Pod {\n// This section figures out what the current phase of the pod should be\n// based on the container statuses\n- let current_statuses = status\n+ let statuses_to_merge = status_changes\n.container_statuses\n.into_iter()\n- .map(|s| (s.0.clone(), s.1.to_kubernetes(s.0)))\n- .collect::<HashMap<String, KubeContainerStatus>>();\n+ .map(|s| (s.0.clone(), s.1.to_kubernetes(s.0.name())))\n+ .collect::<ContainerMap<KubeContainerStatus>>();\n+ let (app_statuses_to_merge, init_statuses_to_merge): (ContainerMap<_>, ContainerMap<_>) =\n+ statuses_to_merge.into_iter().partition(|(k, _)| k.is_app());\n// Filter out any ones we are updating and then combine them all together\n- let mut container_statuses = current_status\n+ let mut app_container_statuses = current_k8s_status\n.container_statuses\n.unwrap_or_default()\n.into_iter()\n- .filter(|s| !current_statuses.contains_key(&s.name))\n+ .filter(|s| !app_statuses_to_merge.contains_key(&ContainerKey::App(s.name.clone())))\n.collect::<Vec<KubeContainerStatus>>();\n- container_statuses.extend(current_statuses.into_iter().map(|(_, v)| v));\n+ let mut init_container_statuses = current_k8s_status\n+ .init_container_statuses\n+ .unwrap_or_default()\n+ .into_iter()\n+ .filter(|s| !init_statuses_to_merge.contains_key(&ContainerKey::Init(s.name.clone())))\n+ .collect::<Vec<KubeContainerStatus>>();\n+ app_container_statuses.extend(app_statuses_to_merge.into_iter().map(|(_, v)| v));\n+ init_container_statuses.extend(init_statuses_to_merge.into_iter().map(|(_, v)| v));\n+\nlet mut num_succeeded: usize = 0;\nlet mut failed = false;\n// TODO(thomastaylor312): Add inferring a message from these container\n// statuses if there is no message passed in the Status object\n- for status in container_statuses.iter() {\n+ for status in app_container_statuses\n+ .iter()\n+ .chain(init_container_statuses.iter())\n+ {\n// Basically anything is considered running phase in kubernetes\n// unless it is explicitly exited, so don't worry about considering\n// that state. We only really need to check terminated\n@@ -173,9 +186,11 @@ impl Pod {\n}\n}\n+ // TODO: should we have more general-purpose 'container phases' model\n+ // so we don't need parallel app and init logic?\n+ let container_count = app_container_statuses.len() + init_container_statuses.len();\n// is there ever a case when we get a status that we should end up in Phase unknown?\n-\n- let phase = if num_succeeded == container_statuses.len() {\n+ let phase = if num_succeeded >= container_count {\nPhase::Succeeded\n} else if failed {\nPhase::Failed\n@@ -192,7 +207,8 @@ impl Pod {\n},\n\"status\": {\n\"phase\": phase,\n- \"containerStatuses\": container_statuses\n+ \"containerStatuses\": app_container_statuses,\n+ \"initContainerStatuses\": init_container_statuses,\n}\n}\n);\n@@ -201,7 +217,7 @@ impl Pod {\nif let Some(status_json) = map.get_mut(\"status\") {\nif let Some(status_map) = status_json.as_object_mut() {\nlet message_key = \"message\".to_owned();\n- match status.message {\n+ match status_changes.message {\nStatusMessage::LeaveUnchanged => (),\nStatusMessage::Clear => {\nstatus_map.insert(message_key, serde_json::Value::Null);\n@@ -228,28 +244,35 @@ impl Pod {\npub async fn initialise_status(\n&self,\nclient: &kube::Client,\n- container_names: &[&String],\n+ container_keys: &[ContainerKey],\ninitial_message: Option<String>,\n) {\n- let mut all_waiting_map = HashMap::new();\n- for name in container_names {\n- let waiting = crate::container::Status::Waiting {\n- timestamp: chrono::Utc::now(),\n- message: \"PodInitializing\".to_owned(),\n- };\n- all_waiting_map.insert(name.to_string(), waiting);\n- }\n+ let all_containers_waiting = Self::all_waiting(container_keys);\n+\nlet initial_status_message = match initial_message {\nSome(m) => StatusMessage::Message(m),\nNone => StatusMessage::Clear,\n};\n+\nlet all_waiting = Status {\nmessage: initial_status_message,\n- container_statuses: all_waiting_map,\n+ container_statuses: all_containers_waiting,\n};\nself.patch_status(client.clone(), all_waiting).await;\n}\n+ fn all_waiting(container_keys: &[ContainerKey]) -> ContainerMap<crate::container::Status> {\n+ let mut all_waiting_map = HashMap::new();\n+ for key in container_keys {\n+ let waiting = crate::container::Status::Waiting {\n+ timestamp: chrono::Utc::now(),\n+ message: \"PodInitializing\".to_owned(),\n+ };\n+ all_waiting_map.insert(key.clone(), waiting);\n+ }\n+ all_waiting_map\n+ }\n+\n/// Get a pod's containers\npub fn containers(&self) -> Vec<Container> {\nself.0\n@@ -274,6 +297,19 @@ impl Pod {\n.collect()\n}\n+ /// Gets all of a pod's containers (init and application)\n+ pub fn all_containers(&self) -> Vec<ContainerKey> {\n+ let app_containers = self.containers();\n+ let app_container_keys = app_containers\n+ .iter()\n+ .map(|c| ContainerKey::App(c.name().to_owned()));\n+ let init_containers = self.containers();\n+ let init_container_keys = init_containers\n+ .iter()\n+ .map(|c| ContainerKey::Init(c.name().to_owned()));\n+ app_container_keys.chain(init_container_keys).collect()\n+ }\n+\n/// Turn the Pod into the Kubernetes API version of a Pod\npub fn into_kube_pod(self) -> KubePod {\nself.0\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/status.rs", "new_path": "crates/kubelet/src/pod/status.rs", "diff": "//! Container statuses\n-use std::collections::HashMap;\n-\nuse k8s_openapi::api::core::v1::Pod;\nuse kube::{api::PatchParams, Api};\n-use crate::container::Status as ContainerStatus;\n+use crate::container::{ContainerMap, Status as ContainerStatus};\n/// Describe the status of a workload.\n#[derive(Clone, Debug, Default)]\n@@ -14,7 +12,7 @@ pub struct Status {\n/// a message from the container statuses\npub message: StatusMessage,\n/// The statuses of containers keyed off their names\n- pub container_statuses: HashMap<String, ContainerStatus>,\n+ pub container_statuses: ContainerMap<ContainerStatus>,\n}\n#[derive(Clone, Debug)]\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -35,7 +35,10 @@ use async_trait::async_trait;\nuse k8s_openapi::api::core::v1::{ContainerStatus as KubeContainerStatus, Pod as KubePod};\nuse kube::{api::DeleteParams, Api};\nuse kubelet::container::Container;\n-use kubelet::container::{Handle as ContainerHandle, Status as ContainerStatus};\n+use kubelet::container::{\n+ ContainerKey, Handle as ContainerHandle, HandleMap as ContainerHandleMap,\n+ Status as ContainerStatus,\n+};\nuse kubelet::handle::StopHandler;\nuse kubelet::node::Builder;\nuse kubelet::pod::{key_from_pod, pod_key, Handle};\n@@ -289,7 +292,7 @@ impl WasccProvider {\nOk(handle) => {\nrun_context\n.container_handles\n- .insert(container.name().to_string(), handle);\n+ .insert(ContainerKey::App(container.name().to_string()), handle);\nstatus_sender\n.broadcast(ContainerStatus::Running {\ntimestamp: chrono::Utc::now(),\n@@ -302,7 +305,7 @@ impl WasccProvider {\n// (it was never used in creating a runtime handle)\nlet mut container_statuses = HashMap::new();\ncontainer_statuses.insert(\n- container.name().to_string(),\n+ ContainerKey::App(container.name().to_string()),\nContainerStatus::Terminated {\ntimestamp: chrono::Utc::now(),\nfailed: true,\n@@ -324,8 +327,7 @@ struct ModuleRunContext<'a> {\nclient: &'a kube::Client,\nmodules: &'a mut HashMap<String, Vec<u8>>,\nvolumes: &'a HashMap<String, Ref>,\n- container_handles:\n- &'a mut HashMap<String, kubelet::container::Handle<ActorHandle, LogHandleFactory>>,\n+ container_handles: &'a mut ContainerHandleMap<ActorHandle, LogHandleFactory>,\n}\n#[async_trait]\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/lib.rs", "new_path": "crates/wasi-provider/src/lib.rs", "diff": "@@ -42,7 +42,7 @@ use futures::stream::StreamExt;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::{api::DeleteParams, Api};\nuse kubelet::container::Container;\n-use kubelet::container::Status;\n+use kubelet::container::{ContainerKey, HandleMap as ContainerHandleMap, Status};\nuse kubelet::node::Builder;\nuse kubelet::pod::{key_from_pod, pod_key, Handle, Pod};\nuse kubelet::provider::Provider;\n@@ -162,10 +162,7 @@ impl WasiProvider {\nmodules: &mut HashMap<String, Vec<u8>>,\nvolumes: &HashMap<String, Ref>,\n) -> (\n- HashMap<\n- String,\n- kubelet::container::Handle<wasi_runtime::Runtime, wasi_runtime::HandleFactory>,\n- >,\n+ ContainerHandleMap<wasi_runtime::Runtime, wasi_runtime::HandleFactory>,\nOption<anyhow::Error>,\n) {\ninfo!(\"Starting containers for pod {:?}\", pod.name());\n@@ -176,7 +173,8 @@ impl WasiProvider {\n.await;\nmatch start_result {\nOk(handle) => {\n- container_handles.insert(container.name().to_owned(), handle);\n+ container_handles\n+ .insert(ContainerKey::App(container.name().to_owned()), handle);\n}\nErr(e) => {\nreturn (container_handles, Some(e));\n@@ -216,10 +214,7 @@ impl WasiProvider {\nmodules: &mut HashMap<String, Vec<u8>>,\nvolumes: &HashMap<String, Ref>,\n) -> (\n- HashMap<\n- String,\n- kubelet::container::Handle<wasi_runtime::Runtime, wasi_runtime::HandleFactory>,\n- >,\n+ ContainerHandleMap<wasi_runtime::Runtime, wasi_runtime::HandleFactory>,\nOption<anyhow::Error>,\n) {\ninfo!(\"Running init containers for pod {:?}\", pod.name());\n@@ -231,7 +226,8 @@ impl WasiProvider {\nmatch start_result {\nOk(handle) => {\nlet mut status_receiver = handle.status(); // TODO: ugh but borrow checker\n- container_handles.insert(container.name().to_owned(), handle);\n+ container_handles\n+ .insert(ContainerKey::Init(container.name().to_owned()), handle);\nlet run_result = self\n.run_container_to_completion(&mut status_receiver, &container)\n.await;\n@@ -282,7 +278,7 @@ impl Provider for WasiProvider {\n// When the pod finishes, we update the status to Succeeded unless it\n// produces an error, in which case we mark it Failed.\n- let mut container_handles = HashMap::new();\n+ let mut container_handles = ContainerHandleMap::new();\nlet mut modules = self.store.fetch_pod_modules(&pod).await?;\nlet client = kube::Client::new(self.kubeconfig.clone());\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/expectations.rs", "diff": "+use k8s_openapi::api::core::v1::{ContainerState, ContainerStatus, Pod, PodStatus};\n+use kube::api::Api;\n+\n+pub enum ContainerStatusExpectation<'a> {\n+ InitTerminated(&'a str, &'a str),\n+ InitNotPresent(&'a str),\n+ AppTerminated(&'a str, &'a str),\n+ AppNotPresent(&'a str),\n+}\n+\n+impl ContainerStatusExpectation<'_> {\n+ fn verify_against(&self, pod_status: &PodStatus) -> anyhow::Result<()> {\n+ let container_statuses = match self {\n+ Self::InitTerminated(_, _) | Self::InitNotPresent(_) => {\n+ &pod_status.init_container_statuses\n+ }\n+ _ => &pod_status.container_statuses,\n+ };\n+\n+ match self {\n+ Self::InitTerminated(container_name, expected)\n+ | Self::AppTerminated(container_name, expected) => {\n+ Self::verify_terminated(container_statuses, container_name, expected)\n+ }\n+ Self::InitNotPresent(container_name) | Self::AppNotPresent(container_name) => {\n+ Self::verify_not_present(container_statuses, container_name)\n+ }\n+ }\n+ }\n+\n+ fn verify_terminated(\n+ actual_statuses: &Option<Vec<ContainerStatus>>,\n+ container_name: &str,\n+ expected: &str,\n+ ) -> anyhow::Result<()> {\n+ match actual_statuses {\n+ None => Err(anyhow::anyhow!(\"Expected statuses section not present\")),\n+ Some(statuses) => match statuses.iter().find(|s| s.name == container_name) {\n+ None => Err(anyhow::anyhow!(\n+ \"Expected {} present but it wasn't\",\n+ container_name\n+ )),\n+ Some(status) => match &status.state {\n+ None => Err(anyhow::anyhow!(\n+ \"Expected {} to have state but it didn't\",\n+ container_name\n+ )),\n+ Some(state) => Self::verify_terminated_state(&state, container_name, expected),\n+ },\n+ },\n+ }\n+ }\n+\n+ fn verify_terminated_state(\n+ actual_state: &ContainerState,\n+ container_name: &str,\n+ expected: &str,\n+ ) -> anyhow::Result<()> {\n+ match &actual_state.terminated {\n+ None => Err(anyhow::anyhow!(\n+ \"Expected {} terminated but was not\",\n+ container_name\n+ )),\n+ Some(term_state) => match &term_state.message {\n+ None => Err(anyhow::anyhow!(\n+ \"Expected {} termination message was not set\",\n+ container_name\n+ )),\n+ Some(message) => {\n+ if message == expected {\n+ Ok(())\n+ } else {\n+ Err(anyhow::anyhow!(\n+ \"Expected {} termination message '{}' but was '{}'\",\n+ container_name,\n+ expected,\n+ message\n+ ))\n+ }\n+ }\n+ },\n+ }\n+ }\n+\n+ fn verify_not_present(\n+ actual_statuses: &Option<Vec<ContainerStatus>>,\n+ container_name: &str,\n+ ) -> anyhow::Result<()> {\n+ match actual_statuses {\n+ None => Ok(()),\n+ Some(statuses) => match statuses.iter().find(|s| s.name == container_name) {\n+ None => Ok(()),\n+ Some(_) => Err(anyhow::anyhow!(\n+ \"Expected {} not present but it was\",\n+ container_name\n+ )),\n+ },\n+ }\n+ }\n+}\n+\n+pub async fn assert_container_statuses(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ expectations: Vec<ContainerStatusExpectation<'_>>,\n+) -> anyhow::Result<()> {\n+ let pod = pods.get(pod_name).await?;\n+\n+ let status = pod\n+ .status\n+ .ok_or(anyhow::anyhow!(\"Pod {} had no status\", pod_name))?;\n+\n+ for expectation in expectations {\n+ if let Err(e) = expectation.verify_against(&status) {\n+ assert!(\n+ false,\n+ \"Pod {} status expectation failed: {}\",\n+ pod_name,\n+ e.to_string()\n+ );\n+ }\n+ }\n+\n+ Ok(())\n+}\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -6,7 +6,9 @@ use kube::{\n};\nuse serde_json::json;\n+mod expectations;\nmod pod_builder;\n+use expectations::{assert_container_statuses, ContainerStatusExpectation};\nuse pod_builder::{wasmerciser_pod, WasmerciserContainerSpec, WasmerciserVolumeSpec};\n#[tokio::test]\n@@ -709,6 +711,19 @@ async fn test_wasi_provider() -> anyhow::Result<()> {\ncreate_pod_with_init_containers(client.clone(), &pods).await?;\nassert_pod_log_contains(&pods, INITY_WASI_POD, r#\"slats\"#).await?;\n+ assert_container_statuses(\n+ &pods,\n+ INITY_WASI_POD,\n+ vec![\n+ ContainerStatusExpectation::InitTerminated(\"init-1\", \"Module run completed\"),\n+ ContainerStatusExpectation::InitTerminated(\"init-2\", \"Module run completed\"),\n+ ContainerStatusExpectation::InitNotPresent(INITY_WASI_POD),\n+ ContainerStatusExpectation::AppNotPresent(\"init-1\"),\n+ ContainerStatusExpectation::AppNotPresent(\"init-2\"),\n+ ContainerStatusExpectation::AppTerminated(INITY_WASI_POD, \"Module run completed\"),\n+ ],\n+ )\n+ .await?;\ncreate_pod_with_failing_init_container(client.clone(), &pods).await?;\nassert_pod_exited_with_failure(&pods, FAILY_INITS_POD).await?;\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix reporting of init container statuses (#325)
350,405
24.07.2020 09:09:34
-43,200
1e74ecde502885791d0acaa8580eb61ebbb2c909
Modularise WASI integration tests
[ { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -40,7 +40,7 @@ rustls-tls = [\"kube/rustls-tls\", \"kubelet/rustls-tls\", \"wasi-provider/rustls-tls\n[dependencies]\nanyhow = \"1.0\"\n-tokio = { version = \"0.2\", features = [\"macros\", \"rt-threaded\"] }\n+tokio = { version = \"0.2\", features = [\"macros\", \"rt-threaded\", \"time\"] }\nkube = { version= \"0.35\", default-features = false }\nenv_logger = \"0.7\"\nkubelet = { path = \"./crates/kubelet\", version = \"0.3\", default-features = false, features = [\"cli\"] }\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/assert.rs", "diff": "+use futures::TryStreamExt;\n+use k8s_openapi::api::core::v1::Pod;\n+use kube::api::{Api, LogParams};\n+\n+pub async fn pod_log_equals(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ expected_log: &str,\n+) -> anyhow::Result<()> {\n+ let mut logs = pods.log_stream(pod_name, &LogParams::default()).await?;\n+\n+ while let Some(chunk) = logs.try_next().await? {\n+ assert_eq!(expected_log, String::from_utf8_lossy(&chunk));\n+ }\n+\n+ Ok(())\n+}\n+\n+pub async fn pod_log_contains(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ expected_log: &str,\n+) -> anyhow::Result<()> {\n+ let logs = pods.logs(pod_name, &LogParams::default()).await?;\n+ assert!(\n+ logs.contains(expected_log),\n+ format!(\"Expected log containing {} but got {}\", expected_log, logs)\n+ );\n+ Ok(())\n+}\n+\n+pub async fn pod_container_log_contains(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ container_name: &str,\n+ expected_log: &str,\n+) -> anyhow::Result<()> {\n+ let mut log_params = LogParams::default();\n+ log_params.container = Some(container_name.to_owned());\n+ let logs = pods.logs(pod_name, &log_params).await?;\n+ assert!(\n+ logs.contains(expected_log),\n+ format!(\"Expected log containing {} but got {}\", expected_log, logs)\n+ );\n+ Ok(())\n+}\n+\n+pub async fn pod_exited_successfully(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\n+ let pod = pods.get(pod_name).await?;\n+\n+ let state = (|| {\n+ pod.status?.container_statuses?[0]\n+ .state\n+ .as_ref()?\n+ .terminated\n+ .clone()\n+ })()\n+ .expect(\"Could not fetch terminated states\");\n+ assert_eq!(state.exit_code, 0);\n+\n+ Ok(())\n+}\n+\n+pub async fn pod_exited_with_failure(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\n+ let pod = pods.get(pod_name).await?;\n+\n+ let phase = (|| pod.status?.phase)().expect(\"Could not get pod phase\");\n+ assert_eq!(phase, \"Failed\");\n+\n+ Ok(())\n+}\n+\n+pub async fn pod_message_contains(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+ expected_message: &str,\n+) -> anyhow::Result<()> {\n+ let pod = pods.get(pod_name).await?;\n+\n+ let message = (|| pod.status?.message)().expect(\"Could not get pod message\");\n+ assert!(\n+ message.contains(expected_message),\n+ format!(\n+ \"Expected pod message containing {} but got {}\",\n+ expected_message, message\n+ )\n+ );\n+\n+ Ok(())\n+}\n+\n+pub async fn main_container_exited_with_failure(\n+ pods: &Api<Pod>,\n+ pod_name: &str,\n+) -> anyhow::Result<()> {\n+ let pod = pods.get(pod_name).await?;\n+\n+ let state = (|| {\n+ pod.status?.container_statuses?[0]\n+ .state\n+ .as_ref()?\n+ .terminated\n+ .clone()\n+ })()\n+ .expect(\"Could not fetch terminated states\");\n+ assert_eq!(state.exit_code, 1);\n+\n+ Ok(())\n+}\n+\n+pub async fn container_file_contains(\n+ pod_name: &str,\n+ pod_namespace: &str,\n+ container_file_path: &str,\n+ expected_content: &str,\n+ file_error: &str,\n+) -> anyhow::Result<()> {\n+ let pod_dir_name = format!(\"{}-{}\", pod_name, pod_namespace);\n+ let file_path_base = dirs::home_dir()\n+ .expect(\"home dir does not exist\")\n+ .join(\".krustlet/volumes\")\n+ .join(pod_dir_name);\n+ let container_file_bytes = tokio::fs::read(file_path_base.join(container_file_path))\n+ .await\n+ .expect(file_error);\n+ assert_eq!(\n+ expected_content.to_owned().into_bytes(),\n+ container_file_bytes\n+ );\n+ Ok(())\n+}\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "-use futures::{StreamExt, TryStreamExt};\n-use k8s_openapi::api::core::v1::{ConfigMap, Node, Pod, Secret, Taint};\n-use kube::{\n- api::{Api, DeleteParams, ListParams, LogParams, PostParams, WatchEvent},\n- runtime::Informer,\n-};\n+use k8s_openapi::api::core::v1::{Node, Pod, Taint};\n+use kube::api::{Api, DeleteParams, LogParams, PostParams};\nuse serde_json::json;\n+mod assert;\nmod expectations;\nmod pod_builder;\n+mod pod_setup;\n+mod test_resource_manager;\nuse expectations::{assert_container_statuses, ContainerStatusExpectation};\nuse pod_builder::{wasmerciser_pod, WasmerciserContainerSpec, WasmerciserVolumeSpec};\n+use pod_setup::{wait_for_pod_complete, wait_for_pod_ready, OnFailure};\n+use test_resource_manager::{TestResource, TestResourceManager, TestResourceSpec};\n#[tokio::test]\nasync fn test_wascc_provider() -> Result<(), Box<dyn std::error::Error>> {\n@@ -89,37 +90,6 @@ async fn verify_wascc_node(node: Node) -> () {\n);\n}\n-async fn wait_for_pod_ready(client: kube::Client, pod_name: &str) -> anyhow::Result<()> {\n- let api = Api::namespaced(client, \"default\");\n- let inf: Informer<Pod> = Informer::new(api).params(\n- ListParams::default()\n- .fields(&format!(\"metadata.name={}\", pod_name))\n- .timeout(30),\n- );\n-\n- let mut watcher = inf.poll().await?.boxed();\n- let mut went_ready = false;\n- while let Some(event) = watcher.try_next().await? {\n- match event {\n- WatchEvent::Modified(o) => {\n- let phase = o.status.unwrap().phase.unwrap();\n- if phase == \"Running\" {\n- went_ready = true;\n- break;\n- }\n- }\n- WatchEvent::Error(e) => {\n- panic!(\"WatchEvent error: {:?}\", e);\n- }\n- _ => {}\n- }\n- }\n-\n- assert!(went_ready, \"pod never went ready\");\n-\n- Ok(())\n-}\n-\nasync fn create_wascc_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\nlet p = serde_json::from_value(json!({\n\"apiVersion\": \"v1\",\n@@ -155,7 +125,7 @@ async fn create_wascc_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resu\nassert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n- wait_for_pod_ready(client, \"greet-wascc\").await?;\n+ wait_for_pod_ready(client, \"greet-wascc\", \"default\").await?;\nOk(())\n}\n@@ -235,7 +205,11 @@ const LOGGY_POD: &str = \"loggy-pod\";\nconst INITY_WASI_POD: &str = \"hello-wasi-with-inits\";\nconst FAILY_INITS_POD: &str = \"faily-inits-pod\";\n-async fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\n+async fn create_wasi_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n+) -> anyhow::Result<()> {\nlet pod_name = SIMPLE_WASI_POD;\n// Create a temp directory to use for the host path\nlet tempdir = tempfile::tempdir()?;\n@@ -274,6 +248,9 @@ async fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resul\n\"value\": \"wasm32-wasi\"\n},\n],\n+ \"nodeSelector\": {\n+ \"kubernetes.io/arch\": \"wasm32-wasi\"\n+ },\n\"volumes\": [\n{\n\"name\": \"secret-test\",\n@@ -297,19 +274,24 @@ async fn create_wasi_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resul\n}\n}))?;\n- // TODO: Create a testing module to write to the path to actually check that writing and reading\n- // from a host path volume works\n-\nlet pod = pods.create(&PostParams::default(), &p).await?;\n+ resource_manager.push(TestResource::Pod(pod_name.to_owned()));\nassert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n- wait_for_pod_complete(client, pod_name, OnFailure::Panic).await\n+ wait_for_pod_complete(\n+ client,\n+ pod_name,\n+ resource_manager.namespace(),\n+ OnFailure::Panic,\n+ )\n+ .await\n}\nasync fn create_fancy_schmancy_wasi_pod(\nclient: kube::Client,\npods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n) -> anyhow::Result<()> {\nlet pod_name = VERBOSE_WASI_POD;\nlet p = serde_json::from_value(json!({\n@@ -334,17 +316,31 @@ async fn create_fancy_schmancy_wasi_pod(\n\"value\": \"wasm32-wasi\"\n},\n],\n+ \"nodeSelector\": {\n+ \"kubernetes.io/arch\": \"wasm32-wasi\"\n+ }\n}\n}))?;\nlet pod = pods.create(&PostParams::default(), &p).await?;\n+ resource_manager.push(TestResource::Pod(pod_name.to_owned()));\nassert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n- wait_for_pod_complete(client, pod_name, OnFailure::Panic).await\n+ wait_for_pod_complete(\n+ client,\n+ pod_name,\n+ resource_manager.namespace(),\n+ OnFailure::Panic,\n+ )\n+ .await\n}\n-async fn create_loggy_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\n+async fn create_loggy_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n+) -> anyhow::Result<()> {\nlet pod_name = LOGGY_POD;\nlet containers = vec![\n@@ -366,11 +362,16 @@ async fn create_loggy_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resu\ncontainers,\nvec![],\nOnFailure::Panic,\n+ resource_manager,\n)\n.await\n}\n-async fn create_faily_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Result<()> {\n+async fn create_faily_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n+) -> anyhow::Result<()> {\nlet pod_name = FAILY_POD;\nlet containers = vec![WasmerciserContainerSpec {\n@@ -386,6 +387,7 @@ async fn create_faily_pod(client: kube::Client, pods: &Api<Pod>) -> anyhow::Resu\ncontainers,\nvec![],\nOnFailure::Accept,\n+ resource_manager,\n)\n.await\n}\n@@ -398,19 +400,22 @@ async fn wasmercise_wasi(\ncontainers: Vec<WasmerciserContainerSpec>,\ntest_volumes: Vec<WasmerciserVolumeSpec>,\non_failure: OnFailure,\n+ resource_manager: &mut TestResourceManager,\n) -> anyhow::Result<()> {\nlet p = wasmerciser_pod(pod_name, inits, containers, test_volumes, \"wasm32-wasi\")?;\nlet pod = pods.create(&PostParams::default(), &p.pod).await?;\n+ resource_manager.push(TestResource::Pod(pod_name.to_owned()));\nassert_eq!(pod.status.unwrap().phase.unwrap(), \"Pending\");\n- wait_for_pod_complete(client, pod_name, on_failure).await\n+ wait_for_pod_complete(client, pod_name, resource_manager.namespace(), on_failure).await\n}\nasync fn create_pod_with_init_containers(\nclient: kube::Client,\npods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n) -> anyhow::Result<()> {\nlet pod_name = INITY_WASI_POD;\n@@ -449,6 +454,7 @@ async fn create_pod_with_init_containers(\ncontainers,\nvolumes,\nOnFailure::Panic,\n+ resource_manager,\n)\n.await\n}\n@@ -456,6 +462,7 @@ async fn create_pod_with_init_containers(\nasync fn create_pod_with_failing_init_container(\nclient: kube::Client,\npods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n) -> anyhow::Result<()> {\nlet pod_name = FAILY_INITS_POD;\n@@ -483,234 +490,117 @@ async fn create_pod_with_failing_init_container(\ncontainers,\nvec![],\nOnFailure::Accept,\n+ resource_manager,\n)\n.await\n}\n-#[derive(PartialEq)]\n-enum OnFailure {\n- Accept,\n- Panic,\n-}\n-\n-async fn wait_for_pod_complete(\n- client: kube::Client,\n- pod_name: &str,\n- on_failure: OnFailure,\n-) -> anyhow::Result<()> {\n- let api = Api::namespaced(client.clone(), \"default\");\n- let inf: Informer<Pod> = Informer::new(api).params(\n- ListParams::default()\n- .fields(&format!(\"metadata.name={}\", pod_name))\n- .timeout(30),\n- );\n-\n- let mut watcher = inf.poll().await?.boxed();\n- let mut went_ready = false;\n- while let Some(event) = watcher.try_next().await? {\n- match event {\n- WatchEvent::Modified(o) => {\n- let phase = o.status.unwrap().phase.unwrap();\n- if phase == \"Failed\" && on_failure == OnFailure::Accept {\n- return Ok(());\n- }\n- if phase == \"Running\" {\n- went_ready = true;\n- }\n- if phase == \"Succeeded\" && !went_ready {\n- panic!(\n- \"Pod {} reached completed phase before receiving Running phase\",\n- pod_name\n- );\n- } else if phase == \"Succeeded\" {\n- break;\n- }\n- }\n- WatchEvent::Error(e) => {\n- panic!(\"WatchEvent error: {:?}\", e);\n- }\n- _ => {}\n- }\n- }\n-\n- assert!(went_ready, format!(\"pod {} never went ready\", pod_name));\n-\n- Ok(())\n-}\n-\n-async fn set_up_wasi_test_environment(client: kube::Client) -> anyhow::Result<()> {\n- let secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\n- secrets\n- .create(\n- &PostParams::default(),\n- &serde_json::from_value(json!({\n- \"apiVersion\": \"v1\",\n- \"kind\": \"Secret\",\n- \"metadata\": {\n- \"name\": \"hello-wasi-secret\"\n- },\n- \"stringData\": {\n- \"myval\": \"a cool secret\"\n- }\n- }))?,\n- )\n- .await?;\n-\n- let config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), \"default\");\n- config_maps\n- .create(\n- &PostParams::default(),\n- &serde_json::from_value(json!({\n- \"apiVersion\": \"v1\",\n- \"kind\": \"ConfigMap\",\n- \"metadata\": {\n- \"name\": \"hello-wasi-configmap\"\n- },\n- \"data\": {\n- \"myval\": \"a cool configmap\"\n- }\n- }))?,\n- )\n- .await?;\n-\n- Ok(())\n-}\n-\n-async fn clean_up_wasi_test_resources() -> anyhow::Result<()> {\n- let client = kube::Client::try_default()\n- .await\n- .expect(\"Failed to create client\");\n-\n- let secrets: Api<Secret> = Api::namespaced(client.clone(), \"default\");\n- let config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), \"default\");\n- let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\n-\n- let cleanup_errors: Vec<_> = vec![\n- secrets\n- .delete(\"hello-wasi-secret\", &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"secret hello-wasi-secret ({})\", e)),\n- config_maps\n- .delete(\"hello-wasi-configmap\", &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"configmap hello-wasi-configmap ({})\", e)),\n- pods.delete(SIMPLE_WASI_POD, &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"pod {} ({})\", SIMPLE_WASI_POD, e)),\n- pods.delete(VERBOSE_WASI_POD, &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"pod {} ({})\", VERBOSE_WASI_POD, e)),\n- pods.delete(FAILY_POD, &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"pod {} ({})\", FAILY_POD, e)),\n- pods.delete(LOGGY_POD, &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"pod {} ({})\", LOGGY_POD, e)),\n- pods.delete(INITY_WASI_POD, &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"pod {} ({})\", INITY_WASI_POD, e)),\n- pods.delete(FAILY_INITS_POD, &DeleteParams::default())\n- .await\n- .err()\n- .map(|e| format!(\"pod {} ({})\", FAILY_INITS_POD, e)),\n- ]\n- .iter()\n- .filter(|e| e.is_some())\n- .map(|e| e.as_ref().unwrap().to_string())\n- .filter(|s| !s.contains(r#\"reason: \"NotFound\"\"#))\n- .collect();\n-\n- if cleanup_errors.is_empty() {\n- Ok(())\n- } else {\n- let cleanup_failure_text = format!(\n- \"Error(s) cleaning up resources: {}\",\n- cleanup_errors.join(\", \")\n- );\n- Err(anyhow::anyhow!(cleanup_failure_text))\n- }\n-}\n-\n-struct WasiTestResourceCleaner {}\n-\n-impl Drop for WasiTestResourceCleaner {\n- fn drop(&mut self) {\n- let t = std::thread::spawn(move || {\n- let mut rt =\n- tokio::runtime::Runtime::new().expect(\"Failed to create Tokio runtime for cleanup\");\n- rt.block_on(clean_up_wasi_test_resources())\n- });\n-\n- let thread_result = t.join();\n- let cleanup_result = thread_result.expect(\"Failed to clean up WASI test resources\");\n- cleanup_result.unwrap()\n- }\n+async fn set_up_test(\n+ test_ns: &str,\n+) -> anyhow::Result<(kube::Client, Api<Pod>, TestResourceManager)> {\n+ let client = kube::Client::try_default().await?;\n+ let pods: Api<Pod> = Api::namespaced(client.clone(), test_ns);\n+ let resource_manager = TestResourceManager::initialise(test_ns, client.clone()).await?;\n+ Ok((client, pods, resource_manager))\n}\n#[tokio::test]\n-async fn test_wasi_provider() -> anyhow::Result<()> {\n+async fn test_wasi_node_should_verify() -> anyhow::Result<()> {\nlet client = kube::Client::try_default().await?;\n-\nlet nodes: Api<Node> = Api::all(client);\n-\nlet node = nodes.get(\"krustlet-wasi\").await?;\nverify_wasi_node(node).await;\n- let client: kube::Client = nodes.into();\n-\n- set_up_wasi_test_environment(client.clone()).await?;\n-\n- let _cleaner = WasiTestResourceCleaner {};\n+ Ok(())\n+}\n- let pods: Api<Pod> = Api::namespaced(client.clone(), \"default\");\n+#[tokio::test]\n+async fn test_pod_logs_and_mounts() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-pod-logs-and-mounts\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ resource_manager\n+ .set_up_resources(vec![\n+ TestResourceSpec::secret(\"hello-wasi-secret\", \"myval\", \"a cool secret\"),\n+ TestResourceSpec::config_map(\"hello-wasi-configmap\", \"myval\", \"a cool configmap\"),\n+ ])\n+ .await?;\n- create_wasi_pod(client.clone(), &pods).await?;\n+ create_wasi_pod(client.clone(), &pods, &mut resource_manager).await?;\n- assert_pod_log_equals(&pods, SIMPLE_WASI_POD, \"Hello, world!\\n\").await?;\n+ assert::pod_log_equals(&pods, SIMPLE_WASI_POD, \"Hello, world!\\n\").await?;\n- assert_pod_exited_successfully(&pods, SIMPLE_WASI_POD).await?;\n+ assert::pod_exited_successfully(&pods, SIMPLE_WASI_POD).await?;\n- // TODO: Create a module that actually reads from a directory and outputs to logs\n- assert_container_file_contains(\n+ assert::container_file_contains(\n+ SIMPLE_WASI_POD,\n+ resource_manager.namespace(),\n\"secret-test/myval\",\n\"a cool secret\",\n\"unable to open secret file\",\n)\n.await?;\n- assert_container_file_contains(\n+ assert::container_file_contains(\n+ SIMPLE_WASI_POD,\n+ resource_manager.namespace(),\n\"configmap-test/myval\",\n\"a cool configmap\",\n\"unable to open configmap file\",\n)\n.await?;\n- create_fancy_schmancy_wasi_pod(client.clone(), &pods).await?;\n+ Ok(())\n+}\n+\n+#[tokio::test]\n+async fn test_container_args() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-container-args\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ create_fancy_schmancy_wasi_pod(client.clone(), &pods, &mut resource_manager).await?;\n+\n+ assert::pod_log_contains(&pods, VERBOSE_WASI_POD, r#\"Args are: [\"arg1\", \"arg2\"]\"#).await?;\n+\n+ Ok(())\n+}\n+\n+#[tokio::test]\n+async fn test_container_logging() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-container-logging\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ create_loggy_pod(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::pod_container_log_contains(&pods, LOGGY_POD, \"floofycat\", r#\"slats\"#).await?;\n+ assert::pod_container_log_contains(&pods, LOGGY_POD, \"neatcat\", r#\"kiki\"#).await?;\n+\n+ Ok(())\n+}\n- assert_pod_log_contains(&pods, VERBOSE_WASI_POD, r#\"Args are: [\"arg1\", \"arg2\"]\"#).await?;\n+#[tokio::test]\n+async fn test_module_exiting_with_error() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-module-exit-error\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n- create_faily_pod(client.clone(), &pods).await?;\n- assert_main_container_exited_with_failure(&pods, FAILY_POD).await?;\n- assert_pod_log_contains(\n+ create_faily_pod(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::main_container_exited_with_failure(&pods, FAILY_POD).await?;\n+ assert::pod_log_contains(\n&pods,\nFAILY_POD,\nr#\"ERR: Failed with File /nope.nope.nope.txt was expected to exist but did not\"#,\n)\n.await?;\n- create_loggy_pod(client.clone(), &pods).await?;\n- assert_pod_container_log_contains(&pods, LOGGY_POD, \"floofycat\", r#\"slats\"#).await?;\n- assert_pod_container_log_contains(&pods, LOGGY_POD, \"neatcat\", r#\"kiki\"#).await?;\n+ Ok(())\n+}\n+\n+#[tokio::test]\n+async fn test_init_containers() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-init-containers\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n- create_pod_with_init_containers(client.clone(), &pods).await?;\n- assert_pod_log_contains(&pods, INITY_WASI_POD, r#\"slats\"#).await?;\n+ create_pod_with_init_containers(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::pod_log_contains(&pods, INITY_WASI_POD, r#\"slats\"#).await?;\nassert_container_statuses(\n&pods,\nINITY_WASI_POD,\n@@ -725,15 +615,23 @@ async fn test_wasi_provider() -> anyhow::Result<()> {\n)\n.await?;\n- create_pod_with_failing_init_container(client.clone(), &pods).await?;\n- assert_pod_exited_with_failure(&pods, FAILY_INITS_POD).await?;\n- assert_pod_message_contains(\n+ Ok(())\n+}\n+\n+#[tokio::test]\n+async fn test_failing_init_containers() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-failing-init-containers\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ create_pod_with_failing_init_container(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::pod_exited_with_failure(&pods, FAILY_INITS_POD).await?;\n+ assert::pod_message_contains(\n&pods,\nFAILY_INITS_POD,\n\"Init container init-that-fails failed\",\n)\n.await?;\n- assert_pod_container_log_contains(\n+ assert::pod_container_log_contains(\n&pods,\nFAILY_INITS_POD,\n\"init-that-fails\",\n@@ -746,143 +644,3 @@ async fn test_wasi_provider() -> anyhow::Result<()> {\nOk(())\n}\n-\n-async fn assert_pod_log_equals(\n- pods: &Api<Pod>,\n- pod_name: &str,\n- expected_log: &str,\n-) -> anyhow::Result<()> {\n- let mut logs = pods.log_stream(pod_name, &LogParams::default()).await?;\n-\n- while let Some(chunk) = logs.try_next().await? {\n- assert_eq!(expected_log, String::from_utf8_lossy(&chunk));\n- }\n-\n- Ok(())\n-}\n-\n-async fn assert_pod_log_contains(\n- pods: &Api<Pod>,\n- pod_name: &str,\n- expected_log: &str,\n-) -> anyhow::Result<()> {\n- let logs = pods.logs(pod_name, &LogParams::default()).await?;\n- assert!(\n- logs.contains(expected_log),\n- format!(\"Expected log containing {} but got {}\", expected_log, logs)\n- );\n- Ok(())\n-}\n-\n-async fn assert_pod_container_log_contains(\n- pods: &Api<Pod>,\n- pod_name: &str,\n- container_name: &str,\n- expected_log: &str,\n-) -> anyhow::Result<()> {\n- let mut log_params = LogParams::default();\n- log_params.container = Some(container_name.to_owned());\n- let logs = pods.logs(pod_name, &log_params).await?;\n- assert!(\n- logs.contains(expected_log),\n- format!(\"Expected log containing {} but got {}\", expected_log, logs)\n- );\n- Ok(())\n-}\n-\n-// async fn assert_pod_log_does_not_contain(\n-// pods: &Api<Pod>,\n-// pod_name: &str,\n-// unexpected_log: &str,\n-// ) -> anyhow::Result<()> {\n-// let logs = pods.logs(pod_name, &LogParams::default()).await?;\n-// assert!(\n-// !logs.contains(unexpected_log),\n-// format!(\n-// \"Expected log NOT containing {} but got {}\",\n-// unexpected_log, logs\n-// )\n-// );\n-// Ok(())\n-// }\n-\n-async fn assert_pod_exited_successfully(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\n- let pod = pods.get(pod_name).await?;\n-\n- let state = (|| {\n- pod.status?.container_statuses?[0]\n- .state\n- .as_ref()?\n- .terminated\n- .clone()\n- })()\n- .expect(\"Could not fetch terminated states\");\n- assert_eq!(state.exit_code, 0);\n-\n- Ok(())\n-}\n-\n-async fn assert_pod_exited_with_failure(pods: &Api<Pod>, pod_name: &str) -> anyhow::Result<()> {\n- let pod = pods.get(pod_name).await?;\n-\n- let phase = (|| pod.status?.phase)().expect(\"Could not get pod phase\");\n- assert_eq!(phase, \"Failed\");\n-\n- Ok(())\n-}\n-\n-async fn assert_pod_message_contains(\n- pods: &Api<Pod>,\n- pod_name: &str,\n- expected_message: &str,\n-) -> anyhow::Result<()> {\n- let pod = pods.get(pod_name).await?;\n-\n- let message = (|| pod.status?.message)().expect(\"Could not get pod message\");\n- assert!(\n- message.contains(expected_message),\n- format!(\n- \"Expected pod message containing {} but got {}\",\n- expected_message, message\n- )\n- );\n-\n- Ok(())\n-}\n-\n-async fn assert_main_container_exited_with_failure(\n- pods: &Api<Pod>,\n- pod_name: &str,\n-) -> anyhow::Result<()> {\n- let pod = pods.get(pod_name).await?;\n-\n- let state = (|| {\n- pod.status?.container_statuses?[0]\n- .state\n- .as_ref()?\n- .terminated\n- .clone()\n- })()\n- .expect(\"Could not fetch terminated states\");\n- assert_eq!(state.exit_code, 1);\n-\n- Ok(())\n-}\n-\n-async fn assert_container_file_contains(\n- container_file_path: &str,\n- expected_content: &str,\n- file_error: &str,\n-) -> anyhow::Result<()> {\n- let file_path_base = dirs::home_dir()\n- .expect(\"home dir does not exist\")\n- .join(\".krustlet/volumes/hello-wasi-default\");\n- let container_file_bytes = tokio::fs::read(file_path_base.join(container_file_path))\n- .await\n- .expect(file_error);\n- assert_eq!(\n- expected_content.to_owned().into_bytes(),\n- container_file_bytes\n- );\n- Ok(())\n-}\n" }, { "change_type": "MODIFY", "old_path": "tests/pod_builder.rs", "new_path": "tests/pod_builder.rs", "diff": "@@ -96,6 +96,9 @@ pub fn wasmerciser_pod(\n\"value\": architecture,\n},\n],\n+ \"nodeSelector\": {\n+ \"kubernetes.io/arch\": architecture\n+ },\n\"volumes\": volumes,\n}\n}))?;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/pod_setup.rs", "diff": "+use futures::{StreamExt, TryStreamExt};\n+use k8s_openapi::api::core::v1::Pod;\n+use kube::{\n+ api::{Api, ListParams, WatchEvent},\n+ runtime::Informer,\n+};\n+\n+pub async fn wait_for_pod_ready(\n+ client: kube::Client,\n+ pod_name: &str,\n+ namespace: &str,\n+) -> anyhow::Result<()> {\n+ let api = Api::namespaced(client, namespace);\n+ let inf: Informer<Pod> = Informer::new(api).params(\n+ ListParams::default()\n+ .fields(&format!(\"metadata.name={}\", pod_name))\n+ .timeout(30),\n+ );\n+\n+ let mut watcher = inf.poll().await?.boxed();\n+ let mut went_ready = false;\n+ while let Some(event) = watcher.try_next().await? {\n+ match event {\n+ WatchEvent::Modified(o) => {\n+ let phase = o.status.unwrap().phase.unwrap();\n+ if phase == \"Running\" {\n+ went_ready = true;\n+ break;\n+ }\n+ }\n+ WatchEvent::Error(e) => {\n+ panic!(\"WatchEvent error: {:?}\", e);\n+ }\n+ _ => {}\n+ }\n+ }\n+\n+ assert!(went_ready, \"pod never went ready\");\n+\n+ Ok(())\n+}\n+\n+#[derive(PartialEq)]\n+pub enum OnFailure {\n+ Accept,\n+ Panic,\n+}\n+\n+pub async fn wait_for_pod_complete(\n+ client: kube::Client,\n+ pod_name: &str,\n+ namespace: &str,\n+ on_failure: OnFailure,\n+) -> anyhow::Result<()> {\n+ let api = Api::namespaced(client.clone(), namespace);\n+ let inf: Informer<Pod> = Informer::new(api).params(\n+ ListParams::default()\n+ .fields(&format!(\"metadata.name={}\", pod_name))\n+ .timeout(30),\n+ );\n+\n+ let mut watcher = inf.poll().await?.boxed();\n+ let mut went_ready = false;\n+ while let Some(event) = watcher.try_next().await? {\n+ match event {\n+ WatchEvent::Modified(o) => {\n+ let phase = o.status.unwrap().phase.unwrap();\n+ if phase == \"Failed\" && on_failure == OnFailure::Accept {\n+ return Ok(());\n+ }\n+ if phase == \"Running\" {\n+ went_ready = true;\n+ }\n+ if phase == \"Succeeded\" && !went_ready {\n+ panic!(\n+ \"Pod {} reached completed phase before receiving Running phase\",\n+ pod_name\n+ );\n+ } else if phase == \"Succeeded\" {\n+ break;\n+ }\n+ }\n+ WatchEvent::Error(e) => {\n+ panic!(\"WatchEvent error: {:?}\", e);\n+ }\n+ _ => {}\n+ }\n+ }\n+\n+ assert!(went_ready, format!(\"pod {} never went ready\", pod_name));\n+\n+ Ok(())\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/test_resource_manager.rs", "diff": "+use futures::StreamExt;\n+use k8s_openapi::api::core::v1::{ConfigMap, Namespace, Pod, Secret};\n+use kube::api::{Api, DeleteParams, PostParams};\n+use serde_json::json;\n+\n+#[derive(Clone, Debug)]\n+pub enum TestResource {\n+ Secret(String),\n+ ConfigMap(String),\n+ Pod(String),\n+}\n+\n+#[derive(Clone, Debug)]\n+pub enum TestResourceSpec {\n+ Secret(String, String, String), // single value per secret for now\n+ ConfigMap(String, String, String), // single value per cm for now\n+}\n+\n+impl TestResourceSpec {\n+ pub fn secret(resource_name: &str, value_name: &str, value: &str) -> Self {\n+ Self::Secret(\n+ resource_name.to_owned(),\n+ value_name.to_owned(),\n+ value.to_owned(),\n+ )\n+ }\n+\n+ pub fn config_map(resource_name: &str, value_name: &str, value: &str) -> Self {\n+ Self::ConfigMap(\n+ resource_name.to_owned(),\n+ value_name.to_owned(),\n+ value.to_owned(),\n+ )\n+ }\n+}\n+\n+pub struct TestResourceManager {\n+ namespace: String,\n+ client: kube::Client,\n+ resources: Vec<TestResource>,\n+}\n+\n+impl Drop for TestResourceManager {\n+ fn drop(&mut self) {\n+ let resources = self.resources.clone();\n+ let namespace = self.namespace.clone();\n+ let t = std::thread::spawn(move || {\n+ let mut rt =\n+ tokio::runtime::Runtime::new().expect(\"Failed to create Tokio runtime for cleanup\");\n+ rt.block_on(clean_up_resources(resources, namespace))\n+ });\n+\n+ let thread_result = t.join();\n+ let cleanup_result = thread_result.expect(\"Failed to clean up WASI test resources\");\n+ cleanup_result.unwrap()\n+ }\n+}\n+\n+impl TestResourceManager {\n+ pub async fn initialise(namespace: &str, client: kube::Client) -> anyhow::Result<Self> {\n+ let namespaces: Api<Namespace> = Api::all(client.clone());\n+ namespaces\n+ .create(\n+ &PostParams::default(),\n+ &serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Namespace\",\n+ \"metadata\": {\n+ \"name\": namespace\n+ },\n+ \"spec\": {}\n+ }))?,\n+ )\n+ .await?;\n+\n+ // k8s seems to need a bit of time for namespace permissions to flow\n+ // through the system. TODO: make this less worse\n+ tokio::time::delay_for(tokio::time::Duration::from_millis(100)).await;\n+\n+ Ok(TestResourceManager {\n+ namespace: namespace.to_owned(),\n+ client: client.clone(),\n+ resources: vec![],\n+ })\n+ }\n+\n+ pub fn namespace(&self) -> &str {\n+ &self.namespace\n+ }\n+\n+ pub fn push(&mut self, resource: TestResource) {\n+ self.resources.push(resource)\n+ }\n+\n+ pub async fn set_up_resources(\n+ &mut self,\n+ resources: Vec<TestResourceSpec>,\n+ ) -> anyhow::Result<()> {\n+ for resource in resources {\n+ self.set_up_resource(&resource).await?;\n+ }\n+\n+ Ok(())\n+ }\n+\n+ async fn set_up_resource(&mut self, resource: &TestResourceSpec) -> anyhow::Result<()> {\n+ let secrets: Api<Secret> = Api::namespaced(self.client.clone(), self.namespace());\n+ let config_maps: Api<ConfigMap> = Api::namespaced(self.client.clone(), self.namespace());\n+\n+ match resource {\n+ TestResourceSpec::Secret(resource_name, value_name, value) => {\n+ secrets\n+ .create(\n+ &PostParams::default(),\n+ &serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Secret\",\n+ \"metadata\": {\n+ \"name\": resource_name\n+ },\n+ \"stringData\": {\n+ value_name: value\n+ }\n+ }))?,\n+ )\n+ .await?;\n+ self.push(TestResource::Secret(resource_name.to_owned()));\n+ }\n+ TestResourceSpec::ConfigMap(resource_name, value_name, value) => {\n+ config_maps\n+ .create(\n+ &PostParams::default(),\n+ &serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"ConfigMap\",\n+ \"metadata\": {\n+ \"name\": resource_name\n+ },\n+ \"data\": {\n+ value_name: value\n+ }\n+ }))?,\n+ )\n+ .await?;\n+ self.push(TestResource::ConfigMap(resource_name.to_owned()));\n+ }\n+ }\n+\n+ Ok(())\n+ }\n+}\n+\n+// This needs to be a free function to work nicely with the Drop\n+// implementation\n+async fn clean_up_resources(resources: Vec<TestResource>, namespace: String) -> anyhow::Result<()> {\n+ let mut cleanup_error_opts: Vec<_> = futures::stream::iter(resources)\n+ .then(|r| clean_up_resource(r, &namespace))\n+ .collect()\n+ .await;\n+ cleanup_error_opts.push(clean_up_namespace(&namespace).await);\n+\n+ let cleanup_errors: Vec<_> = cleanup_error_opts\n+ .iter()\n+ .filter(|e| e.is_some())\n+ .map(|e| e.as_ref().unwrap().to_string())\n+ .filter(|s| !s.contains(r#\"reason: \"NotFound\"\"#))\n+ .collect();\n+\n+ if cleanup_errors.is_empty() {\n+ Ok(())\n+ } else {\n+ let cleanup_failure_text = format!(\n+ \"Error(s) cleaning up resources: {}\",\n+ cleanup_errors.join(\", \")\n+ );\n+ Err(anyhow::anyhow!(cleanup_failure_text))\n+ }\n+}\n+\n+async fn clean_up_resource(resource: TestResource, namespace: &String) -> Option<String> {\n+ let client = kube::Client::try_default()\n+ .await\n+ .expect(\"Failed to create client\");\n+\n+ let secrets: Api<Secret> = Api::namespaced(client.clone(), namespace);\n+ let config_maps: Api<ConfigMap> = Api::namespaced(client.clone(), namespace);\n+ let pods: Api<Pod> = Api::namespaced(client.clone(), namespace);\n+\n+ match resource {\n+ TestResource::Secret(name) => secrets\n+ .delete(&name, &DeleteParams::default())\n+ .await\n+ .err()\n+ .map(|e| format!(\"secret {} ({})\", name, e)),\n+ TestResource::ConfigMap(name) => config_maps\n+ .delete(&name, &DeleteParams::default())\n+ .await\n+ .err()\n+ .map(|e| format!(\"configmap {} ({})\", name, e)),\n+ TestResource::Pod(name) => pods\n+ .delete(&name, &DeleteParams::default())\n+ .await\n+ .err()\n+ .map(|e| format!(\"pod {} ({})\", name, e)),\n+ }\n+}\n+\n+async fn clean_up_namespace(namespace: &String) -> Option<String> {\n+ let client = kube::Client::try_default()\n+ .await\n+ .expect(\"Failed to create client\");\n+\n+ let namespaces: Api<Namespace> = Api::all(client.clone());\n+\n+ namespaces\n+ .delete(&namespace, &DeleteParams::default())\n+ .await\n+ .err()\n+ .map(|e| format!(\"namespace {} ({})\", namespace, e))\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Modularise WASI integration tests (#330)
350,405
28.07.2020 14:01:22
-43,200
724745bce426642a110308c0dc6f3d9a1a11c4f1
Document tolerations and node affinities for WASM
[ { "change_type": "MODIFY", "old_path": "docs/howto/README.md", "new_path": "docs/howto/README.md", "diff": "@@ -14,3 +14,5 @@ However, these guides will help you quickly accomplish common tasks.\n- [Running Kubernetes on Amazon Elastic Kubernetes Service (EKS)](kubernetes-on-eks.md)\n- [Running Kubernetes on Kubernetes-in-Docker (KinD)](kubernetes-on-kind.md)\n- [Running Kubernetes on Minikube](kubernetes-on-minikube.md)\n+\n+- [Running Web Assembly (WASM) workloads in Kubernetes](wasm.md)\n" }, { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-wsl2.md", "new_path": "docs/howto/krustlet-on-wsl2.md", "diff": "@@ -122,3 +122,13 @@ $ kubectl get nodes -o wide\nNAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME\ndocker-desktop Ready master 4d v1.15.5 192.168.65.3 <none> Docker Desktop 4.19.104-microsoft-standard docker://19.3.8\n```\n+\n+## Troubleshooting\n+\n+### WASM workloads on Docker Desktop\n+\n+Docker Desktop's Kubernetes always provides a schedulable node called\n+`docker-desktop`. This node uses Docker to run containers. If you want\n+to run WASM workloads on Krustlet, you must prevent these pods from being\n+scheduled to the `docker-desktop` node. You can do this using a nodeSelector\n+in pod specs. See [Running WASM workloads](../howto/wasm.md) for details.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/howto/wasm.md", "diff": "+# Running Web Assembly (WASM) workloads in Kubernetes\n+\n+The Krustlet repository contains two projects, `krustlet-wasi` and\n+`krustlet-wascc`, for running WASM workloads in Kubernetes. These kubelets\n+run workloads implemented as Web Assembly (WASM) modules rather than\n+as OCI containers. Each running instance appears to Kubernetes as a\n+node; Kubernetes schedules work to the instance as to any other node.\n+\n+## Running WASM modules on the right kubelet\n+\n+WASM modules are not interchangeable with OCI containers: `krustlet-wasi`\n+and `krustlet-wascc` can't run OCI containers, and normal OCI nodes\n+can't run WASM modules. In order to run your WASM workloads on the right\n+nodes, you should use the Kubernetes tolerations system; in some cases you\n+will also need to use node affinity.\n+\n+The `krustlet-wasi` and `krustlet-wascc` 'virtual nodes' both have\n+`NoExecute` taints with the key `krustlet/arch` and a provider-defined\n+value (`wasm32-wasi` or `wasm32-wascc` respectively). WASM pods must\n+therefore specify a toleration for this taint. For example:\n+\n+```yaml\n+apiVersion: v1\n+kind: Pod\n+metadata:\n+ name: hello-wasm\n+spec:\n+ containers:\n+ - name: hello-wasm\n+ image: webassembly.azurecr.io/hello-wasm:v1\n+ tolerations:\n+ - effect: NoExecute\n+ key: krustlet/arch\n+ operator: Equal\n+ value: wasm32-wasi # or wasm32-wascc according to module target arch\n+```\n+\n+In addition, if the Kubernetes cluster contains 'standard' OCI nodes which\n+do not taint themselves, you should prevent Kubernetes from scheduling\n+WASM workloads to those nodes. To do this, you can either taint the OCI\n+nodes (though this may require you to provide suitable tolerations on\n+OCI pods), or you can specify a node selector on the WASM workload to\n+direct it to compatible nodes:\n+\n+```yaml\n+apiVersion: v1\n+kind: Pod\n+metadata:\n+ name: hello-wasm\n+spec:\n+ # other values as above\n+ nodeSelector:\n+ kubernetes.io/arch: wasm32-wasi # or wasm32-wascc\n+```\n+\n+If you get intermittent image pull errors on your WASM workloads, check\n+that they are not inadvertently getting scheduled to OCI nodes.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Document tolerations and node affinities for WASM (#332)
350,405
30.07.2020 12:04:15
-43,200
3fc343ba7bb04a5d1feb324dca657531a66de5e9
UI to notify user if they need to approve a bootstrap CSR
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/bootstrapping/mod.rs", "new_path": "crates/kubelet/src/bootstrapping/mod.rs", "diff": "@@ -23,10 +23,11 @@ const APPROVED_TYPE: &str = \"Approved\";\npub async fn bootstrap<K: AsRef<Path>>(\nconfig: &KubeletConfig,\nbootstrap_file: K,\n+ notify: impl Fn(String),\n) -> anyhow::Result<Config> {\ndebug!(\"Starting bootstrap for {}\", config.node_name);\nlet kubeconfig = bootstrap_auth(config, bootstrap_file).await?;\n- bootstrap_tls(config, kubeconfig.clone()).await?;\n+ bootstrap_tls(config, kubeconfig.clone(), notify).await?;\nOk(kubeconfig)\n}\n@@ -149,7 +150,11 @@ async fn bootstrap_auth<K: AsRef<Path>>(\n}\n}\n-async fn bootstrap_tls(config: &KubeletConfig, kubeconfig: Config) -> anyhow::Result<()> {\n+async fn bootstrap_tls(\n+ config: &KubeletConfig,\n+ kubeconfig: Config,\n+ notify: impl Fn(String),\n+) -> anyhow::Result<()> {\ndebug!(\"Starting bootstrap of TLS serving certs\");\nif config.server_config.cert_file.exists() {\nreturn Ok(());\n@@ -182,6 +187,8 @@ async fn bootstrap_tls(config: &KubeletConfig, kubeconfig: Config) -> anyhow::Re\ncsrs.create(&PostParams::default(), &post_data).await?;\n+ notify(awaiting_user_csr_approval(\"TLS\", &csr_name));\n+\n// Wait for CSR signing\nlet inf: Informer<CertificateSigningRequest> = Informer::new(csrs)\n.params(ListParams::default().fields(&format!(\"metadata.name={}\", csr_name)));\n@@ -231,9 +238,25 @@ async fn bootstrap_tls(config: &KubeletConfig, kubeconfig: Config) -> anyhow::Re\nwrite(&config.server_config.cert_file, &certificate).await?;\nwrite(&config.server_config.private_key_file, &private_key).await?;\n+ notify(completed_csr_approval(\"TLS\"));\n+\nOk(())\n}\n+fn awaiting_user_csr_approval(cert_description: &str, csr_name: &str) -> String {\n+ format!(\n+ \"{} certificate requires manual approval. Run kubectl certificate approve {}\",\n+ cert_description, csr_name\n+ )\n+}\n+\n+fn completed_csr_approval(cert_description: &str) -> String {\n+ format!(\n+ \"received {} certificate approval: continuing\",\n+ cert_description\n+ )\n+}\n+\nfn gen_auth_cert(config: &KubeletConfig) -> anyhow::Result<Certificate> {\nlet mut params = CertificateParams::default();\nparams.not_before = chrono::Utc::now();\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wascc.rs", "new_path": "src/krustlet-wascc.rs", "diff": "@@ -14,7 +14,7 @@ async fn main() -> anyhow::Result<()> {\n// Initialize the logger\nenv_logger::init();\n- let kubeconfig = kubelet::bootstrap(&config, &config.bootstrap_file).await?;\n+ let kubeconfig = kubelet::bootstrap(&config, &config.bootstrap_file, notify_bootstrap).await?;\nlet store = make_store(&config);\n@@ -35,3 +35,7 @@ fn make_store(config: &Config) -> Arc<dyn kubelet::store::Store + Send + Sync> {\nfile_store\n}\n}\n+\n+fn notify_bootstrap(message: String) {\n+ println!(\"BOOTSTRAP: {}\", message);\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wasi.rs", "new_path": "src/krustlet-wasi.rs", "diff": "@@ -14,7 +14,7 @@ async fn main() -> anyhow::Result<()> {\n// Initialize the logger\nenv_logger::init();\n- let kubeconfig = kubelet::bootstrap(&config, &config.bootstrap_file).await?;\n+ let kubeconfig = kubelet::bootstrap(&config, &config.bootstrap_file, notify_bootstrap).await?;\nlet store = make_store(&config);\n@@ -35,3 +35,7 @@ fn make_store(config: &Config) -> Arc<dyn kubelet::store::Store + Send + Sync> {\nfile_store\n}\n}\n+\n+fn notify_bootstrap(message: String) {\n+ println!(\"BOOTSTRAP: {}\", message);\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
UI to notify user if they need to approve a bootstrap CSR (#336)
350,426
31.07.2020 10:15:22
18,000
dc7c60b1eadc9b761f014ba17abbadebafcd0831
State module
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -358,6 +358,17 @@ dependencies = [\n\"pin-project-lite\",\n]\n+[[package]]\n+name = \"async-recursion\"\n+version = \"0.3.1\"\n+source = \"registry+https://github.com/rust-lang/crates.io-index\"\n+checksum = \"e5444eec77a9ec2bfe4524139e09195862e981400c4358d3b760cae634e4c4ee\"\n+dependencies = [\n+ \"proc-macro2\",\n+ \"quote\",\n+ \"syn\",\n+]\n+\n[[package]]\nname = \"async-trait\"\nversion = \"0.1.36\"\n@@ -1679,6 +1690,7 @@ name = \"kubelet\"\nversion = \"0.3.0\"\ndependencies = [\n\"anyhow\",\n+ \"async-recursion\",\n\"async-trait\",\n\"base64 0.12.3\",\n\"chrono\",\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/Cargo.toml", "new_path": "crates/kubelet/Cargo.toml", "diff": "@@ -60,6 +60,7 @@ warp = { version = \"0.2\", features = ['tls'] }\nhttp = \"0.2\"\nrcgen = \"0.8\"\nuuid = { version = \"0.8.1\", features = [\"v4\"] }\n+async-recursion = \"0.3.1\"\n[dev-dependencies]\nreqwest = {version = \"0.10\", default-features = false }\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/lib.rs", "new_path": "crates/kubelet/src/lib.rs", "diff": "mod bootstrapping;\nmod kubelet;\n+mod state;\npub(crate) mod kubeconfig;\npub(crate) mod webserver;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -43,11 +43,12 @@ impl Worker {\n// Watch errors are handled before an event ever gets here, so it should always have\n// a pod\nlet pod = pod_from_event(&event).unwrap();\n- if let Err(e) = provider.handle_event(event).await {\n- if let Err(e) = error_sender.send((pod, e)).await {\n- error!(\"Unable to send error to status updater: {:?}\", e)\n- }\n- }\n+ unimplemented!()\n+ // if let Err(e) = provider.handle_event(event).await {\n+ // if let Err(e) = error_sender.send((pod, e)).await {\n+ // error!(\"Unable to send error to status updater: {:?}\", e)\n+ // }\n+ // }\n}\n});\nWorker {\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider/mod.rs", "new_path": "crates/kubelet/src/provider/mod.rs", "diff": "@@ -57,21 +57,6 @@ pub trait Provider {\nOk(())\n}\n- /// Given a Pod definition, execute the workload.\n- async fn add(&self, pod: Pod) -> anyhow::Result<()>;\n-\n- /// Given an updated Pod definition, update the given workload.\n- ///\n- /// Pods that are sent to this function have already met certain criteria for modification.\n- /// For example, updates to the `status` of a Pod will not be sent into this function.\n- async fn modify(&self, pod: Pod) -> anyhow::Result<()>;\n-\n- /// Given the definition of a deleted Pod, remove the workload from the runtime.\n- ///\n- /// This does not need to actually delete the Pod definition -- just destroy the\n- /// associated workload.\n- async fn delete(&self, pod: Pod) -> anyhow::Result<()>;\n-\n/// Given a Pod, get back the logs for the associated workload.\nasync fn logs(\n&self,\n@@ -89,32 +74,6 @@ pub trait Provider {\nErr(NotImplementedError.into())\n}\n- /// Determine what to do when a new event comes in.\n- ///\n- /// In most cases, this should not be overridden. It is exposed for rare cases when\n- /// the underlying event handling needs to change.\n- async fn handle_event(&self, event: WatchEvent<KubePod>) -> anyhow::Result<()> {\n- match event {\n- WatchEvent::Added(pod) => {\n- let pod = pod.into();\n- self.add(pod).await\n- }\n- WatchEvent::Modified(pod) => {\n- let pod = pod.into();\n- self.modify(pod).await\n- }\n- WatchEvent::Deleted(pod) => {\n- let pod = pod.into();\n- self.delete(pod).await\n- }\n- WatchEvent::Error(e) => {\n- error!(\"Event error: {}\", e);\n- Err(e.into())\n- }\n- WatchEvent::Bookmark(_) => Ok(()),\n- }\n- }\n-\n/// Resolve the environment variables for a container.\n///\n/// This generally should not be overwritten unless you need to handle\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/state.rs", "diff": "+use crate::pod::Pod;\n+use k8s_openapi::api::core::v1::Pod as KubePod;\n+use kube::api::{Api, PatchParams};\n+use std::sync::Arc;\n+use tokio::sync::Mutex;\n+\n+/// Represents result of state execution and which state to transition to next.\n+pub enum Transition<S, E> {\n+ /// Advance to next node.\n+ Advance(S),\n+ /// Transition to error node.\n+ Error(E),\n+ /// This is a terminal node of the state graph.\n+ Complete(anyhow::Result<()>),\n+}\n+\n+#[async_trait::async_trait]\n+/// A trait representing a node in the state graph.\n+pub trait State<ProviderState: Sync + Send + 'static>: Sync + Send + 'static {\n+ /// The next state on success.\n+ type Success: State<ProviderState>;\n+ /// The next state on error.\n+ type Error: State<ProviderState>;\n+\n+ /// Provider supplies method to be executed when in this state.\n+ async fn next(\n+ self,\n+ state: Arc<Mutex<ProviderState>>,\n+ pod: &Pod,\n+ ) -> anyhow::Result<Transition<Self::Success, Self::Error>>;\n+\n+ /// Provider supplies JSON status patch to apply when entering this state.\n+ async fn json_status(\n+ &self,\n+ state: &ProviderState,\n+ pod: &Pod,\n+ ) -> anyhow::Result<serde_json::Value>;\n+}\n+\n+#[async_recursion::async_recursion]\n+/// Recursively evaluate state machine until a state returns Complete.\n+pub async fn run_to_completion<ProviderState: Send + Sync + 'static>(\n+ client: &kube::Client,\n+ state: impl State<ProviderState>,\n+ provider_state: Arc<Mutex<ProviderState>>,\n+ pod: Pod,\n+) -> anyhow::Result<()> {\n+ // When handling a new state, we update the Pod state with Kubernetes.\n+ let api: Api<KubePod> = Api::namespaced(client.clone(), pod.namespace());\n+ let patch = {\n+ let pstate = provider_state.lock().await;\n+ state.json_status(&(*pstate), &pod).await?\n+ };\n+ let data = serde_json::to_vec(&patch)?;\n+ api.patch_status(&pod.name(), &PatchParams::default(), data)\n+ .await?;\n+\n+ // Execute state.\n+ let transition = {\n+ state.next(Arc::clone(&provider_state), &pod).await?\n+ };\n+\n+ // Handle transition\n+ match transition {\n+ Transition::Advance(s) => run_to_completion(client, s, provider_state, pod).await,\n+ Transition::Error(s) => run_to_completion(client, s, provider_state, pod).await,\n+ Transition::Complete(result) => result,\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
State module
350,426
01.08.2020 09:17:43
18,000
047ceef0acc360e9147d1bb25b9302eec5e86356
Fix warnings and call state machine from pod queue.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/config.rs", "new_path": "crates/kubelet/src/config.rs", "diff": "//! or in environment variables, but falling back to the specified configuration file\n//! (requires you to turn on the \"cli\" feature)\n-use std::iter::FromIterator;\nuse std::net::IpAddr;\nuse std::net::ToSocketAddrs;\nuse std::path::PathBuf;\n+#[cfg(any(feature = \"cli\", feature = \"docs\"))]\n+use std::iter::FromIterator;\n+\n#[cfg(feature = \"cli\")]\nuse structopt::StructOpt;\n@@ -239,6 +241,7 @@ impl Default for Config {\n}\n}\n+#[cfg(any(feature = \"cli\", feature = \"docs\"))]\nfn ok_result_of<T>(value: Option<T>) -> Option<anyhow::Result<T>> {\nvalue.map(Ok)\n}\n@@ -288,6 +291,7 @@ impl ConfigBuilder {\nserde_json::from_reader(reader).map_err(anyhow::Error::new)\n}\n+ #[cfg(any(feature = \"cli\", feature = \"docs\"))]\nfn with_override(self: Self, other: Self) -> Self {\nConfigBuilder {\nnode_ip: other.node_ip.or(self.node_ip),\n@@ -540,6 +544,7 @@ fn default_cert_path(data_dir: &PathBuf) -> PathBuf {\ndata_dir.join(\"config/krustlet.crt\")\n}\n+#[cfg(any(feature = \"cli\", feature = \"docs\"))]\nfn default_config_file_path() -> PathBuf {\ndirs::home_dir()\n.unwrap()\n@@ -553,6 +558,7 @@ fn is_same_ip_family(first: &IpAddr, second: &IpAddr) -> bool {\n}\n}\n+#[cfg(any(feature = \"cli\", feature = \"docs\"))]\nfn split_one_label(in_string: &str) -> Option<(String, String)> {\nlet mut splitter = in_string.splitn(2, '=');\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "use crate::config::Config;\nuse crate::node;\nuse crate::pod::Queue;\n-use crate::pod::{update_status, Phase};\nuse crate::provider::Provider;\nuse crate::webserver::start as start_webserver;\n@@ -11,7 +10,7 @@ use futures::future::FutureExt;\nuse futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::{\n- api::{ListParams, Meta},\n+ api::{ListParams},\nruntime::Informer,\nApi,\n};\n@@ -19,7 +18,6 @@ use log::{debug, error, info, warn};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\nuse tokio::signal::ctrl_c;\n-use tokio::sync::mpsc;\n/// A Kubelet server backed by a given `Provider`.\n///\n@@ -73,19 +71,12 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n// Start the webserver\nlet webserver = start_webserver(self.provider.clone(), &self.config.server_config).fuse();\n- let (error_sender, error_receiver) =\n- mpsc::channel::<(KubePod, anyhow::Error)>(self.config.max_pods as usize);\n- let error_handler = start_error_handler(error_receiver, client.clone()).fuse();\n-\n// Start updating the node lease and status periodically\nlet node_updater = start_node_updater(client.clone(), self.config.node_name.clone()).fuse();\n// If any of these tasks fail, we can initiate graceful shutdown.\nlet services = Box::pin(async {\ntokio::select! {\n- res = error_handler => if let Err(e) = res {\n- error!(\"Error handler task completed with error: {:?}\", &e);\n- },\nres = signal_task => if let Err(e) = res {\nerror!(\"Signal task completed with error {:?}\", &e);\n},\n@@ -108,7 +99,7 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n.fuse();\n// Create a queue that locks on events per pod\n- let queue = Queue::new(self.provider.clone(), error_sender);\n+ let queue = Queue::new(self.provider.clone(), client.clone());\nlet pod_informer = start_pod_informer::<T>(\nclient.clone(),\nself.config.node_name.clone(),\n@@ -232,48 +223,6 @@ async fn start_signal_handler(\n}\n}\n-/// Consumes error channel and notifies API server of pod failures.\n-async fn start_error_handler(\n- mut rx: mpsc::Receiver<(KubePod, anyhow::Error)>,\n- client: kube::Client,\n-) -> anyhow::Result<()> {\n- while let Some((pod, err)) = rx.recv().await {\n- let json_status = serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Failed,\n- \"message\": format!(\"{}\", err),\n- }\n- }\n- );\n-\n- debug!(\n- \"Setting pod status for {} using {:?}\",\n- pod.name(),\n- json_status\n- );\n- let pod_name = pod.name();\n- match update_status(\n- client.clone(),\n- &pod.namespace().unwrap_or_default(),\n- &pod_name,\n- &json_status,\n- )\n- .await\n- {\n- Ok(_) => (),\n- Err(e) => error!(\n- \"Unable to patch status during pod failure for {}: {}\",\n- pod_name, e\n- ),\n- }\n- }\n- Ok(())\n-}\n-\n#[cfg(test)]\nmod test {\nuse super::*;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -3,12 +3,14 @@ use std::sync::Arc;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Meta, WatchEvent};\n+use kube::Client as KubeClient;\nuse log::{debug, error};\n-use tokio::sync::{mpsc::Sender, watch};\n+use tokio::sync::{watch};\nuse tokio::task::JoinHandle;\n-use crate::pod::pod_key;\n+use crate::pod::{pod_key, Pod};\nuse crate::provider::Provider;\n+use crate::state::run_to_completion;\n/// A per-pod queue that takes incoming Kubernetes events and broadcasts them to the correct queue\n/// for that pod.\n@@ -20,7 +22,7 @@ use crate::provider::Provider;\npub(crate) struct Queue<P> {\nprovider: Arc<P>,\nhandlers: HashMap<String, Worker>,\n- error_sender: Sender<(KubePod, anyhow::Error)>,\n+ client: KubeClient\n}\nstruct Worker {\n@@ -32,7 +34,7 @@ impl Worker {\nfn create<P>(\ninitial_event: WatchEvent<KubePod>,\nprovider: Arc<P>,\n- mut error_sender: Sender<(KubePod, anyhow::Error)>,\n+ client: KubeClient\n) -> Self\nwhere\nP: 'static + Provider + Sync + Send,\n@@ -42,13 +44,24 @@ impl Worker {\nwhile let Some(event) = receiver.recv().await {\n// Watch errors are handled before an event ever gets here, so it should always have\n// a pod\n- let pod = pod_from_event(&event).unwrap();\n- unimplemented!()\n- // if let Err(e) = provider.handle_event(event).await {\n- // if let Err(e) = error_sender.send((pod, e)).await {\n- // error!(\"Unable to send error to status updater: {:?}\", e)\n- // }\n- // }\n+ match event {\n+ WatchEvent::Added(pod) => {\n+ let client = client.clone();\n+ let provider = Arc::clone(&provider);\n+ tokio::spawn(async move {\n+ let state: P::InitialState = Default::default();\n+ run_to_completion(client, state, provider, Pod::new(pod)).await\n+ });\n+ },\n+ WatchEvent::Modified(pod) => {\n+ provider.modify(Pod::new(pod)).await;\n+ },\n+ WatchEvent::Deleted(pod) => {\n+ provider.delete(Pod::new(pod)).await;\n+ }\n+ WatchEvent::Bookmark(_) => (),\n+ _ => unreachable!()\n+ }\n}\n});\nWorker {\n@@ -59,11 +72,11 @@ impl Worker {\n}\nimpl<P: 'static + Provider + Sync + Send> Queue<P> {\n- pub fn new(provider: Arc<P>, error_sender: Sender<(KubePod, anyhow::Error)>) -> Self {\n+ pub fn new(provider: Arc<P>, client: KubeClient) -> Self {\nQueue {\nprovider,\nhandlers: HashMap::new(),\n- error_sender,\n+ client\n}\n}\n@@ -86,7 +99,7 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nWorker::create(\nevent.clone(),\nself.provider.clone(),\n- self.error_sender.clone(),\n+ self.client.clone()\n),\n);\nself.handlers.get(&key).unwrap()\n@@ -108,13 +121,3 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n}\n}\n}\n-\n-fn pod_from_event(event: &WatchEvent<KubePod>) -> Option<KubePod> {\n- match event {\n- WatchEvent::Added(pod)\n- | WatchEvent::Bookmark(pod)\n- | WatchEvent::Deleted(pod)\n- | WatchEvent::Modified(pod) => Some(pod.clone()),\n- WatchEvent::Error(_) => None,\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider/mod.rs", "new_path": "crates/kubelet/src/provider/mod.rs", "diff": "use std::collections::HashMap;\nuse async_trait::async_trait;\n-use k8s_openapi::api::core::v1::{ConfigMap, EnvVarSource, Pod as KubePod, Secret};\n-use kube::api::{Api, WatchEvent};\n+use k8s_openapi::api::core::v1::{ConfigMap, EnvVarSource, Secret};\n+use kube::api::{Api};\nuse log::{error, info};\nuse thiserror::Error;\n@@ -11,6 +11,7 @@ use crate::container::Container;\nuse crate::log::Sender;\nuse crate::node::Builder;\nuse crate::pod::Pod;\n+use crate::state::State;\n/// A back-end for a Kubelet.\n///\n@@ -37,18 +38,14 @@ use crate::pod::Pod;\n/// impl Provider for MyProvider {\n/// const ARCH: &'static str = \"my-arch\";\n///\n-/// async fn add(&self, pod: Pod) -> anyhow::Result<()> {\n-/// todo!(\"Implement Provider::add\")\n-/// }\n-///\n-/// // Implement the rest of the methods using `async` for the ones that return futures ...\n-/// # async fn modify(&self, pod: Pod) -> anyhow::Result<()> { todo!() }\n-/// # async fn delete(&self, pod: Pod) -> anyhow::Result<()> { todo!() }\n/// # async fn logs(&self, namespace: String, pod: String, container: String, sender: kubelet::log::Sender) -> anyhow::Result<()> { todo!() }\n/// }\n/// ```\n#[async_trait]\n-pub trait Provider {\n+pub trait Provider: Sized {\n+ /// The initial state for Pod state machine.\n+ type InitialState: Default + State<Self>;\n+\n/// Arch returns a string specifying what architecture this provider supports\nconst ARCH: &'static str;\n@@ -57,6 +54,18 @@ pub trait Provider {\nOk(())\n}\n+ /// Given an updated Pod definition, update the given workload.\n+ ///\n+ /// Pods that are sent to this function have already met certain criteria for modification.\n+ /// For example, updates to the `status` of a Pod will not be sent into this function.\n+ async fn modify(&self, pod: Pod);\n+\n+ /// Given the definition of a deleted Pod, remove the workload from the runtime.\n+ ///\n+ /// This does not need to actually delete the Pod definition -- just destroy the\n+ /// associated workload.\n+ async fn delete(&self, pod: Pod);\n+\n/// Given a Pod, get back the logs for the associated workload.\nasync fn logs(\n&self,\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state.rs", "new_path": "crates/kubelet/src/state.rs", "diff": "@@ -2,7 +2,6 @@ use crate::pod::Pod;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Api, PatchParams};\nuse std::sync::Arc;\n-use tokio::sync::Mutex;\n/// Represents result of state execution and which state to transition to next.\npub enum Transition<S, E> {\n@@ -16,54 +15,51 @@ pub enum Transition<S, E> {\n#[async_trait::async_trait]\n/// A trait representing a node in the state graph.\n-pub trait State<ProviderState: Sync + Send + 'static>: Sync + Send + 'static {\n+pub trait State<Provider>: Sync + Send + 'static {\n/// The next state on success.\n- type Success: State<ProviderState>;\n+ type Success: State<Provider>;\n/// The next state on error.\n- type Error: State<ProviderState>;\n+ type Error: State<Provider>;\n/// Provider supplies method to be executed when in this state.\nasync fn next(\nself,\n- state: Arc<Mutex<ProviderState>>,\n+ provider: Arc<Provider>,\npod: &Pod,\n) -> anyhow::Result<Transition<Self::Success, Self::Error>>;\n/// Provider supplies JSON status patch to apply when entering this state.\nasync fn json_status(\n&self,\n- state: &ProviderState,\n+ provider: Arc<Provider>,\npod: &Pod,\n) -> anyhow::Result<serde_json::Value>;\n}\n#[async_recursion::async_recursion]\n/// Recursively evaluate state machine until a state returns Complete.\n-pub async fn run_to_completion<ProviderState: Send + Sync + 'static>(\n- client: &kube::Client,\n- state: impl State<ProviderState>,\n- provider_state: Arc<Mutex<ProviderState>>,\n+pub async fn run_to_completion<Provider: Send + Sync + 'static>(\n+ client: kube::Client,\n+ state: impl State<Provider>,\n+ provider: Arc<Provider>,\npod: Pod,\n) -> anyhow::Result<()> {\n// When handling a new state, we update the Pod state with Kubernetes.\nlet api: Api<KubePod> = Api::namespaced(client.clone(), pod.namespace());\n- let patch = {\n- let pstate = provider_state.lock().await;\n- state.json_status(&(*pstate), &pod).await?\n- };\n+ let patch = state.json_status(Arc::clone(&provider), &pod).await?;\nlet data = serde_json::to_vec(&patch)?;\napi.patch_status(&pod.name(), &PatchParams::default(), data)\n.await?;\n// Execute state.\nlet transition = {\n- state.next(Arc::clone(&provider_state), &pod).await?\n+ state.next(Arc::clone(&provider), &pod).await?\n};\n// Handle transition\nmatch transition {\n- Transition::Advance(s) => run_to_completion(client, s, provider_state, pod).await,\n- Transition::Error(s) => run_to_completion(client, s, provider_state, pod).await,\n+ Transition::Advance(s) => run_to_completion(client, s, provider, pod).await,\n+ Transition::Error(s) => run_to_completion(client, s, provider, pod).await,\nTransition::Complete(result) => result,\n}\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix warnings and call state machine from pod queue.
350,426
01.08.2020 09:58:54
18,000
9300387a8d3df605093c43f5fdb6d193a56acb60
Cargo fmt and fix doctests.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "@@ -9,11 +9,7 @@ use crate::webserver::start as start_webserver;\nuse futures::future::FutureExt;\nuse futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::core::v1::Pod as KubePod;\n-use kube::{\n- api::{ListParams},\n- runtime::Informer,\n- Api,\n-};\n+use kube::{api::ListParams, runtime::Informer, Api};\nuse log::{debug, error, info, warn};\nuse std::sync::atomic::{AtomicBool, Ordering};\nuse std::sync::Arc;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/lib.rs", "new_path": "crates/kubelet/src/lib.rs", "diff": "//! use kubelet::config::Config;\n//! use kubelet::pod::Pod;\n//! use kubelet::provider::Provider;\n+//! use kubelet::state::{State, Transition};\n+//! use std::sync::Arc;\n//!\n//! // Create some type that will act as your provider\n//! struct MyProvider;\n//!\n+//! // Implement a state machine of Pod states\n+//! #[derive(Default)]\n+//! struct Completed;\n+//! #[async_trait::async_trait]\n+//! impl <P: 'static + Sync + Send> State<P> for Completed {\n+//! type Success = Completed;\n+//! type Error = Completed;\n+//!\n+//! async fn next(\n+//! self,\n+//! provider: Arc<P>,\n+//! pod: &Pod,\n+//! ) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n+//! Ok(Transition::Complete(Ok(())))\n+//! }\n+//!\n+//! async fn json_status(\n+//! &self,\n+//! provider: Arc<P>,\n+//! pod: &Pod,\n+//! ) -> anyhow::Result<serde_json::Value> {\n+//! Ok(serde_json::json!(null))\n+//! }\n+//! }\n+//!\n//! // Implement the `Provider` trait for that type\n//! #[async_trait::async_trait]\n//! impl Provider for MyProvider {\n//! const ARCH: &'static str = \"my-arch\";\n+//! type InitialState = Completed;\n//!\n-//! async fn add(&self, pod: Pod) -> anyhow::Result<()> {\n+//! async fn modify(&self, pod: Pod) {\n//! todo!(\"Implement Provider::add\")\n//! }\n//!\n//! // Implement the rest of the methods\n-//! # async fn modify(&self, pod: Pod) -> anyhow::Result<()> { todo!() }\n-//! # async fn delete(&self, pod: Pod) -> anyhow::Result<()> { todo!() }\n-//! # async fn logs(&self, namespace: String, pod: String, container: String, sender: kubelet::log::Sender) -> anyhow::Result<()> { todo!() }\n+//! async fn delete(&self, pod: Pod) { todo!() }\n+//! async fn logs(&self, namespace: String, pod: String, container: String, sender: kubelet::log::Sender) -> anyhow::Result<()> { todo!() }\n//! }\n//!\n//! async {\nmod bootstrapping;\nmod kubelet;\n-mod state;\n+pub mod state;\npub(crate) mod kubeconfig;\npub(crate) mod webserver;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -5,7 +5,7 @@ use k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Meta, WatchEvent};\nuse kube::Client as KubeClient;\nuse log::{debug, error};\n-use tokio::sync::{watch};\n+use tokio::sync::watch;\nuse tokio::task::JoinHandle;\nuse crate::pod::{pod_key, Pod};\n@@ -22,7 +22,7 @@ use crate::state::run_to_completion;\npub(crate) struct Queue<P> {\nprovider: Arc<P>,\nhandlers: HashMap<String, Worker>,\n- client: KubeClient\n+ client: KubeClient,\n}\nstruct Worker {\n@@ -31,11 +31,7 @@ struct Worker {\n}\nimpl Worker {\n- fn create<P>(\n- initial_event: WatchEvent<KubePod>,\n- provider: Arc<P>,\n- client: KubeClient\n- ) -> Self\n+ fn create<P>(initial_event: WatchEvent<KubePod>, provider: Arc<P>, client: KubeClient) -> Self\nwhere\nP: 'static + Provider + Sync + Send,\n{\n@@ -52,15 +48,15 @@ impl Worker {\nlet state: P::InitialState = Default::default();\nrun_to_completion(client, state, provider, Pod::new(pod)).await\n});\n- },\n+ }\nWatchEvent::Modified(pod) => {\nprovider.modify(Pod::new(pod)).await;\n- },\n+ }\nWatchEvent::Deleted(pod) => {\nprovider.delete(Pod::new(pod)).await;\n}\nWatchEvent::Bookmark(_) => (),\n- _ => unreachable!()\n+ _ => unreachable!(),\n}\n}\n});\n@@ -76,7 +72,7 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nQueue {\nprovider,\nhandlers: HashMap::new(),\n- client\n+ client,\n}\n}\n@@ -99,7 +95,7 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nWorker::create(\nevent.clone(),\nself.provider.clone(),\n- self.client.clone()\n+ self.client.clone(),\n),\n);\nself.handlers.get(&key).unwrap()\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider/mod.rs", "new_path": "crates/kubelet/src/provider/mod.rs", "diff": "@@ -3,7 +3,7 @@ use std::collections::HashMap;\nuse async_trait::async_trait;\nuse k8s_openapi::api::core::v1::{ConfigMap, EnvVarSource, Secret};\n-use kube::api::{Api};\n+use kube::api::Api;\nuse log::{error, info};\nuse thiserror::Error;\n@@ -32,13 +32,49 @@ use crate::state::State;\n/// use kubelet::pod::Pod;\n/// use kubelet::provider::Provider;\n///\n+/// use kubelet::state::{State, Transition};\n+/// use std::sync::Arc;\n+///\n/// struct MyProvider;\n///\n+///\n+/// // Implement a state machine of Pod states\n+/// #[derive(Default)]\n+/// struct Completed;\n+/// #[async_trait::async_trait]\n+/// impl <P: 'static + Sync + Send> State<P> for Completed {\n+/// type Success = Completed;\n+/// type Error = Completed;\n+///\n+/// async fn next(\n+/// self,\n+/// provider: Arc<P>,\n+/// pod: &Pod,\n+/// ) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n+/// Ok(Transition::Complete(Ok(())))\n+/// }\n+///\n+/// async fn json_status(\n+/// &self,\n+/// provider: Arc<P>,\n+/// pod: &Pod,\n+/// ) -> anyhow::Result<serde_json::Value> {\n+/// Ok(serde_json::json!(null))\n+/// }\n+/// }\n+///\n/// #[async_trait]\n/// impl Provider for MyProvider {\n+/// type InitialState = Completed;\n/// const ARCH: &'static str = \"my-arch\";\n///\n-/// # async fn logs(&self, namespace: String, pod: String, container: String, sender: kubelet::log::Sender) -> anyhow::Result<()> { todo!() }\n+/// async fn modify(&self, pod: Pod) {\n+/// todo!(\"Implement Provider::add\")\n+/// }\n+///\n+/// // Implement the rest of the methods\n+/// async fn delete(&self, pod: Pod) { todo!() }\n+/// async fn logs(&self, namespace: String, pod: String, container: String, sender: kubelet::log::Sender) -> anyhow::Result<()> { todo!() }\n/// }\n/// ```\n#[async_trait]\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state.rs", "new_path": "crates/kubelet/src/state.rs", "diff": "+//! Used to define a state machine of Pod states.\n+\nuse crate::pod::Pod;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Api, PatchParams};\n@@ -52,9 +54,7 @@ pub async fn run_to_completion<Provider: Send + Sync + 'static>(\n.await?;\n// Execute state.\n- let transition = {\n- state.next(Arc::clone(&provider), &pod).await?\n- };\n+ let transition = { state.next(Arc::clone(&provider), &pod).await? };\n// Handle transition\nmatch transition {\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Cargo fmt and fix doctests.
350,426
01.08.2020 13:13:42
18,000
af6ad8832dee21a5da019e883a30422f8e51e399
Macro, default state machine graph and trait
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state.rs", "new_path": "crates/kubelet/src/state.rs", "diff": "//! Used to define a state machine of Pod states.\n+use log::info;\n+\n+pub mod default;\n+#[macro_use]\n+pub mod macros;\nuse crate::pod::Pod;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\n@@ -6,6 +11,7 @@ use kube::api::{Api, PatchParams};\nuse std::sync::Arc;\n/// Represents result of state execution and which state to transition to next.\n+#[derive(Debug)]\npub enum Transition<S, E> {\n/// Advance to next node.\nAdvance(S),\n@@ -17,7 +23,7 @@ pub enum Transition<S, E> {\n#[async_trait::async_trait]\n/// A trait representing a node in the state graph.\n-pub trait State<Provider>: Sync + Send + 'static {\n+pub trait State<Provider>: Sync + Send + 'static + std::fmt::Debug {\n/// The next state on success.\ntype Success: State<Provider>;\n/// The next state on error.\n@@ -46,6 +52,8 @@ pub async fn run_to_completion<Provider: Send + Sync + 'static>(\nprovider: Arc<Provider>,\npod: Pod,\n) -> anyhow::Result<()> {\n+ info!(\"Pod {} entering state {:?}\", pod.name(), state);\n+\n// When handling a new state, we update the Pod state with Kubernetes.\nlet api: Api<KubePod> = Api::namespaced(client.clone(), pod.namespace());\nlet patch = state.json_status(Arc::clone(&provider), &pod).await?;\n@@ -56,6 +64,12 @@ pub async fn run_to_completion<Provider: Send + Sync + 'static>(\n// Execute state.\nlet transition = { state.next(Arc::clone(&provider), &pod).await? };\n+ info!(\n+ \"Pod {} state execution result: {:?}\",\n+ pod.name(),\n+ transition\n+ );\n+\n// Handle transition\nmatch transition {\nTransition::Advance(s) => run_to_completion(client, s, provider, pod).await,\n@@ -64,7 +78,7 @@ pub async fn run_to_completion<Provider: Send + Sync + 'static>(\n}\n}\n-#[derive(Default)]\n+#[derive(Default, Debug)]\n/// Stub state machine for testing.\npub struct Stub;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/state/default.rs", "diff": "+//! Default implementation for state machine graph.\n+\n+use crate::pod::Pod;\n+use crate::state;\n+use crate::state::State;\n+use crate::state::Transition;\n+use log::error;\n+use std::sync::Arc;\n+\n+#[async_trait::async_trait]\n+/// Trait for implementing default state machine.\n+pub trait DefaultStateProvider: 'static + Sync + Send {\n+ /// A new Pod has been created.\n+ async fn registered(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ Ok(())\n+ }\n+\n+ /// Pull images for containers.\n+ async fn image_pull(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ Ok(())\n+ }\n+\n+ /// Image pull has failed several times.\n+ async fn image_pull_backoff(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n+ Ok(())\n+ }\n+\n+ /// Mount volumes for containers.\n+ async fn volume_mount(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ Ok(())\n+ }\n+\n+ /// Volume mount has failed several times.\n+ async fn volume_mount_backoff(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n+ Ok(())\n+ }\n+\n+ /// Start containers.\n+ async fn starting(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ Ok(())\n+ }\n+\n+ /// Running state.\n+ async fn running(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n+ Ok(())\n+ }\n+\n+ /// Handle any errors, on Ok, will transition to Starting again.\n+ async fn error(&self, _pod: &Pod) -> anyhow::Result<()> {\n+ tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n+ Ok(())\n+ }\n+}\n+\n+state!(\n+ /// The Kubelet is aware of the Pod.\n+ Registered,\n+ DefaultStateProvider,\n+ ImagePull,\n+ Error,\n+ {\n+ match provider.registered(pod).await {\n+ Ok(_) => Ok(Transition::Advance(ImagePull)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(Error))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Kubelet is pulling container images.\n+ ImagePull,\n+ DefaultStateProvider,\n+ VolumeMount,\n+ ImagePullBackoff,\n+ {\n+ match provider.image_pull(pod).await {\n+ Ok(_) => Ok(Transition::Advance(VolumeMount)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(ImagePullBackoff))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// Image pull has failed several times.\n+ ImagePullBackoff,\n+ DefaultStateProvider,\n+ ImagePull,\n+ ImagePullBackoff,\n+ {\n+ match provider.image_pull_backoff(pod).await {\n+ Ok(_) => Ok(Transition::Advance(ImagePull)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(ImagePullBackoff))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Kubelet is provisioning volumes.\n+ VolumeMount,\n+ DefaultStateProvider,\n+ Starting,\n+ VolumeMountBackoff,\n+ {\n+ match provider.volume_mount(pod).await {\n+ Ok(_) => Ok(Transition::Advance(Starting)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(VolumeMountBackoff))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// Volume mount has failed several times.\n+ VolumeMountBackoff,\n+ DefaultStateProvider,\n+ VolumeMount,\n+ VolumeMountBackoff,\n+ {\n+ match provider.volume_mount_backoff(pod).await {\n+ Ok(_) => Ok(Transition::Advance(VolumeMount)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(VolumeMountBackoff))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Kubelet is starting the containers.\n+ Starting,\n+ DefaultStateProvider,\n+ Running,\n+ Error,\n+ {\n+ match provider.starting(pod).await {\n+ Ok(_) => Ok(Transition::Advance(Running)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(Error))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Kubelet is provisioning volumes.\n+ Running,\n+ DefaultStateProvider,\n+ Finished,\n+ Error,\n+ {\n+ match provider.running(pod).await {\n+ Ok(_) => Ok(Transition::Advance(Finished)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(Error))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Pod encountered an error.\n+ Error,\n+ DefaultStateProvider,\n+ Starting,\n+ Error,\n+ {\n+ match provider.error(pod).await {\n+ Ok(_) => Ok(Transition::Advance(Starting)),\n+ Err(e) => {\n+ error!(\n+ \"Pod {} encountered an error in state {:?}: {:?}\",\n+ pod.name(),\n+ Self,\n+ e\n+ );\n+ Ok(Transition::Error(Error))\n+ }\n+ }\n+ },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Pod was terminated before it completed.\n+ Terminated,\n+ DefaultStateProvider,\n+ Terminated,\n+ Terminated,\n+ { Ok(Transition::Complete(Ok(()))) },\n+ { Ok(serde_json::json!(null)) }\n+);\n+\n+state!(\n+ /// The Pod completed execution with no errors.\n+ Finished,\n+ DefaultStateProvider,\n+ Finished,\n+ Finished,\n+ { Ok(Transition::Complete(Ok(()))) },\n+ { Ok(serde_json::json!(null)) }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/state/macros.rs", "diff": "+//! Macro for defining state graphs.\n+\n+#[macro_export]\n+/// Easily define state machine states and behavior.\n+macro_rules! state {\n+ (\n+ $(#[$meta:meta])*\n+ $name:ident,\n+ $state:path,\n+ $success:ty,\n+ $error: ty,\n+ $work:block,\n+ $patch:block\n+ ) => {\n+ $(#[$meta])*\n+ #[derive(Default, Debug)]\n+ pub struct $name;\n+\n+\n+ #[async_trait::async_trait]\n+ impl <P: $state> State<P> for $name {\n+ type Success = $success;\n+ type Error = $error;\n+\n+ async fn next(\n+ self,\n+ #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod: &Pod,\n+ ) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n+ #[allow(unused_braces)]\n+ $work\n+ }\n+\n+ async fn json_status(\n+ &self,\n+ #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod: &Pod,\n+ ) -> anyhow::Result<serde_json::Value> {\n+ #[allow(unused_braces)]\n+ $patch\n+ }\n+ }\n+ };\n+ (\n+ $(#[$meta:meta])*\n+ $name:ident,\n+ $state:path,\n+ $success:ty,\n+ $error: ty,\n+ $work:path,\n+ $patch:block\n+ ) => {\n+ $(#[$meta])*\n+ #[derive(Default, Debug)]\n+ pub struct $name;\n+\n+\n+ #[async_trait::async_trait]\n+ impl <P: $state> State<P> for $name {\n+ type Success = $success;\n+ type Error = $error;\n+\n+ async fn next(\n+ self,\n+ #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod: &Pod,\n+ ) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n+ $work(self, pod).await\n+ }\n+\n+ async fn json_status(\n+ &self,\n+ #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod: &Pod,\n+ ) -> anyhow::Result<serde_json::Value> {\n+ #[allow(unused_braces)]\n+ $patch\n+ }\n+ }\n+ };\n+\n+\n+\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Macro, default state machine graph and trait
350,447
10.08.2020 16:25:50
14,400
9ecba542076a7515e3d9380886fa8bbe4e64de2a
feat(oci-distribution): support digest references
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -185,7 +185,7 @@ impl Client {\nself.auth(image, None).await?;\n}\n- let url = image.to_v2_manifest_url(self.config.protocol.as_str());\n+ let url = self.to_v2_manifest_url(image);\ndebug!(\"Pulling image manifest from {}\", url);\nlet request = self.client.get(&url);\n@@ -216,7 +216,7 @@ impl Client {\n/// If the connection has already gone through authentication, this will\n/// use the bearer token. Otherwise, this will attempt an anonymous pull.\nasync fn pull_manifest(&self, image: &Reference) -> anyhow::Result<(OciManifest, String)> {\n- let url = image.to_v2_manifest_url(self.config.protocol.as_str());\n+ let url = self.to_v2_manifest_url(image);\ndebug!(\"Pulling image manifest from {}\", url);\nlet request = self.client.get(&url);\n@@ -266,7 +266,11 @@ impl Client {\ndigest: &str,\nmut out: T,\n) -> anyhow::Result<()> {\n- let url = image.to_v2_blob_url(self.config.protocol.as_str(), digest);\n+ let url = self.to_v2_blob_url(\n+ image.registry(),\n+ image.repository(),\n+ digest,\n+ );\nlet mut stream = self\n.client\n.get(&url)\n@@ -282,6 +286,38 @@ impl Client {\nOk(())\n}\n+ /// Convert a Reference to a v2 manifest URL.\n+ fn to_v2_manifest_url(&self, reference: &Reference) -> String {\n+ if let Some(digest) = reference.digest() {\n+ format!(\n+ \"{}://{}/v2/{}/manifests/{}\",\n+ self.config.protocol.as_str(),\n+ reference.registry(),\n+ reference.repository(),\n+ digest,\n+ )\n+ } else {\n+ format!(\n+ \"{}://{}/v2/{}/manifests/{}\",\n+ self.config.protocol.as_str(),\n+ reference.registry(),\n+ reference.repository(),\n+ reference.tag().unwrap_or(\"latest\")\n+ )\n+ }\n+ }\n+\n+ /// Convert a Reference to a v2 blob (layer) URL.\n+ fn to_v2_blob_url(&self, registry: &str, repository: &str, digest: &str) -> String {\n+ format!(\n+ \"{}://{}/v2/{}/blobs/{}\",\n+ self.config.protocol.as_str(),\n+ registry,\n+ repository,\n+ digest,\n+ )\n+ }\n+\n/// Generate the headers necessary for authentication.\n///\n/// If the struct has Some(bearer), this will insert the bearer token in an\n@@ -397,7 +433,52 @@ mod test {\nuse super::*;\nuse std::convert::TryFrom;\n- const HELLO_IMAGE: &str = \"webassembly.azurecr.io/hello-wasm:v1\";\n+ const HELLO_IMAGE_TAGGED: &str = \"webassembly.azurecr.io/hello-wasm:v1\";\n+ const HELLO_IMAGE_DIGESTED: &str = \"webassembly.azurecr.io/hello-wasm@sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\";\n+\n+ #[test]\n+ fn test_to_v2_blob_url() {\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n+ let blob_url = Client::default().to_v2_blob_url(image.registry(), image.repository(), \"sha256:deadbeef\");\n+ assert_eq!(\"https://webassembly.azurecr.io/v2/hello-wasm/blobs/sha256:deadbeef\", blob_url)\n+ }\n+\n+ #[test]\n+ fn test_to_v2_manifest() {\n+ let c = Client::default();\n+\n+ // Tag only\n+ let reference = Reference::try_from(HELLO_IMAGE_TAGGED)\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/v1\",\n+ c.to_v2_manifest_url(&reference)\n+ );\n+\n+ // Digest only\n+ let reference = Reference::try_from(HELLO_IMAGE_DIGESTED)\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\",\n+ c.to_v2_manifest_url(&reference)\n+ );\n+\n+ // Tag and digest\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"https://webassembly.azurecr.io/v2/hello/manifests/sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\",\n+ c.to_v2_manifest_url(&reference)\n+ );\n+\n+ // No tag or digest\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello\")\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"https://webassembly.azurecr.io/v2/hello/manifests/latest\", // TODO: confirm this is the right translation when no tag\n+ c.to_v2_manifest_url(&reference)\n+ );\n+ }\n#[tokio::test]\nasync fn test_version() {\n@@ -411,7 +492,7 @@ mod test {\n#[tokio::test]\nasync fn test_auth() {\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\nc.auth(&image, None)\n.await\n@@ -424,7 +505,7 @@ mod test {\n#[tokio::test]\nasync fn test_pull_manifest() {\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n// Currently, pull_manifest does not perform Authz, so this will fail.\nlet c = Client::default();\nc.pull_manifest(&image)\n@@ -432,8 +513,7 @@ mod test {\n.expect_err(\"pull manifest should fail\");\n// But this should pass\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n- // Currently, pull_manifest does not perform Authz, so this will fail.\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\nc.auth(&image, None).await.expect(\"authenticated\");\nlet (manifest, _) = c\n@@ -444,11 +524,22 @@ mod test {\n// The test on the manifest checks all fields. This is just a brief sanity check.\nassert_eq!(manifest.schema_version, 2);\nassert!(!manifest.layers.is_empty());\n+\n+ // Validate pulling by digest\n+ let image = Reference::try_from(HELLO_IMAGE_DIGESTED).expect(\"failed to parse reference\");\n+ let mut c = Client::default();\n+ c.auth(&image, None).await.expect(\"authenticated\");\n+ let (manifest, _) = c\n+ .pull_manifest(&image)\n+ .await\n+ .expect(\"pull manifest should not fail\");\n+ assert_eq!(manifest.config.digest, \"sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a\");\n+ assert!(!manifest.layers.is_empty());\n}\n#[tokio::test]\nasync fn test_fetch_digest() {\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\nc.fetch_manifest_digest(&image)\n@@ -456,7 +547,7 @@ mod test {\n.expect(\"pull manifest should not fail\");\n// This should pass\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\nc.auth(&image, None).await.expect(\"authenticated\");\nlet digest = c\n@@ -472,7 +563,7 @@ mod test {\n#[tokio::test]\nasync fn test_pull_layer() {\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\nc.auth(&image, None).await.expect(\"authenticated\");\nlet (manifest, _) = c\n@@ -494,7 +585,7 @@ mod test {\n#[tokio::test]\nasync fn test_pull_image() {\n- let image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\nlet image_data = c.pull_image(&image).await.expect(\"failed to pull manifest\");\n" }, { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -3,13 +3,15 @@ use std::convert::{Into, TryFrom};\n/// An OCI image reference\n///\n/// currently, the library only accepts modules tagged in the following structure:\n-/// <registry>/<repository>:<tag> or <registry>/<repository>\n+/// <registry>/<repository>, <registry>/<repository>:<tag>, or <registry>/<repository>@<digest>\n/// for example: webassembly.azurecr.io/hello:v1 or webassembly.azurecr.io/hello\n#[derive(Clone, Hash, PartialEq, Eq)]\npub struct Reference {\nwhole: String,\n- slash: usize,\n- colon: Option<usize>,\n+ repo_start: usize,\n+ repo_end: usize,\n+ tag_start: Option<usize>,\n+ digest_start: Option<usize>,\n}\nimpl std::fmt::Debug for Reference {\n@@ -32,62 +34,65 @@ impl Reference {\n/// Get the registry name.\npub fn registry(&self) -> &str {\n- &self.whole[..self.slash]\n+ &self.whole[..self.repo_start]\n}\n/// Get the repository (a.k.a the image name) of this reference\npub fn repository(&self) -> &str {\n- match self.colon {\n- Some(c) => &self.whole[self.slash + 1..c],\n- None => &self.whole[self.slash + 1..],\n- }\n+ &self.whole[self.repo_start + 1..self.repo_end]\n}\n/// Get the tag for this reference.\npub fn tag(&self) -> Option<&str> {\n- match self.colon {\n- Some(c) => Some(&self.whole[c + 1..]),\n- None => None,\n+ match (self.digest_start, self.tag_start) {\n+ (Some(d), Some(t)) => Some(&self.whole[t + 1..d]),\n+ (None, Some(t)) => Some(&self.whole[t + 1..]),\n+ _ => None,\n}\n}\n- /// Convert a Reference to a v2 manifest URL.\n- pub fn to_v2_manifest_url(&self, protocol: &str) -> String {\n- format!(\n- \"{}://{}/v2/{}/manifests/{}\",\n- protocol,\n- self.registry(),\n- self.repository(),\n- self.tag().unwrap_or(\"latest\")\n- )\n+ /// Get the digest for this reference.\n+ pub fn digest(&self) -> Option<&str> {\n+ match self.digest_start {\n+ Some(c) => Some(&self.whole[c + 1..]),\n+ None => None,\n}\n-\n- /// Convert a Reference to a v2 blob (layer) URL.\n- pub fn to_v2_blob_url(&self, protocol: &str, digest: &str) -> String {\n- format!(\n- \"{}://{}/v2/{}/blobs/{}\",\n- protocol,\n- self.registry(),\n- self.repository(),\n- digest\n- )\n}\n}\nimpl TryFrom<String> for Reference {\ntype Error = anyhow::Error;\nfn try_from(string: String) -> Result<Self, Self::Error> {\n- let slash = string.find('/').ok_or_else(|| {\n+ let repo_start = string.find('/').ok_or_else(|| {\nanyhow::anyhow!(\n\"Failed to parse reference string '{}'. Expected at least one slash (/)\",\nstring\n)\n})?;\n- let colon = string[slash + 1..].find(':');\n+ let digest_start = string[repo_start + 1..].find('@').map(|i| repo_start + i + 1);\n+ let mut tag_start = string[repo_start + 1..].find(':').map(|i| repo_start + i + 1);\n+\n+ let repo_end = match (digest_start, tag_start) {\n+ (Some(d), Some(t)) => {\n+ if t > d {\n+ // tag_start is after digest_start, so no tag is actually present\n+ tag_start = None;\n+ d\n+ } else {\n+ t\n+ }\n+ },\n+ (Some(d), None) => d,\n+ (None, Some(t)) => t,\n+ (None, None) => string.len(),\n+ };\n+\nOk(Reference {\nwhole: string,\n- slash,\n- colon: colon.map(|c| slash + 1 + c),\n+ repo_start,\n+ repo_end,\n+ tag_start,\n+ digest_start,\n})\n}\n}\n@@ -111,6 +116,7 @@ mod tests {\n#[test]\nfn correctly_parses_string() {\n+ // Tag only (String)\nlet reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\".to_owned())\n.expect(\"Could not parse reference\");\n@@ -118,6 +124,7 @@ mod tests {\nassert_eq!(reference.repository(), \"hello\");\nassert_eq!(reference.tag(), Some(\"v1\"));\n+ // Tag only (&str)\nlet reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\")\n.expect(\"Could not parse reference\");\n@@ -125,6 +132,25 @@ mod tests {\nassert_eq!(reference.repository(), \"hello\");\nassert_eq!(reference.tag(), Some(\"v1\"));\n+ // Digest only\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n+ .expect(\"Could not parse reference\");\n+\n+ assert_eq!(reference.registry(), \"webassembly.azurecr.io\");\n+ assert_eq!(reference.repository(), \"hello\");\n+ assert_eq!(reference.tag(), None);\n+ assert_eq!(reference.digest(), Some(\"sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\"));\n+\n+ // Tag and digest\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n+ .expect(\"Could not parse reference\");\n+\n+ assert_eq!(reference.registry(), \"webassembly.azurecr.io\");\n+ assert_eq!(reference.repository(), \"hello\");\n+ assert_eq!(reference.tag(), Some(\"v1\"));\n+ assert_eq!(reference.digest(), Some(\"sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\"));\n+\n+ // No tag or digest\nlet reference =\nReference::try_from(\"webassembly.azurecr.io/hello\").expect(\"Could not parse reference\");\n@@ -132,24 +158,8 @@ mod tests {\nassert_eq!(reference.repository(), \"hello\");\nassert_eq!(reference.tag(), None);\n+ // Missing slash character\nReference::try_from(\"webassembly.azurecr.io:hello\")\n.expect_err(\"No slash should produce an error\");\n}\n-\n- #[test]\n- fn test_to_v2_manifest() {\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\".to_owned())\n- .expect(\"Could not parse reference\");\n- assert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello/manifests/v1\",\n- reference.to_v2_manifest_url(\"https\")\n- );\n-\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello\".to_owned())\n- .expect(\"Could not parse reference\");\n- assert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello/manifests/latest\", // TODO: confirm this is the right translation when no tag\n- reference.to_v2_manifest_url(\"https\")\n- );\n- }\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
feat(oci-distribution): support digest references
350,447
10.08.2020 20:08:24
14,400
5144d268068bd515c28621e5b5819bb0b7575f95
chore(oci-distribution): bump version
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -2039,7 +2039,7 @@ dependencies = [\n[[package]]\nname = \"oci-distribution\"\n-version = \"0.3.0\"\n+version = \"0.4.0\"\ndependencies = [\n\"anyhow\",\n\"futures-util\",\n" }, { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -46,7 +46,7 @@ env_logger = \"0.7\"\nkubelet = { path = \"./crates/kubelet\", version = \"0.4\", default-features = false, features = [\"cli\"] }\nwascc-provider = { path = \"./crates/wascc-provider\", version = \"0.4\", default-features = false }\nwasi-provider = { path = \"./crates/wasi-provider\", version = \"0.4\", default-features = false }\n-oci-distribution = { path = \"./crates/oci-distribution\", version = \"0.3\", default-features = false }\n+oci-distribution = { path = \"./crates/oci-distribution\", version = \"0.4\", default-features = false }\n[dev-dependencies]\nfutures = \"0.3\"\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/Cargo.toml", "new_path": "crates/kubelet/Cargo.toml", "diff": "@@ -54,7 +54,7 @@ native-tls = \"0.2\"\ntokio-tls = \"0.3\"\nthiserror = \"1.0\"\nlazy_static = \"1.4\"\n-oci-distribution = { path = \"../oci-distribution\", version = \"0.3\", default-features = false }\n+oci-distribution = { path = \"../oci-distribution\", version = \"0.4\", default-features = false }\nurl = \"2.1\"\nwarp = { version = \"0.2\", features = ['tls'] }\nhttp = \"0.2\"\n" }, { "change_type": "MODIFY", "old_path": "crates/oci-distribution/Cargo.toml", "new_path": "crates/oci-distribution/Cargo.toml", "diff": "[package]\nname = \"oci-distribution\"\n-version = \"0.3.0\"\n+version = \"0.4.0\"\nauthors = [\n\"Matt Butcher <[email protected]>\",\n\"Matthew Fisher <[email protected]>\",\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/Cargo.toml", "new_path": "crates/wascc-provider/Cargo.toml", "diff": "@@ -39,4 +39,4 @@ k8s-openapi = { version = \"0.8\", default-features = false, features = [\"v1_17\"]\nrand = \"0.7.3\"\n[dev-dependencies]\n-oci-distribution = { path = \"../oci-distribution\", version = \"0.3\" }\n+oci-distribution = { path = \"../oci-distribution\", version = \"0.4\" }\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/Cargo.toml", "new_path": "crates/wasi-provider/Cargo.toml", "diff": "@@ -36,4 +36,4 @@ futures = \"0.3\"\nk8s-openapi = { version = \"0.8\", default-features = false, features = [\"v1_17\"] }\n[dev-dependencies]\n-oci-distribution = { path = \"../oci-distribution\", version = \"0.3\" }\n+oci-distribution = { path = \"../oci-distribution\", version = \"0.4\" }\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
chore(oci-distribution): bump version
350,405
11.08.2020 14:11:17
-43,200
67fa2c949bc0bb1bd872ce50d882b2acbb80108e
OCI version function was showing as dead code
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -17,8 +17,6 @@ use std::collections::HashMap;\nuse tokio::io::{AsyncWrite, AsyncWriteExt};\nuse www_authenticate::{Challenge, ChallengeFields, RawChallenge, WwwAuthenticate};\n-const OCI_VERSION_KEY: &str = \"Docker-Distribution-Api-Version\";\n-\n/// The data for an image or module.\n#[derive(Clone)]\npub struct ImageData {\n@@ -98,23 +96,6 @@ impl Client {\n})\n}\n- /// According to the v2 specification, 200 and 401 error codes MUST return the\n- /// version. It appears that any other response code should be deemed non-v2.\n- ///\n- /// For this implementation, it will return v2 or an error result. If the error is a\n- /// `reqwest` error, the request itself failed. All other error messages mean that\n- /// v2 is not supported.\n- async fn version(&self, host: &str) -> anyhow::Result<String> {\n- let url = format!(\"{}://{}/v2/\", self.config.protocol.as_str(), host);\n- let res = self.client.get(&url).send().await?;\n- let dist_hdr = res.headers().get(OCI_VERSION_KEY);\n- let version = dist_hdr\n- .ok_or_else(|| anyhow::anyhow!(\"no header v2 found\"))?\n- .to_str()?\n- .to_owned();\n- Ok(version)\n- }\n-\n/// Perform an OAuth v2 auth request if necessary.\n///\n/// This performs authorization and then stores the token internally to be used\n@@ -399,16 +380,6 @@ mod test {\nconst HELLO_IMAGE: &str = \"webassembly.azurecr.io/hello-wasm:v1\";\n- #[tokio::test]\n- async fn test_version() {\n- let c = Client::default();\n- let ver = c\n- .version(\"webassembly.azurecr.io\")\n- .await\n- .expect(\"result from version request\");\n- assert_eq!(\"registry/2.0\".to_owned(), ver);\n- }\n-\n#[tokio::test]\nasync fn test_auth() {\nlet image = Reference::try_from(HELLO_IMAGE).expect(\"failed to parse reference\");\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
OCI version function was showing as dead code
350,447
12.08.2020 21:13:19
14,400
60e35142e5500a109bdfca2c391ff0d439a413ed
test(client): use table driven tests Adds coverage for image references missing tag/digest, as well as references with both tag and digest.
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -429,20 +429,28 @@ mod test {\nuse super::*;\nuse std::convert::TryFrom;\n- const HELLO_IMAGE_TAGGED: &str = \"webassembly.azurecr.io/hello-wasm:v1\";\n- const HELLO_IMAGE_DIGESTED: &str = \"webassembly.azurecr.io/hello-wasm@sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\";\n+ const HELLO_IMAGE_NO_TAG: &str = \"webassembly.azurecr.io/hello-wasm\";\n+ const HELLO_IMAGE_TAG: &str = \"webassembly.azurecr.io/hello-wasm:v1\";\n+ const HELLO_IMAGE_DIGEST: &str = \"webassembly.azurecr.io/hello-wasm@sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\";\n+ const HELLO_IMAGE_TAG_AND_DIGEST: &str = \"webassembly.azurecr.io/hello-wasm:v1@sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\";\n+ const TEST_IMAGES: &'static [&str] = &[\n+ HELLO_IMAGE_NO_TAG,\n+ HELLO_IMAGE_TAG,\n+ HELLO_IMAGE_DIGEST,\n+ HELLO_IMAGE_TAG_AND_DIGEST,\n+ ];\n#[test]\nfn test_to_v2_blob_url() {\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n+ let image = Reference::try_from(HELLO_IMAGE_TAG).expect(\"failed to parse reference\");\nlet blob_url = Client::default().to_v2_blob_url(\nimage.registry(),\nimage.repository(),\n\"sha256:deadbeef\",\n);\nassert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello-wasm/blobs/sha256:deadbeef\",\n- blob_url\n+ blob_url,\n+ \"https://webassembly.azurecr.io/v2/hello-wasm/blobs/sha256:deadbeef\"\n)\n}\n@@ -450,36 +458,15 @@ mod test {\nfn test_to_v2_manifest() {\nlet c = Client::default();\n- // Tag only\n- let reference = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"Could not parse reference\");\n- assert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/v1\",\n- c.to_v2_manifest_url(&reference)\n- );\n-\n- // Digest only\n- let reference =\n- Reference::try_from(HELLO_IMAGE_DIGESTED).expect(\"Could not parse reference\");\n- assert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\",\n- c.to_v2_manifest_url(&reference)\n- );\n-\n- // Tag and digest\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n- .expect(\"Could not parse reference\");\n- assert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello/manifests/sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\",\n- c.to_v2_manifest_url(&reference)\n- );\n-\n- // No tag or digest\n- let reference =\n- Reference::try_from(\"webassembly.azurecr.io/hello\").expect(\"Could not parse reference\");\n- assert_eq!(\n- \"https://webassembly.azurecr.io/v2/hello/manifests/latest\", // TODO: confirm this is the right translation when no tag\n- c.to_v2_manifest_url(&reference)\n- );\n+ for &(image, expected_uri) in [\n+ (HELLO_IMAGE_NO_TAG, \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/latest\"), // TODO: confirm this is the right translation when no tag\n+ (HELLO_IMAGE_TAG, \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/v1\"),\n+ (HELLO_IMAGE_DIGEST, \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\"),\n+ (HELLO_IMAGE_TAG_AND_DIGEST, \"https://webassembly.azurecr.io/v2/hello-wasm/manifests/sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\"),\n+ ].iter() {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n+ assert_eq!(c.to_v2_manifest_url(&reference), expected_uri);\n+ }\n}\n#[tokio::test]\n@@ -494,69 +481,62 @@ mod test {\n#[tokio::test]\nasync fn test_auth() {\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\nlet mut c = Client::default();\n- c.auth(&image, None)\n+ c.auth(&reference, None)\n.await\n.expect(\"result from auth request\");\n- let tok = c.tokens.get(image.registry()).expect(\"token is available\");\n+ let tok = c\n+ .tokens\n+ .get(reference.registry())\n+ .expect(\"token is available\");\n// We test that the token is longer than a minimal hash.\nassert!(tok.token.len() > 64);\n}\n+ }\n#[tokio::test]\nasync fn test_pull_manifest() {\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n// Currently, pull_manifest does not perform Authz, so this will fail.\nlet c = Client::default();\n- c.pull_manifest(&image)\n+ c.pull_manifest(&reference)\n.await\n.expect_err(\"pull manifest should fail\");\n// But this should pass\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\n- c.auth(&image, None).await.expect(\"authenticated\");\n+ c.auth(&reference, None).await.expect(\"authenticated\");\nlet (manifest, _) = c\n- .pull_manifest(&image)\n+ .pull_manifest(&reference)\n.await\n.expect(\"pull manifest should not fail\");\n// The test on the manifest checks all fields. This is just a brief sanity check.\nassert_eq!(manifest.schema_version, 2);\nassert!(!manifest.layers.is_empty());\n-\n- // Validate pulling by digest\n- let image = Reference::try_from(HELLO_IMAGE_DIGESTED).expect(\"failed to parse reference\");\n- let mut c = Client::default();\n- c.auth(&image, None).await.expect(\"authenticated\");\n- let (manifest, _) = c\n- .pull_manifest(&image)\n- .await\n- .expect(\"pull manifest should not fail\");\n- assert_eq!(\n- manifest.config.digest,\n- \"sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a\"\n- );\n- assert!(!manifest.layers.is_empty());\n+ }\n}\n#[tokio::test]\nasync fn test_fetch_digest() {\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n-\nlet mut c = Client::default();\n- c.fetch_manifest_digest(&image)\n+\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n+ c.fetch_manifest_digest(&reference)\n.await\n.expect(\"pull manifest should not fail\");\n// This should pass\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\nlet mut c = Client::default();\n- c.auth(&image, None).await.expect(\"authenticated\");\n+ c.auth(&reference, None).await.expect(\"authenticated\");\nlet digest = c\n- .fetch_manifest_digest(&image)\n+ .fetch_manifest_digest(&reference)\n.await\n.expect(\"pull manifest should not fail\");\n@@ -565,14 +545,17 @@ mod test {\n\"sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\"\n);\n}\n+ }\n#[tokio::test]\nasync fn test_pull_layer() {\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\nlet mut c = Client::default();\n- c.auth(&image, None).await.expect(\"authenticated\");\n+\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n+ c.auth(&reference, None).await.expect(\"authenticated\");\nlet (manifest, _) = c\n- .pull_manifest(&image)\n+ .pull_manifest(&reference)\n.await\n.expect(\"failed to pull manifest\");\n@@ -580,22 +563,27 @@ mod test {\nlet mut file: Vec<u8> = Vec::new();\nlet layer0 = &manifest.layers[0];\n- c.pull_layer(&image, &layer0.digest, &mut file)\n+ c.pull_layer(&reference, &layer0.digest, &mut file)\n.await\n.expect(\"Pull layer into vec\");\n// The manifest says how many bytes we should expect.\nassert_eq!(file.len(), layer0.size as usize);\n}\n+ }\n#[tokio::test]\nasync fn test_pull_image() {\n- let image = Reference::try_from(HELLO_IMAGE_TAGGED).expect(\"failed to parse reference\");\n- let mut c = Client::default();\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n- let image_data = c.pull_image(&image).await.expect(\"failed to pull manifest\");\n+ let image_data = Client::default()\n+ .pull_image(&reference)\n+ .await\n+ .expect(\"failed to pull manifest\");\nassert!(image_data.content.len() != 0);\nassert!(image_data.digest.is_some());\n}\n}\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
test(client): use table driven tests Adds coverage for image references missing tag/digest, as well as references with both tag and digest.
350,447
12.08.2020 21:50:02
14,400
2adcd7837b474a7af398edd48e5acf2cd143751a
test(client): disable latest ref in e2e tests
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -434,7 +434,10 @@ mod test {\nconst HELLO_IMAGE_DIGEST: &str = \"webassembly.azurecr.io/hello-wasm@sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\";\nconst HELLO_IMAGE_TAG_AND_DIGEST: &str = \"webassembly.azurecr.io/hello-wasm:v1@sha256:51d9b231d5129e3ffc267c9d455c49d789bf3167b611a07ab6e4b3304c96b0e7\";\nconst TEST_IMAGES: &'static [&str] = &[\n- HELLO_IMAGE_NO_TAG,\n+ // TODO(jlegrone): this image cannot be pulled currently because no `latest`\n+ // tag exists on the image repository. Re-enable this image\n+ // in tests once `latest` is published.\n+ // HELLO_IMAGE_NO_TAG,\nHELLO_IMAGE_TAG,\nHELLO_IMAGE_DIGEST,\nHELLO_IMAGE_TAG_AND_DIGEST,\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
test(client): disable latest ref in e2e tests
350,405
14.08.2020 09:57:07
-43,200
85195ced0404a4818af79115f9b54c6666e941e5
Self-contained integration tester
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -1630,10 +1630,12 @@ dependencies = [\n\"dirs\",\n\"env_logger\",\n\"futures\",\n+ \"hostname\",\n\"k8s-openapi\",\n\"kube\",\n\"kubelet\",\n\"oci-distribution\",\n+ \"regex\",\n\"reqwest\",\n\"serde\",\n\"serde_derive\",\n" }, { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -47,6 +47,9 @@ kubelet = { path = \"./crates/kubelet\", version = \"0.4\", default-features = false\nwascc-provider = { path = \"./crates/wascc-provider\", version = \"0.4\", default-features = false }\nwasi-provider = { path = \"./crates/wasi-provider\", version = \"0.4\", default-features = false }\noci-distribution = { path = \"./crates/oci-distribution\", version = \"0.3\", default-features = false }\n+dirs = \"2.0\"\n+hostname = \"0.3\"\n+regex = \"1.3\"\n[dev-dependencies]\nfutures = \"0.3\"\n@@ -55,7 +58,6 @@ serde_json = \"1.0\"\nserde = \"1.0\"\nk8s-openapi = { version = \"0.8\", default-features = false, features = [\"v1_17\"] }\nreqwest = { version = \"0.10\", default-features = false }\n-dirs = \"2.0\"\ntempfile = \"3.1\"\n[workspace]\n@@ -70,3 +72,7 @@ path = \"src/krustlet-wascc.rs\"\n[[bin]]\nname = \"krustlet-wasi\"\npath = \"src/krustlet-wasi.rs\"\n+\n+[[bin]]\n+name = \"oneclick\"\n+path = \"tests/oneclick/src/main.rs\"\n" }, { "change_type": "MODIFY", "old_path": "docs/community/developers.md", "new_path": "docs/community/developers.md", "diff": "@@ -148,6 +148,27 @@ And in terminal 3:\n$ just test-e2e\n```\n+You can run the integration tests without creating additional terminals or\n+manually running the kubelets by running:\n+\n+```\n+$ just test-e2e-standalone\n+```\n+\n+This:\n+\n+* Bootstraps and approves certificates if necessary\n+* Runs the WASI and WASCC kubelets in the background\n+* Runs the integration tests\n+* Terminates the kubelets when the integration tests complete\n+* Reports test failures, and saves the kubelet logs if any tests failed\n+\n+You **will** still need to set `KRUSTLET_NODE_IP` because the tester doesn't know what\n+kind of Kubernetes cluster you're using and so doesn't know how to infer a node IP.\n+\n+_WARNING:_ The standalone integration tester has not been, er, tested on Windows.\n+Hashtag irony.\n+\n## Creating your own Kubelets with Krustlet\nIf you want to create your own Kubelet based on Krustlet, all you need to do is implement a\n" }, { "change_type": "MODIFY", "old_path": "justfile", "new_path": "justfile", "diff": "@@ -16,6 +16,9 @@ test:\ntest-e2e:\ncargo test --test integration_tests\n+test-e2e-standalone:\n+ cargo run --bin oneclick\n+\nrun-wascc +FLAGS='': bootstrap\nKUBECONFIG=$(eval echo $CONFIG_DIR)/kubeconfig-wascc cargo run --bin krustlet-wascc {{FLAGS}} -- --node-name krustlet-wascc --port 3000 --bootstrap-file $(eval echo $CONFIG_DIR)/bootstrap.conf --cert-file $(eval echo $CONFIG_DIR)/krustlet-wascc.crt --private-key-file $(eval echo $CONFIG_DIR)/krustlet-wascc.key\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/oneclick/src/main.rs", "diff": "+use std::io::BufRead;\n+\n+enum BootstrapReadiness {\n+ AlreadyBootstrapped,\n+ NeedBootstrapAndApprove,\n+ NeedManualCleanup,\n+}\n+\n+const EXIT_CODE_TESTS_PASSED: i32 = 0;\n+const EXIT_CODE_TESTS_FAILED: i32 = 1;\n+const EXIT_CODE_NEED_MANUAL_CLEANUP: i32 = 2;\n+const EXIT_CODE_BUILD_FAILED: i32 = 3;\n+\n+fn main() {\n+ println!(\"Ensuring all binaries are built...\");\n+\n+ let build_result = build_workspace();\n+\n+ match build_result {\n+ Ok(()) => {\n+ println!(\"Build succeeded\");\n+ }\n+ Err(e) => {\n+ eprintln!(\"{}\", e);\n+ eprintln!(\"Build FAILED\");\n+ std::process::exit(EXIT_CODE_BUILD_FAILED);\n+ }\n+ }\n+\n+ println!(\"Preparing for bootstrap...\");\n+\n+ let readiness = prepare_for_bootstrap();\n+\n+ match readiness {\n+ BootstrapReadiness::AlreadyBootstrapped => {\n+ println!(\"Already bootstrapped\");\n+ }\n+ BootstrapReadiness::NeedBootstrapAndApprove => {\n+ println!(\"Bootstrap required\");\n+ }\n+ BootstrapReadiness::NeedManualCleanup => {\n+ eprintln!(\"Bootstrap directory and CSRs need manual clean up\");\n+ std::process::exit(EXIT_CODE_NEED_MANUAL_CLEANUP);\n+ }\n+ }\n+\n+ if matches!(readiness, BootstrapReadiness::NeedBootstrapAndApprove) {\n+ println!(\"Running bootstrap script...\");\n+ let bootstrap_result = run_bootstrap();\n+ match bootstrap_result {\n+ Ok(()) => {\n+ println!(\"Bootstrap script succeeded\");\n+ }\n+ Err(e) => {\n+ eprintln!(\"Running bootstrap script failed: {}\", e);\n+ std::process::exit(EXIT_CODE_NEED_MANUAL_CLEANUP);\n+ }\n+ }\n+ }\n+\n+ let test_result = run_tests(readiness);\n+\n+ println!(\"All complete\");\n+\n+ let exit_code = match test_result {\n+ Ok(()) => EXIT_CODE_TESTS_PASSED,\n+ Err(_) => EXIT_CODE_TESTS_FAILED,\n+ };\n+\n+ std::process::exit(exit_code);\n+}\n+\n+fn config_dir() -> std::path::PathBuf {\n+ let home_dir = dirs::home_dir().expect(\"Can't get home dir\"); // TODO: allow override of config dir\n+ home_dir.join(\".krustlet/config\")\n+}\n+\n+fn config_file_path_str(file_name: impl AsRef<std::path::Path>) -> String {\n+ config_dir().join(file_name).to_str().unwrap().to_owned()\n+}\n+\n+fn build_workspace() -> anyhow::Result<()> {\n+ let build_result = std::process::Command::new(\"cargo\")\n+ .args(&[\"build\"])\n+ .output()?;\n+\n+ match build_result.status.success() {\n+ true => Ok(()),\n+ false => Err(anyhow::anyhow!(\n+ \"{}\",\n+ String::from_utf8(build_result.stderr).unwrap()\n+ )),\n+ }\n+}\n+\n+fn prepare_for_bootstrap() -> BootstrapReadiness {\n+ let host_name = hostname::get()\n+ .expect(\"Can't get host name\")\n+ .into_string()\n+ .expect(\"Can't get host name\");\n+\n+ let cert_paths: Vec<_> = vec![\n+ \"krustlet-wasi.crt\",\n+ \"krustlet-wasi.key\",\n+ \"krustlet-wascc.crt\",\n+ \"krustlet-wascc.key\",\n+ ]\n+ .iter()\n+ .map(|f| config_dir().join(f))\n+ .collect();\n+\n+ let status = all_or_none(cert_paths);\n+\n+ match status {\n+ AllOrNone::AllExist => {\n+ return BootstrapReadiness::AlreadyBootstrapped;\n+ }\n+ AllOrNone::NoneExist => (),\n+ AllOrNone::Error => {\n+ return BootstrapReadiness::NeedManualCleanup;\n+ }\n+ };\n+\n+ // We are not bootstrapped, but there may be existing CSRs around\n+\n+ // TODO: allow override of host names\n+ let wasi_host_name = &host_name;\n+ let wascc_host_name = &host_name;\n+\n+ let wasi_cert_name = format!(\"{}-tls\", wasi_host_name);\n+ let wascc_cert_name = format!(\"{}-tls\", wascc_host_name);\n+\n+ let csr_spawn_deletes: Vec<_> = vec![\n+ \"krustlet-wasi\",\n+ \"krustlet-wascc\",\n+ &wasi_cert_name,\n+ &wascc_cert_name,\n+ ]\n+ .iter()\n+ .map(delete_csr)\n+ .collect();\n+\n+ let (csr_deletions, csr_spawn_delete_errors) = csr_spawn_deletes.partition_success();\n+\n+ if !csr_spawn_delete_errors.is_empty() {\n+ return BootstrapReadiness::NeedManualCleanup;\n+ }\n+\n+ let csr_deletion_results: Vec<_> = csr_deletions\n+ .into_iter()\n+ .map(|c| c.wait_with_output())\n+ .collect();\n+\n+ let (csr_deletion_outputs, csr_run_deletion_failures) =\n+ csr_deletion_results.partition_success();\n+\n+ if !csr_run_deletion_failures.is_empty() {\n+ return BootstrapReadiness::NeedManualCleanup;\n+ }\n+\n+ if csr_deletion_outputs.iter().any(|o| !is_resource_gone(o)) {\n+ return BootstrapReadiness::NeedManualCleanup;\n+ }\n+\n+ // We have now deleted all the local certificate files, and all the CSRs that\n+ // might get in the way of our re-bootstrapping. Let the caller know they\n+ // will need to re-approve once the new CSRs come up.\n+ return BootstrapReadiness::NeedBootstrapAndApprove;\n+}\n+\n+enum AllOrNone {\n+ AllExist,\n+ NoneExist,\n+ Error,\n+}\n+\n+fn all_or_none(files: Vec<std::path::PathBuf>) -> AllOrNone {\n+ let (exist, missing): (Vec<_>, Vec<_>) = files.iter().partition(|f| f.exists());\n+\n+ if missing.is_empty() {\n+ return AllOrNone::AllExist;\n+ }\n+\n+ for f in exist {\n+ if matches!(std::fs::remove_file(f), Err(_)) {\n+ return AllOrNone::Error;\n+ }\n+ }\n+\n+ AllOrNone::NoneExist\n+}\n+\n+fn delete_csr(csr_name: impl AsRef<str>) -> std::io::Result<std::process::Child> {\n+ std::process::Command::new(\"kubectl\")\n+ .args(&[\"delete\", \"csr\", csr_name.as_ref()])\n+ .stderr(std::process::Stdio::piped())\n+ .stdout(std::process::Stdio::piped())\n+ .spawn()\n+}\n+\n+trait ResultSequence {\n+ type SuccessItem;\n+ type FailureItem;\n+ fn partition_success(self) -> (Vec<Self::SuccessItem>, Vec<Self::FailureItem>);\n+}\n+\n+impl<T, E: std::fmt::Debug> ResultSequence for Vec<Result<T, E>> {\n+ type SuccessItem = T;\n+ type FailureItem = E;\n+ fn partition_success(self) -> (Vec<Self::SuccessItem>, Vec<Self::FailureItem>) {\n+ let (success_results, error_results): (Vec<_>, Vec<_>) =\n+ self.into_iter().partition(|r| r.is_ok());\n+ let success_values = success_results.into_iter().map(|r| r.unwrap()).collect();\n+ let error_values = error_results\n+ .into_iter()\n+ .map(|r| r.err().unwrap())\n+ .collect();\n+ (success_values, error_values)\n+ }\n+}\n+\n+fn is_resource_gone(kubectl_output: &std::process::Output) -> bool {\n+ kubectl_output.status.success()\n+ || match String::from_utf8(kubectl_output.stderr.clone()) {\n+ Ok(s) => s.contains(\"NotFound\"),\n+ _ => false,\n+ }\n+}\n+\n+fn run_bootstrap() -> anyhow::Result<()> {\n+ let (shell, ext) = match std::env::consts::OS {\n+ \"windows\" => (\"powershell.exe\", \"ps1\"),\n+ \"linux\" | \"macos\" => (\"bash\", \"sh\"),\n+ os => Err(anyhow::anyhow!(\"Unsupported OS {}\", os))?,\n+ };\n+\n+ let repo_root = std::env!(\"CARGO_MANIFEST_DIR\");\n+\n+ let bootstrap_script = format!(\"{}/docs/howto/assets/bootstrap.{}\", repo_root, ext);\n+ let bootstrap_output = std::process::Command::new(shell)\n+ .arg(bootstrap_script)\n+ .env(\"CONFIG_DIR\", config_dir())\n+ .stdout(std::process::Stdio::piped())\n+ .stderr(std::process::Stdio::piped())\n+ .output()?;\n+\n+ match bootstrap_output.status.code() {\n+ Some(0) => Ok(()),\n+ Some(e) => Err(anyhow::anyhow!(\n+ \"Bootstrap error {}: {}\",\n+ e,\n+ String::from_utf8_lossy(&bootstrap_output.stderr)\n+ )),\n+ None => Err(anyhow::anyhow!(\n+ \"Bootstrap error (no exit code): {}\",\n+ String::from_utf8_lossy(&bootstrap_output.stderr)\n+ )),\n+ }\n+}\n+\n+fn launch_kubelet(\n+ name: &str,\n+ kubeconfig_suffix: &str,\n+ kubelet_port: i32,\n+ need_csr: bool,\n+) -> anyhow::Result<OwnedChildProcess> {\n+ // run the kubelet as a background process using the\n+ // same cmd line as in the justfile:\n+ // KUBECONFIG=$(eval echo $CONFIG_DIR)/kubeconfig-wasi cargo run --bin krustlet-wasi {{FLAGS}} -- --node-name krustlet-wasi --port 3001 --bootstrap-file $(eval echo $CONFIG_DIR)/bootstrap.conf --cert-file $(eval echo $CONFIG_DIR)/krustlet-wasi.crt --private-key-file $(eval echo $CONFIG_DIR)/krustlet-wasi.key\n+ let bootstrap_conf = config_file_path_str(\"bootstrap.conf\");\n+ let cert = config_file_path_str(format!(\"{}.crt\", name));\n+ let private_key = config_file_path_str(format!(\"{}.key\", name));\n+ let kubeconfig = config_file_path_str(format!(\"kubeconfig-{}\", kubeconfig_suffix));\n+ let port_arg = format!(\"{}\", kubelet_port);\n+\n+ let repo_root = std::path::PathBuf::from(env!(\"CARGO_MANIFEST_DIR\"));\n+ let bin_path = repo_root.join(\"target/debug\").join(name);\n+\n+ let mut launch_kubelet_process = std::process::Command::new(bin_path)\n+ .args(&[\n+ \"--node-name\",\n+ name,\n+ \"--port\",\n+ &port_arg,\n+ \"--bootstrap-file\",\n+ &bootstrap_conf,\n+ \"--cert-file\",\n+ &cert,\n+ \"--private-key-file\",\n+ &private_key,\n+ ])\n+ .env(\"KUBECONFIG\", kubeconfig)\n+ .env(\n+ \"RUST_LOG\",\n+ \"wascc_host=debug,wascc_provider=debug,wasi_provider=debug,main=debug\",\n+ )\n+ .stdout(std::process::Stdio::piped())\n+ .stderr(std::process::Stdio::piped())\n+ .spawn()?;\n+\n+ println!(\"Kubelet process {} launched\", name);\n+\n+ if need_csr {\n+ println!(\"Waiting for kubelet {} to generate CSR\", name);\n+ let stdout = launch_kubelet_process.stdout.as_mut().unwrap();\n+ wait_for_tls_certificate_approval(stdout)?;\n+ println!(\"Finished bootstrapping for kubelet {}\", name);\n+ }\n+\n+ let terminator = OwnedChildProcess {\n+ terminated: false,\n+ child: launch_kubelet_process,\n+ };\n+ Ok(terminator)\n+}\n+\n+fn wait_for_tls_certificate_approval(stdout: impl std::io::Read) -> anyhow::Result<()> {\n+ let reader = std::io::BufReader::new(stdout);\n+ for (_, line) in reader.lines().enumerate() {\n+ match line {\n+ Ok(line_text) => {\n+ println!(\"Kubelet printed: {}\", line_text);\n+ if line_text == \"BOOTSTRAP: received TLS certificate approval: continuing\" {\n+ return Ok(());\n+ }\n+ let re = regex::Regex::new(r\"^BOOTSTRAP: TLS certificate requires manual approval. Run kubectl certificate approve (\\S+)$\").unwrap();\n+ match re.captures(&line_text) {\n+ None => (),\n+ Some(captures) => {\n+ let csr_name = &captures[1];\n+ approve_csr(csr_name)?\n+ }\n+ }\n+ }\n+ Err(e) => eprintln!(\"Error reading kubelet stdout: {}\", e),\n+ }\n+ }\n+ println!(\"End of kubelet output with no approval\");\n+ Err(anyhow::anyhow!(\"End of kubelet output with no approval\"))\n+}\n+\n+fn approve_csr(csr_name: &str) -> anyhow::Result<()> {\n+ println!(\"Approving CSR {}\", csr_name);\n+ let approve_process = std::process::Command::new(\"kubectl\")\n+ .args(&[\"certificate\", \"approve\", csr_name])\n+ .stderr(std::process::Stdio::piped())\n+ .stdout(std::process::Stdio::piped())\n+ .output()?;\n+ if !approve_process.status.success() {\n+ Err(anyhow::anyhow!(\n+ \"Error approving CSR {}: {}\",\n+ csr_name,\n+ String::from_utf8(approve_process.stderr).unwrap()\n+ ))\n+ } else {\n+ println!(\"Approved CSR {}\", csr_name);\n+ clean_up_csr(csr_name)\n+ }\n+}\n+\n+fn clean_up_csr(csr_name: &str) -> anyhow::Result<()> {\n+ println!(\"Cleaning up approved CSR {}\", csr_name);\n+ let clean_up_process = std::process::Command::new(\"kubectl\")\n+ .args(&[\"delete\", \"csr\", csr_name])\n+ .stderr(std::process::Stdio::piped())\n+ .stdout(std::process::Stdio::piped())\n+ .output()?;\n+ if !clean_up_process.status.success() {\n+ Err(anyhow::anyhow!(\n+ \"Error cleaning up CSR {}: {}\",\n+ csr_name,\n+ String::from_utf8(clean_up_process.stderr).unwrap()\n+ ))\n+ } else {\n+ println!(\"Cleaned up approved CSR {}\", csr_name);\n+ Ok(())\n+ }\n+}\n+\n+struct OwnedChildProcess {\n+ terminated: bool,\n+ child: std::process::Child,\n+}\n+\n+impl OwnedChildProcess {\n+ fn terminate(&mut self) -> anyhow::Result<()> {\n+ match self.child.kill().and_then(|_| self.child.wait()) {\n+ Ok(_) => {\n+ self.terminated = true;\n+ Ok(())\n+ }\n+ Err(e) => Err(anyhow::anyhow!(\n+ \"Failed to terminate spawned kubelet process: {}\",\n+ e\n+ )),\n+ }\n+ }\n+}\n+\n+impl Drop for OwnedChildProcess {\n+ fn drop(&mut self) {\n+ if !self.terminated {\n+ match self.terminate() {\n+ Ok(()) => (),\n+ Err(e) => eprintln!(\"{}\", e),\n+ }\n+ }\n+ }\n+}\n+\n+fn run_tests(readiness: BootstrapReadiness) -> anyhow::Result<()> {\n+ let wasi_process_result = launch_kubelet(\n+ \"krustlet-wasi\",\n+ \"wasi\",\n+ 3001,\n+ matches!(readiness, BootstrapReadiness::NeedBootstrapAndApprove),\n+ );\n+ let wascc_process_result = launch_kubelet(\n+ \"krustlet-wascc\",\n+ \"wascc\",\n+ 3000,\n+ matches!(readiness, BootstrapReadiness::NeedBootstrapAndApprove),\n+ );\n+\n+ for process in &[&wasi_process_result, &wascc_process_result] {\n+ match process {\n+ Err(e) => {\n+ eprintln!(\"Error running kubelet process: {}\", e);\n+ return Err(anyhow::anyhow!(\"Error running kubelet process: {}\", e));\n+ }\n+ Ok(_) => println!(\"Running kubelet process\"),\n+ }\n+ }\n+\n+ let test_result = run_test_suite();\n+\n+ let mut wasi_process = wasi_process_result.unwrap();\n+ let mut wascc_process = wascc_process_result.unwrap();\n+\n+ if matches!(test_result, Err(_)) {\n+ // TODO: ideally we shouldn't have to wait for termination before getting logs\n+ let terminate_result = wasi_process\n+ .terminate()\n+ .and_then(|_| wascc_process.terminate());\n+ match terminate_result {\n+ Ok(_) => {\n+ let wasi_log_destination = std::path::PathBuf::from(\"./krustlet-wasi-e2e\");\n+ capture_kubelet_logs(\n+ \"krustlet-wasi\",\n+ &mut wasi_process.child,\n+ wasi_log_destination,\n+ );\n+ let wascc_log_destination = std::path::PathBuf::from(\"./krustlet-wascc-e2e\");\n+ capture_kubelet_logs(\n+ \"krustlet-wascc\",\n+ &mut wascc_process.child,\n+ wascc_log_destination,\n+ );\n+ }\n+ Err(e) => {\n+ eprintln!(\"{}\", e);\n+ eprintln!(\"Can't capture kubelet logs as they didn't terminate\");\n+ }\n+ }\n+ }\n+\n+ test_result\n+}\n+\n+fn run_test_suite() -> anyhow::Result<()> {\n+ println!(\"Launching integration tests\");\n+ let test_process = std::process::Command::new(\"cargo\")\n+ .args(&[\"test\", \"--test\", \"integration_tests\"])\n+ .stderr(std::process::Stdio::piped())\n+ .stdout(std::process::Stdio::piped())\n+ .spawn()?;\n+ println!(\"Integration tests running\");\n+ // TODO: consider streaming progress\n+ // TODO: capture pod logs: probably requires cooperation from the test\n+ // process\n+ let test_process_result = test_process.wait_with_output()?;\n+ if test_process_result.status.success() {\n+ println!(\"Integration tests PASSED\");\n+ Ok(())\n+ } else {\n+ let stdout = String::from_utf8(test_process_result.stdout)?;\n+ eprintln!(\"{}\", stdout);\n+ let stderr = String::from_utf8(test_process_result.stderr)?;\n+ eprintln!(\"{}\", stderr);\n+ eprintln!(\"Integration tests FAILED\");\n+ Err(anyhow::anyhow!(stderr))\n+ }\n+}\n+\n+fn capture_kubelet_logs(\n+ kubelet_name: &str,\n+ kubelet_process: &mut std::process::Child,\n+ destination: std::path::PathBuf,\n+) {\n+ let stdout = kubelet_process.stdout.as_mut().unwrap();\n+ let stdout_path = destination.with_extension(\"stdout.txt\");\n+ write_kubelet_log_to_file(kubelet_name, stdout, stdout_path);\n+\n+ let stderr = kubelet_process.stderr.as_mut().unwrap();\n+ let stderr_path = destination.with_extension(\"stderr.txt\");\n+ write_kubelet_log_to_file(kubelet_name, stderr, stderr_path);\n+}\n+\n+fn write_kubelet_log_to_file(\n+ kubelet_name: &str,\n+ log: &mut impl std::io::Read,\n+ file_path: std::path::PathBuf,\n+) {\n+ let mut file_result = std::fs::File::create(file_path);\n+ match file_result {\n+ Ok(ref mut file) => {\n+ let write_result = std::io::copy(log, file);\n+ match write_result {\n+ Ok(_) => (),\n+ Err(e) => eprintln!(\"Can't capture {} output: {}\", kubelet_name, e),\n+ }\n+ }\n+ Err(e) => {\n+ eprintln!(\"Can't capture {} output: {}\", kubelet_name, e);\n+ }\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Self-contained integration tester (#343)
350,447
13.08.2020 18:48:58
14,400
f3ffb70c815cfb9504a3d41ce6253806f23f485a
test(reference): break test cases into separate functions
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -115,61 +115,82 @@ impl Into<String> for Reference {\n}\n#[cfg(test)]\n-mod tests {\n+mod test {\nuse super::*;\n- #[test]\n- fn correctly_parses_string() {\n- // Tag only (String)\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\".to_owned())\n- .expect(\"Could not parse reference\");\n-\n- assert_eq!(reference.registry(), \"webassembly.azurecr.io\");\n- assert_eq!(reference.repository(), \"hello\");\n- assert_eq!(reference.tag(), Some(\"v1\"));\n+ mod parse {\n+ use super::*;\n- // Tag only (&str)\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\")\n- .expect(\"Could not parse reference\");\n+ fn must_parse(image: &str) -> Reference {\n+ Reference::try_from(image).expect(\"could not parse reference\")\n+ }\n+ fn validate_registry_and_repository(reference: &Reference) {\nassert_eq!(reference.registry(), \"webassembly.azurecr.io\");\nassert_eq!(reference.repository(), \"hello\");\n- assert_eq!(reference.tag(), Some(\"v1\"));\n+ }\n- // Digest only\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n- .expect(\"Could not parse reference\");\n+ fn validate_tag(reference: &Reference) {\n+ assert_eq!(reference.tag(), Some(\"v1\"));\n+ }\n- assert_eq!(reference.registry(), \"webassembly.azurecr.io\");\n- assert_eq!(reference.repository(), \"hello\");\n- assert_eq!(reference.tag(), None);\n+ fn validate_digest(reference: &Reference) {\nassert_eq!(\nreference.digest(),\nSome(\"sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n);\n+ }\n- // Tag and digest\n- let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n- .expect(\"Could not parse reference\");\n+ #[test]\n+ fn owned_string() {\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\".to_owned())\n+ .expect(\"could not parse reference\");\n- assert_eq!(reference.registry(), \"webassembly.azurecr.io\");\n- assert_eq!(reference.repository(), \"hello\");\n- assert_eq!(reference.tag(), Some(\"v1\"));\n- assert_eq!(\n- reference.digest(),\n- Some(\"sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\")\n- );\n+ validate_registry_and_repository(&reference);\n+ validate_tag(&reference);\n+ assert_eq!(reference.digest(), None);\n+ }\n- // No tag or digest\n- let reference =\n- Reference::try_from(\"webassembly.azurecr.io/hello\").expect(\"Could not parse reference\");\n+ #[test]\n+ fn tag_only() {\n+ let reference = must_parse(\"webassembly.azurecr.io/hello:v1\");\n- assert_eq!(reference.registry(), \"webassembly.azurecr.io\");\n- assert_eq!(reference.repository(), \"hello\");\n+ validate_registry_and_repository(&reference);\n+ validate_tag(&reference);\n+ assert_eq!(reference.digest(), None);\n+ }\n+\n+ #[test]\n+ fn digest_only() {\n+ let reference = must_parse(\"webassembly.azurecr.io/hello@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\");\n+\n+ validate_registry_and_repository(&reference);\n+ validate_digest(&reference);\n+ assert_eq!(reference.tag(), None);\n+ }\n+\n+ #[test]\n+ fn tag_and_digest() {\n+ let reference = must_parse(\"webassembly.azurecr.io/hello:v1@sha256:f29dba55022eec8c0ce1cbfaaed45f2352ab3fbbb1cdcd5ea30ca3513deb70c9\");\n+\n+ validate_registry_and_repository(&reference);\n+ validate_tag(&reference);\n+ validate_digest(&reference);\n+ }\n+\n+ #[test]\n+ fn no_tag_or_digest() {\n+ let reference = must_parse(\"webassembly.azurecr.io/hello\");\n+\n+ validate_registry_and_repository(&reference);\nassert_eq!(reference.tag(), None);\n+ assert_eq!(reference.digest(), None);\n+ }\n- // Missing slash character\n+ #[test]\n+ fn missing_slash_char() {\nReference::try_from(\"webassembly.azurecr.io:hello\")\n- .expect_err(\"No slash should produce an error\");\n+ .expect_err(\"no slash should produce an error\");\n+ }\n}\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
test(reference): break test cases into separate functions
350,447
13.08.2020 22:45:38
14,400
6bf96423c1ed382cbb4f7081089c0a3ea2433d9e
refactor(reference): separate tag_start and repo_end parsing
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -69,25 +69,28 @@ impl TryFrom<String> for Reference {\nstring\n)\n})?;\n+ let first_colon = string[repo_start + 1..].find(':').map(|i| repo_start + i);\nlet digest_start = string[repo_start + 1..]\n.find('@')\n.map(|i| repo_start + i + 1);\n- let mut tag_start = string[repo_start + 1..]\n- .find(':')\n- .map(|i| repo_start + i + 1);\n-\n- let repo_end = match (digest_start, tag_start) {\n- (Some(d), Some(t)) => {\n- if t > d {\n- // tag_start is after digest_start, so no tag is actually present\n- tag_start = None;\n- d\n- } else {\n- t\n- }\n+ let tag_start = match (digest_start, first_colon) {\n+ // Check if a colon comes before a digest delimeter, indicating\n+ // that image ref is in the form registry/repo:tag@digest\n+ (Some(ds), Some(fc)) => match fc < ds {\n+ true => Some(fc),\n+ false => None,\n+ },\n+ // No digest delimeter was found but a colon is present, so ref\n+ // must be in the form registry/repo:tag\n+ (None, Some(fc)) => Some(fc),\n+ // No tag delimeter was found\n+ _ => None,\n}\n- (Some(d), None) => d,\n- (None, Some(t)) => t,\n+ .map(|i| i + 1);\n+ let repo_end = match (digest_start, tag_start) {\n+ (Some(_), Some(ts)) => ts,\n+ (None, Some(ts)) => ts,\n+ (Some(ds), None) => ds,\n(None, None) => string.len(),\n};\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
refactor(reference): separate tag_start and repo_end parsing
350,405
19.08.2020 10:19:38
-43,200
f77107880d4d1ec6f62fbbe41ccc657ce92b64c9
Mount individual items from configmaps or secrets
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/volume/mod.rs", "new_path": "crates/kubelet/src/volume/mod.rs", "diff": "@@ -5,7 +5,7 @@ use std::ops::Deref;\nuse std::path::PathBuf;\nuse k8s_openapi::api::core::v1::Volume as KubeVolume;\n-use k8s_openapi::api::core::v1::{ConfigMap, Secret};\n+use k8s_openapi::api::core::v1::{ConfigMap, KeyToPath, Secret};\nuse k8s_openapi::ByteString;\nuse kube::api::Api;\nuse log::{debug, error};\n@@ -120,6 +120,7 @@ async fn configure(\nnamespace,\nclient,\npath,\n+ &cm.items,\n)\n.await\n} else if let Some(s) = &vol.secret {\n@@ -130,6 +131,7 @@ async fn configure(\nnamespace,\nclient,\npath,\n+ &s.items,\n)\n.await\n} else if let Some(hostpath) = &vol.host_path {\n@@ -148,14 +150,20 @@ async fn populate_from_secret(\nnamespace: &str,\nclient: &kube::Client,\npath: &PathBuf,\n+ items: &Option<Vec<KeyToPath>>,\n) -> anyhow::Result<Type> {\ntokio::fs::create_dir_all(path).await?;\nlet secret_client: Api<Secret> = Api::namespaced(client.clone(), namespace);\nlet secret = secret_client.get(name).await?;\nlet data = secret.data.unwrap_or_default();\nlet data = data.iter().map(|(key, ByteString(data))| async move {\n- let file_path = path.join(key);\n+ match mount_path_for(key, items) {\n+ Some(mount_path) => {\n+ let file_path = path.join(mount_path);\ntokio::fs::write(file_path, &data).await\n+ }\n+ None => Ok(()),\n+ }\n});\nfutures::future::join_all(data)\n.await\n@@ -170,20 +178,31 @@ async fn populate_from_config_map(\nnamespace: &str,\nclient: &kube::Client,\npath: &PathBuf,\n+ items: &Option<Vec<KeyToPath>>,\n) -> anyhow::Result<Type> {\ntokio::fs::create_dir_all(path).await?;\nlet cm_client: Api<ConfigMap> = Api::namespaced(client.clone(), namespace);\nlet config_map = cm_client.get(name).await?;\nlet binary_data = config_map.binary_data.unwrap_or_default();\nlet binary_data = binary_data.iter().map(|(key, data)| async move {\n- let file_path = path.join(key);\n+ match mount_path_for(key, items) {\n+ Some(mount_path) => {\n+ let file_path = path.join(mount_path);\ntokio::fs::write(file_path, &data.0).await\n+ }\n+ None => Ok(()),\n+ }\n});\nlet binary_data = futures::future::join_all(binary_data);\nlet data = config_map.data.unwrap_or_default();\nlet data = data.iter().map(|(key, data)| async move {\n- let file_path = path.join(key);\n+ match mount_path_for(key, items) {\n+ Some(mount_path) => {\n+ let file_path = path.join(mount_path);\ntokio::fs::write(file_path, data).await\n+ }\n+ None => Ok(()),\n+ }\n});\nlet data = futures::future::join_all(data);\nlet (binary_data, data) = futures::future::join(binary_data, data).await;\n@@ -198,3 +217,13 @@ async fn populate_from_config_map(\nfn pod_dir_name(pod: &Pod) -> String {\nformat!(\"{}-{}\", pod.name(), pod.namespace())\n}\n+\n+fn mount_path_for(key: &String, items_to_mount: &Option<Vec<KeyToPath>>) -> Option<String> {\n+ match items_to_mount {\n+ None => Some(key.to_string()),\n+ Some(items) => items\n+ .iter()\n+ .find(|kp| &kp.key == key)\n+ .map(|kp| kp.path.to_string()),\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "demos/wasi/wasmerciser/Cargo.lock", "new_path": "demos/wasi/wasmerciser/Cargo.lock", "diff": "@@ -8,7 +8,7 @@ checksum = \"85bb70cc08ec97ca5450e6eba421deeea5f172c0fc61f78b5357b2a8e8be195f\"\n[[package]]\nname = \"wasmerciser\"\n-version = \"0.1.0\"\n+version = \"0.2.0\"\ndependencies = [\n\"anyhow\",\n]\n" }, { "change_type": "MODIFY", "old_path": "demos/wasi/wasmerciser/Cargo.toml", "new_path": "demos/wasi/wasmerciser/Cargo.toml", "diff": "[package]\nname = \"wasmerciser\"\n-version = \"0.1.0\"\n+version = \"0.2.0\"\nauthors = [\"itowlson <[email protected]>\"]\nedition = \"2018\"\n" }, { "change_type": "MODIFY", "old_path": "demos/wasi/wasmerciser/src/main.rs", "new_path": "demos/wasi/wasmerciser/src/main.rs", "diff": "@@ -11,6 +11,7 @@ fn main() -> anyhow::Result<()> {\n// Vocabulary:\n// assert_exists(source)\n+ // assert_not_exists(source)\n// assert_value(var)is(val)\n// read(source)to(var)\n// write(val)to(dest)\n@@ -147,6 +148,7 @@ impl<E: Environment> TestContext<E> {\nfn process_command(&mut self, command: Command) -> anyhow::Result<()> {\nmatch command {\nCommand::AssertExists(source) => self.assert_exists(source),\n+ Command::AssertNotExists(source) => self.assert_not_exists(source),\nCommand::AssertValue(variable, value) => self.assert_value(variable, value),\nCommand::Read(source, destination) => self.read(source, destination),\nCommand::Write(value, destination) => self.write(value, destination),\n@@ -160,6 +162,13 @@ impl<E: Environment> TestContext<E> {\n}\n}\n+ fn assert_not_exists(&mut self, source: DataSource) -> anyhow::Result<()> {\n+ match source {\n+ DataSource::File(path) => self.assert_file_not_exists(PathBuf::from(path)),\n+ DataSource::Env(name) => self.assert_env_var_not_exists(name),\n+ }\n+ }\n+\nfn assert_value(&mut self, variable: Variable, value: Value) -> anyhow::Result<()> {\nlet Variable::Variable(testee_name) = variable;\nlet testee_value = self.get_variable(&testee_name)?;\n@@ -213,6 +222,17 @@ impl<E: Environment> TestContext<E> {\n}\n}\n+ fn assert_file_not_exists(&self, path: PathBuf) -> anyhow::Result<()> {\n+ if self.environment.file_exists(&path) {\n+ fail_with(format!(\n+ \"File {} was expected NOT to exist but it did exist\",\n+ path.to_string_lossy()\n+ ))\n+ } else {\n+ Ok(())\n+ }\n+ }\n+\nfn assert_env_var_exists(&self, name: String) -> anyhow::Result<()> {\nmatch self.environment.get_env_var(name.clone()) {\nOk(_) => Ok(()),\n@@ -223,6 +243,16 @@ impl<E: Environment> TestContext<E> {\n}\n}\n+ fn assert_env_var_not_exists(&self, name: String) -> anyhow::Result<()> {\n+ match self.environment.get_env_var(name.clone()) {\n+ Ok(_) => fail_with(format!(\n+ \"Env var {} was supposed to NOT exist but it did exist\",\n+ name\n+ )),\n+ Err(_) => Ok(()),\n+ }\n+ }\n+\nfn file_content(&self, path: PathBuf) -> anyhow::Result<String> {\nself.environment.file_content(&path).map_err(|e| {\nanyhow::anyhow!(\n" }, { "change_type": "MODIFY", "old_path": "demos/wasi/wasmerciser/src/syntax.rs", "new_path": "demos/wasi/wasmerciser/src/syntax.rs", "diff": "#[derive(Debug, PartialEq)]\npub enum Command {\nAssertExists(DataSource),\n+ AssertNotExists(DataSource),\nAssertValue(Variable, Value),\nRead(DataSource, Variable),\nWrite(Value, DataDestination),\n@@ -15,6 +16,7 @@ impl Command {\n}\nCommandToken::Plain(t) => match &t[..] {\n\"assert_exists\" => Self::parse_assert_exists(&tokens),\n+ \"assert_not_exists\" => Self::parse_assert_not_exists(&tokens),\n\"assert_value\" => Self::parse_assert_value(&tokens),\n\"read\" => Self::parse_read(&tokens),\n\"write\" => Self::parse_write(&tokens),\n@@ -32,6 +34,15 @@ impl Command {\n}\n}\n+ fn parse_assert_not_exists(tokens: &[CommandToken]) -> anyhow::Result<Self> {\n+ match &tokens[..] {\n+ [_, CommandToken::Bracketed(source)] => {\n+ Ok(Self::AssertNotExists(DataSource::parse(source.to_string())?))\n+ }\n+ _ => Err(anyhow::anyhow!(\"unexpected assert_not_exists command syntax\")),\n+ }\n+ }\n+\nfn parse_assert_value(tokens: &[CommandToken]) -> anyhow::Result<Self> {\nmatch &tokens[..] {\n// TODO: enforce that the separator is 'is'\n" }, { "change_type": "MODIFY", "old_path": "tests/assert.rs", "new_path": "tests/assert.rs", "diff": "@@ -56,7 +56,10 @@ pub async fn pod_exited_successfully(pods: &Api<Pod>, pod_name: &str) -> anyhow:\n.clone()\n})()\n.expect(\"Could not fetch terminated states\");\n+ if state.exit_code != 0 {\n+ try_dump_pod_logs(pods, pod_name).await;\nassert_eq!(state.exit_code, 0);\n+ }\nOk(())\n}\n@@ -129,3 +132,18 @@ pub async fn container_file_contains(\n);\nOk(())\n}\n+\n+pub async fn try_dump_pod_logs(pods: &Api<Pod>, pod_name: &str) {\n+ let logs = pods.logs(pod_name, &LogParams::default()).await;\n+\n+ match logs {\n+ Err(e) => {\n+ println!(\"Unable to dump logs for {}: {}\", pod_name, e);\n+ }\n+ Ok(content) => {\n+ println!(\"--- BEGIN LOGS for pod {}\", pod_name);\n+ println!(\"{}\", content);\n+ println!(\"--- END LOGS for pod {}\", pod_name);\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -8,7 +8,9 @@ mod pod_builder;\nmod pod_setup;\nmod test_resource_manager;\nuse expectations::{assert_container_statuses, ContainerStatusExpectation};\n-use pod_builder::{wasmerciser_pod, WasmerciserContainerSpec, WasmerciserVolumeSpec};\n+use pod_builder::{\n+ wasmerciser_pod, WasmerciserContainerSpec, WasmerciserVolumeSource, WasmerciserVolumeSpec,\n+};\nuse pod_setup::{wait_for_pod_complete, wait_for_pod_ready, OnFailure};\nuse test_resource_manager::{TestResource, TestResourceManager, TestResourceSpec};\n@@ -201,6 +203,8 @@ async fn verify_wasi_node(node: Node) -> () {\nconst SIMPLE_WASI_POD: &str = \"hello-wasi\";\nconst VERBOSE_WASI_POD: &str = \"hello-world-verbose\";\nconst FAILY_POD: &str = \"faily-pod\";\n+const MULTI_MOUNT_WASI_POD: &str = \"multi-mount-pod\";\n+const MULTI_ITEMS_MOUNT_WASI_POD: &str = \"multi-mount-items-pod\";\nconst LOGGY_POD: &str = \"loggy-pod\";\nconst INITY_WASI_POD: &str = \"hello-wasi-with-inits\";\nconst FAILY_INITS_POD: &str = \"faily-inits-pod\";\n@@ -336,6 +340,118 @@ async fn create_fancy_schmancy_wasi_pod(\n.await\n}\n+async fn create_multi_mount_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n+) -> anyhow::Result<()> {\n+ let pod_name = MULTI_MOUNT_WASI_POD;\n+\n+ let containers = vec![WasmerciserContainerSpec {\n+ name: \"multimount\",\n+ args: &[\n+ \"assert_exists(file:/mcm/mcm1)\",\n+ \"assert_exists(file:/mcm/mcm2)\",\n+ \"assert_exists(file:/mcm/mcm5)\",\n+ \"assert_exists(file:/ms/ms1)\",\n+ \"assert_exists(file:/ms/ms2)\",\n+ \"assert_exists(file:/ms/ms3)\",\n+ \"read(file:/mcm/mcm1)to(var:mcm1)\",\n+ \"read(file:/mcm/mcm5)to(var:mcm5)\",\n+ \"read(file:/ms/ms1)to(var:ms1)\",\n+ \"read(file:/ms/ms3)to(var:ms3)\",\n+ \"write(var:mcm1)to(stm:stdout)\",\n+ \"write(var:mcm5)to(stm:stdout)\",\n+ \"write(var:ms1)to(stm:stdout)\",\n+ \"write(var:ms3)to(stm:stdout)\",\n+ ],\n+ }];\n+\n+ let volumes = vec![\n+ WasmerciserVolumeSpec {\n+ volume_name: \"multicm\",\n+ mount_path: \"/mcm\",\n+ source: WasmerciserVolumeSource::ConfigMap(\"multi-configmap\"),\n+ },\n+ WasmerciserVolumeSpec {\n+ volume_name: \"multisecret\",\n+ mount_path: \"/ms\",\n+ source: WasmerciserVolumeSource::Secret(\"multi-secret\"),\n+ },\n+ ];\n+\n+ wasmercise_wasi(\n+ pod_name,\n+ client,\n+ pods,\n+ vec![],\n+ containers,\n+ volumes,\n+ OnFailure::Panic,\n+ resource_manager,\n+ )\n+ .await\n+}\n+\n+async fn create_multi_items_mount_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n+) -> anyhow::Result<()> {\n+ let pod_name = MULTI_ITEMS_MOUNT_WASI_POD;\n+\n+ let containers = vec![WasmerciserContainerSpec {\n+ name: \"multimount\",\n+ args: &[\n+ \"assert_exists(file:/mcm/mcm1)\",\n+ \"assert_not_exists(file:/mcm/mcm2)\",\n+ \"assert_exists(file:/mcm/mcm-five)\",\n+ \"assert_exists(file:/ms/ms1)\",\n+ \"assert_not_exists(file:/ms/ms2)\",\n+ \"assert_exists(file:/ms/ms-three)\",\n+ \"read(file:/mcm/mcm1)to(var:mcm1)\",\n+ \"read(file:/mcm/mcm-five)to(var:mcm5)\",\n+ \"read(file:/ms/ms1)to(var:ms1)\",\n+ \"read(file:/ms/ms-three)to(var:ms3)\",\n+ \"write(var:mcm1)to(stm:stdout)\",\n+ \"write(var:mcm5)to(stm:stdout)\",\n+ \"write(var:ms1)to(stm:stdout)\",\n+ \"write(var:ms3)to(stm:stdout)\",\n+ ],\n+ }];\n+\n+ let volumes = vec![\n+ WasmerciserVolumeSpec {\n+ volume_name: \"multicm\",\n+ mount_path: \"/mcm\",\n+ source: WasmerciserVolumeSource::ConfigMapItems(\n+ \"multi-configmap\",\n+ vec![(\"mcm1\", \"mcm1\"), (\"mcm5\", \"mcm-five\")],\n+ ),\n+ },\n+ WasmerciserVolumeSpec {\n+ volume_name: \"multisecret\",\n+ mount_path: \"/ms\",\n+ source: WasmerciserVolumeSource::SecretItems(\n+ \"multi-secret\",\n+ vec![(\"ms1\", \"ms1\"), (\"ms3\", \"ms-three\")],\n+ ),\n+ },\n+ ];\n+\n+ wasmercise_wasi(\n+ pod_name,\n+ client,\n+ pods,\n+ vec![],\n+ containers,\n+ volumes,\n+ OnFailure::Panic,\n+ resource_manager,\n+ )\n+ .await\n+}\n+\nasync fn create_loggy_pod(\nclient: kube::Client,\npods: &Api<Pod>,\n@@ -444,6 +560,7 @@ async fn create_pod_with_init_containers(\nlet volumes = vec![WasmerciserVolumeSpec {\nvolume_name: \"hostpath-test\",\nmount_path: \"/hp\",\n+ source: WasmerciserVolumeSource::HostPath,\n}];\nwasmercise_wasi(\n@@ -553,6 +670,87 @@ async fn test_pod_logs_and_mounts() -> anyhow::Result<()> {\nOk(())\n}\n+#[tokio::test]\n+async fn test_can_mount_multi_values() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-can-mount-multi-values\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ resource_manager\n+ .set_up_resources(vec![\n+ TestResourceSpec::secret_multi(\n+ \"multi-secret\",\n+ &[\n+ (\"ms1\", \"tell nobody\"),\n+ (\"ms2\", \"but the password is\"),\n+ (\"ms3\", \"wait was that a foot-- aargh!!!\"),\n+ ],\n+ ),\n+ TestResourceSpec::config_map_multi(\n+ \"multi-configmap\",\n+ &[\n+ (\"mcm1\", \"value1\"),\n+ (\"mcm2\", \"value two\"),\n+ (\"mcm5\", \"VALUE NUMBER FIVE\"),\n+ ],\n+ ),\n+ ])\n+ .await?;\n+\n+ create_multi_mount_pod(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::pod_exited_successfully(&pods, MULTI_MOUNT_WASI_POD).await?;\n+\n+ assert::pod_log_contains(&pods, MULTI_MOUNT_WASI_POD, \"value1\").await?;\n+ assert::pod_log_contains(&pods, MULTI_MOUNT_WASI_POD, \"VALUE NUMBER FIVE\").await?;\n+\n+ assert::pod_log_contains(&pods, MULTI_MOUNT_WASI_POD, \"tell nobody\").await?;\n+ assert::pod_log_contains(&pods, MULTI_MOUNT_WASI_POD, \"was that a foot-- aargh!!!\").await?;\n+\n+ Ok(())\n+}\n+\n+#[tokio::test]\n+async fn test_can_mount_individual_values() -> anyhow::Result<()> {\n+ let test_ns = \"wasi-e2e-can-mount-individual-values\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ resource_manager\n+ .set_up_resources(vec![\n+ TestResourceSpec::secret_multi(\n+ \"multi-secret\",\n+ &[\n+ (\"ms1\", \"tell nobody\"),\n+ (\"ms2\", \"but the password is\"),\n+ (\"ms3\", \"wait was that a foot-- aargh!!!\"),\n+ ],\n+ ),\n+ TestResourceSpec::config_map_multi(\n+ \"multi-configmap\",\n+ &[\n+ (\"mcm1\", \"value1\"),\n+ (\"mcm2\", \"value two\"),\n+ (\"mcm5\", \"VALUE NUMBER FIVE\"),\n+ ],\n+ ),\n+ ])\n+ .await?;\n+\n+ create_multi_items_mount_pod(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::pod_exited_successfully(&pods, MULTI_ITEMS_MOUNT_WASI_POD).await?;\n+\n+ assert::pod_log_contains(&pods, MULTI_ITEMS_MOUNT_WASI_POD, \"value1\").await?;\n+ assert::pod_log_contains(&pods, MULTI_ITEMS_MOUNT_WASI_POD, \"VALUE NUMBER FIVE\").await?;\n+\n+ assert::pod_log_contains(&pods, MULTI_ITEMS_MOUNT_WASI_POD, \"tell nobody\").await?;\n+ assert::pod_log_contains(\n+ &pods,\n+ MULTI_ITEMS_MOUNT_WASI_POD,\n+ \"was that a foot-- aargh!!!\",\n+ )\n+ .await?;\n+\n+ Ok(())\n+}\n+\n#[tokio::test]\nasync fn test_container_args() -> anyhow::Result<()> {\nlet test_ns = \"wasi-e2e-container-args\";\n" }, { "change_type": "MODIFY", "old_path": "tests/oneclick/src/main.rs", "new_path": "tests/oneclick/src/main.rs", "diff": "@@ -288,6 +288,8 @@ fn launch_kubelet(\n&cert,\n\"--private-key-file\",\n&private_key,\n+ \"--x-allow-local-modules\",\n+ \"true\",\n])\n.env(\"KUBECONFIG\", kubeconfig)\n.env(\n" }, { "change_type": "MODIFY", "old_path": "tests/pod_builder.rs", "new_path": "tests/pod_builder.rs", "diff": "@@ -15,6 +15,15 @@ pub struct WasmerciserContainerSpec {\npub struct WasmerciserVolumeSpec {\npub volume_name: &'static str,\npub mount_path: &'static str,\n+ pub source: WasmerciserVolumeSource,\n+}\n+\n+pub enum WasmerciserVolumeSource {\n+ HostPath,\n+ ConfigMap(&'static str),\n+ ConfigMapItems(&'static str, Vec<(&'static str, &'static str)>),\n+ Secret(&'static str),\n+ SecretItems(&'static str, Vec<(&'static str, &'static str)>),\n}\nfn wasmerciser_container(\n@@ -27,7 +36,7 @@ fn wasmerciser_container(\n.collect();\nlet container: Container = serde_json::from_value(json!({\n\"name\": spec.name,\n- \"image\": \"webassembly.azurecr.io/wasmerciser:v0.1.0\",\n+ \"image\": \"webassembly.azurecr.io/wasmerciser:v0.2.0\",\n\"args\": spec.args,\n\"volumeMounts\": volume_mounts,\n}))?;\n@@ -44,7 +53,9 @@ fn wasmerciser_volume_mount(spec: &WasmerciserVolumeSpec) -> anyhow::Result<Volu\nfn wasmerciser_volume(\nspec: &WasmerciserVolumeSpec,\n-) -> anyhow::Result<(Volume, Arc<tempfile::TempDir>)> {\n+) -> anyhow::Result<(Volume, Option<Arc<tempfile::TempDir>>)> {\n+ match spec.source {\n+ WasmerciserVolumeSource::HostPath => {\nlet tempdir = Arc::new(tempfile::tempdir()?);\nlet volume: Volume = serde_json::from_value(json!({\n@@ -54,7 +65,51 @@ fn wasmerciser_volume(\n}\n}))?;\n- Ok((volume, tempdir))\n+ Ok((volume, Some(tempdir)))\n+ }\n+ WasmerciserVolumeSource::ConfigMap(name) => {\n+ let volume: Volume = serde_json::from_value(json!({\n+ \"name\": spec.volume_name,\n+ \"configMap\": {\n+ \"name\": name,\n+ }\n+ }))?;\n+\n+ Ok((volume, None))\n+ }\n+ WasmerciserVolumeSource::ConfigMapItems(name, ref items) => {\n+ let volume: Volume = serde_json::from_value(json!({\n+ \"name\": spec.volume_name,\n+ \"configMap\": {\n+ \"name\": name,\n+ \"items\": items.iter().map(|(key, path)| json!({\"key\": key, \"path\": path})).collect::<Vec<_>>(),\n+ }\n+ }))?;\n+\n+ Ok((volume, None))\n+ }\n+ WasmerciserVolumeSource::Secret(name) => {\n+ let volume: Volume = serde_json::from_value(json!({\n+ \"name\": spec.volume_name,\n+ \"secret\": {\n+ \"secretName\": name,\n+ }\n+ }))?;\n+\n+ Ok((volume, None))\n+ }\n+ WasmerciserVolumeSource::SecretItems(name, ref items) => {\n+ let volume: Volume = serde_json::from_value(json!({\n+ \"name\": spec.volume_name,\n+ \"secret\": {\n+ \"secretName\": name,\n+ \"items\": items.iter().map(|(key, path)| json!({\"key\": key, \"path\": path})).collect::<Vec<_>>(),\n+ }\n+ }))?;\n+\n+ Ok((volume, None))\n+ }\n+ }\n}\npub fn wasmerciser_pod(\n@@ -105,7 +160,7 @@ pub fn wasmerciser_pod(\nOk(PodLifetimeOwner {\npod,\n- _tempdirs: tempdirs,\n+ _tempdirs: option_values(&tempdirs),\n})\n}\n@@ -114,3 +169,7 @@ fn unzip<T, U: Clone>(source: &Vec<(T, U)>) -> (Vec<&T>, Vec<U>) {\nlet us: Vec<_> = source.iter().map(|v| v.1.clone()).collect();\n(ts, us)\n}\n+\n+fn option_values<T: Clone>(source: &Vec<Option<T>>) -> Vec<T> {\n+ source.iter().filter_map(|t| t.clone()).collect()\n+}\n" }, { "change_type": "MODIFY", "old_path": "tests/test_resource_manager.rs", "new_path": "tests/test_resource_manager.rs", "diff": "@@ -12,24 +12,42 @@ pub enum TestResource {\n#[derive(Clone, Debug)]\npub enum TestResourceSpec {\n- Secret(String, String, String), // single value per secret for now\n- ConfigMap(String, String, String), // single value per cm for now\n+ Secret(String, Vec<(String, String)>),\n+ ConfigMap(String, Vec<(String, String)>),\n}\nimpl TestResourceSpec {\npub fn secret(resource_name: &str, value_name: &str, value: &str) -> Self {\nSelf::Secret(\nresource_name.to_owned(),\n- value_name.to_owned(),\n- value.to_owned(),\n+ vec![(value_name.to_owned(), value.to_owned())],\n+ )\n+ }\n+\n+ pub fn secret_multi(resource_name: &str, entries: &[(&str, &str)]) -> Self {\n+ Self::Secret(\n+ resource_name.to_owned(),\n+ entries\n+ .iter()\n+ .map(|(k, v)| (k.to_string(), v.to_string()))\n+ .collect(),\n)\n}\npub fn config_map(resource_name: &str, value_name: &str, value: &str) -> Self {\nSelf::ConfigMap(\nresource_name.to_owned(),\n- value_name.to_owned(),\n- value.to_owned(),\n+ vec![(value_name.to_owned(), value.to_owned())],\n+ )\n+ }\n+\n+ pub fn config_map_multi(resource_name: &str, entries: &[(&str, &str)]) -> Self {\n+ Self::ConfigMap(\n+ resource_name.to_owned(),\n+ entries\n+ .iter()\n+ .map(|(k, v)| (k.to_string(), v.to_string()))\n+ .collect(),\n)\n}\n}\n@@ -108,7 +126,7 @@ impl TestResourceManager {\nlet config_maps: Api<ConfigMap> = Api::namespaced(self.client.clone(), self.namespace());\nmatch resource {\n- TestResourceSpec::Secret(resource_name, value_name, value) => {\n+ TestResourceSpec::Secret(resource_name, entries) => {\nsecrets\n.create(\n&PostParams::default(),\n@@ -118,15 +136,13 @@ impl TestResourceManager {\n\"metadata\": {\n\"name\": resource_name\n},\n- \"stringData\": {\n- value_name: value\n- }\n+ \"stringData\": object_of_tuples(entries)\n}))?,\n)\n.await?;\nself.push(TestResource::Secret(resource_name.to_owned()));\n}\n- TestResourceSpec::ConfigMap(resource_name, value_name, value) => {\n+ TestResourceSpec::ConfigMap(resource_name, entries) => {\nconfig_maps\n.create(\n&PostParams::default(),\n@@ -136,9 +152,7 @@ impl TestResourceManager {\n\"metadata\": {\n\"name\": resource_name\n},\n- \"data\": {\n- value_name: value\n- }\n+ \"data\": object_of_tuples(entries)\n}))?,\n)\n.await?;\n@@ -218,3 +232,16 @@ async fn clean_up_namespace(namespace: &String) -> Option<String> {\n.err()\n.map(|e| format!(\"namespace {} ({})\", namespace, e))\n}\n+\n+fn object_of_tuples(source: &[(String, String)]) -> serde_json::Value {\n+ let mut map = serde_json::Map::new();\n+\n+ for (key, value) in source {\n+ map.insert(\n+ key.to_string(),\n+ serde_json::Value::String(value.to_string()),\n+ );\n+ }\n+\n+ serde_json::Value::Object(map)\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Mount individual items from configmaps or secrets (#354)
350,405
19.08.2020 12:22:27
-43,200
32a93ba86a208d16fa9d295afa5b9d4ea923fa79
Fix wording of decision whether to mount a config item
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/volume/mod.rs", "new_path": "crates/kubelet/src/volume/mod.rs", "diff": "@@ -157,12 +157,12 @@ async fn populate_from_secret(\nlet secret = secret_client.get(name).await?;\nlet data = secret.data.unwrap_or_default();\nlet data = data.iter().map(|(key, ByteString(data))| async move {\n- match mount_path_for(key, items) {\n- Some(mount_path) => {\n+ match mount_setting_for(key, items) {\n+ ItemMount::MountAt(mount_path) => {\nlet file_path = path.join(mount_path);\ntokio::fs::write(file_path, &data).await\n}\n- None => Ok(()),\n+ ItemMount::DoNotMount => Ok(()),\n}\n});\nfutures::future::join_all(data)\n@@ -185,23 +185,23 @@ async fn populate_from_config_map(\nlet config_map = cm_client.get(name).await?;\nlet binary_data = config_map.binary_data.unwrap_or_default();\nlet binary_data = binary_data.iter().map(|(key, data)| async move {\n- match mount_path_for(key, items) {\n- Some(mount_path) => {\n+ match mount_setting_for(key, items) {\n+ ItemMount::MountAt(mount_path) => {\nlet file_path = path.join(mount_path);\ntokio::fs::write(file_path, &data.0).await\n}\n- None => Ok(()),\n+ ItemMount::DoNotMount => Ok(()),\n}\n});\nlet binary_data = futures::future::join_all(binary_data);\nlet data = config_map.data.unwrap_or_default();\nlet data = data.iter().map(|(key, data)| async move {\n- match mount_path_for(key, items) {\n- Some(mount_path) => {\n+ match mount_setting_for(key, items) {\n+ ItemMount::MountAt(mount_path) => {\nlet file_path = path.join(mount_path);\ntokio::fs::write(file_path, data).await\n}\n- None => Ok(()),\n+ ItemMount::DoNotMount => Ok(()),\n}\n});\nlet data = futures::future::join_all(data);\n@@ -218,12 +218,28 @@ fn pod_dir_name(pod: &Pod) -> String {\nformat!(\"{}-{}\", pod.name(), pod.namespace())\n}\n-fn mount_path_for(key: &String, items_to_mount: &Option<Vec<KeyToPath>>) -> Option<String> {\n+fn mount_setting_for(key: &String, items_to_mount: &Option<Vec<KeyToPath>>) -> ItemMount {\nmatch items_to_mount {\n- None => Some(key.to_string()),\n- Some(items) => items\n+ None => ItemMount::MountAt(key.to_string()),\n+ Some(items) => ItemMount::from(\n+ items\n.iter()\n.find(|kp| &kp.key == key)\n.map(|kp| kp.path.to_string()),\n+ ),\n+ }\n+}\n+\n+enum ItemMount {\n+ MountAt(String),\n+ DoNotMount,\n+}\n+\n+impl From<Option<String>> for ItemMount {\n+ fn from(option: Option<String>) -> Self {\n+ match option {\n+ None => ItemMount::DoNotMount,\n+ Some(path) => ItemMount::MountAt(path),\n+ }\n}\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix wording of decision whether to mount a config item (#357)
350,447
10.08.2020 20:51:12
14,400
33ea5f6af7a5674c8c4237d8c468fb4a24b9f3b8
feat(oci-distribution): implement FromStr for Reference
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "use std::convert::{Into, TryFrom};\n+use std::str::FromStr;\n/// An OCI image reference\n///\n@@ -111,6 +112,14 @@ impl TryFrom<&str> for Reference {\n}\n}\n+impl FromStr for Reference {\n+ type Err = anyhow::Error;\n+\n+ fn from_str(s: &str) -> Result<Self, Self::Err> {\n+ Reference::try_from(s)\n+ }\n+}\n+\nimpl Into<String> for Reference {\nfn into(self) -> String {\nself.whole\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
feat(oci-distribution): implement FromStr for Reference
350,447
10.08.2020 20:53:40
14,400
1a724ff32a33b6c3ff887f6fb8704c05369f4986
doc(oci-distribution): add parsing example and fix formatting
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -3,9 +3,25 @@ use std::str::FromStr;\n/// An OCI image reference\n///\n-/// currently, the library only accepts modules tagged in the following structure:\n-/// <registry>/<repository>, <registry>/<repository>:<tag>, or <registry>/<repository>@<digest>\n-/// for example: webassembly.azurecr.io/hello:v1 or webassembly.azurecr.io/hello\n+/// Parsing references in the following formats is supported:\n+/// - `<registry>/<repository>`\n+/// - `<registry>/<repository>:<tag>`\n+/// - `<registry>/<repository>@<digest>`\n+/// - `<registry>/<repository>:<tag>@<digest>`\n+///\n+/// # Examples\n+///\n+/// Parsing a tagged image reference:\n+/// ```\n+/// use oci_distribution::Reference;\n+///\n+/// let reference: Reference = \"docker.io/library/hello-world:latest\".parse().unwrap();\n+///\n+/// assert_eq!(\"docker.io\", reference.registry());\n+/// assert_eq!(\"library/hello-world\", reference.repository());\n+/// assert_eq!(Some(\"latest\"), reference.tag());\n+/// assert_eq!(None, reference.digest());\n+/// ```\n#[derive(Clone, Hash, PartialEq, Eq)]\npub struct Reference {\nwhole: String,\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
doc(oci-distribution): add parsing example and fix formatting
350,426
22.08.2020 09:30:49
18,000
5299992bbff348a9775b27f9655c8c66baa15942
State Machine Attempt 2
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "@@ -33,11 +33,11 @@ pub struct Kubelet<P> {\nconfig: Box<Config>,\n}\n-impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n+impl<P: 'static + Provider + Sync + Send> Kubelet<P> {\n/// Create a new Kubelet with a provider, a kubernetes configuration,\n/// and a kubelet configuration\npub async fn new(\n- provider: T,\n+ provider: P,\nkube_config: kube::Config,\nconfig: Config,\n) -> anyhow::Result<Self> {\n@@ -96,7 +96,7 @@ impl<T: 'static + Provider + Sync + Send> Kubelet<T> {\n// Create a queue that locks on events per pod\nlet queue = Queue::new(self.provider.clone(), client.clone());\n- let pod_informer = start_pod_informer::<T>(\n+ let pod_informer = start_pod_informer::<P>(\nclient.clone(),\nself.config.node_name.clone(),\nqueue,\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/lib.rs", "new_path": "crates/kubelet/src/lib.rs", "diff": "mod bootstrapping;\nmod kubelet;\n-pub mod state;\npub(crate) mod kubeconfig;\npub(crate) mod webserver;\n@@ -63,6 +62,7 @@ pub mod log;\npub mod node;\npub mod pod;\npub mod provider;\n+pub mod state;\npub mod store;\npub mod volume;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "//! `node` contains wrappers around the Kubernetes node API, containing ways to create and update\n//! nodes operating within the cluster.\nuse crate::config::Config;\n-use crate::container::{ContainerKey, ContainerMap, Status as ContainerStatus};\n+// use crate::container::{ContainerKey, ContainerMap, Status as ContainerStatus};\nuse crate::pod::Pod;\n-use crate::pod::{Status as PodStatus, StatusMessage as PodStatusMessage};\n+// use crate::pod::{Status as PodStatus, StatusMessage as PodStatusMessage};\nuse crate::provider::Provider;\nuse chrono::prelude::*;\nuse futures::{StreamExt, TryStreamExt};\n@@ -15,7 +15,7 @@ use kube::api::{Api, ListParams, ObjectMeta, PatchParams, PostParams};\nuse kube::error::ErrorResponse;\nuse kube::Error;\nuse log::{debug, error, info, warn};\n-use std::collections::{BTreeMap, HashMap};\n+use std::collections::BTreeMap;\nuse std::sync::Arc;\nconst KUBELET_VERSION: &str = env!(\"CARGO_PKG_VERSION\");\n@@ -206,12 +206,13 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\ninfo!(\"Skipping eviction of DaemonSet '{}'\", pod.name());\ncontinue;\n} else if pod.is_static() {\n- let container_statuses = all_terminated_due_to_shutdown(&pod.all_containers());\n+ // TODO How to mark this with state machine architecture?\n+ // let container_statuses = all_terminated_due_to_shutdown(&pod.all_containers());\n- let status = PodStatus {\n- message: PodStatusMessage::Message(\"Evicted on node shutdown.\".to_string()),\n- container_statuses,\n- };\n+ // let status = PodStatus {\n+ // message: PodStatusMessage::Message(\"Evicted on node shutdown.\".to_string()),\n+ // container_statuses,\n+ // };\n// pod.patch_status(client.clone(), status).await;\ninfo!(\"Marked static pod as terminated.\");\ncontinue;\n@@ -228,22 +229,22 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\nOk(())\n}\n-fn all_terminated_due_to_shutdown(\n- container_keys: &[ContainerKey],\n-) -> ContainerMap<ContainerStatus> {\n- let mut container_statuses = HashMap::new();\n- for container_key in container_keys {\n- container_statuses.insert(\n- container_key.clone(),\n- ContainerStatus::Terminated {\n- timestamp: Utc::now(),\n- message: \"Evicted on node shutdown.\".to_string(),\n- failed: false,\n- },\n- );\n- }\n- container_statuses\n-}\n+// fn all_terminated_due_to_shutdown(\n+// container_keys: &[ContainerKey],\n+// ) -> ContainerMap<ContainerStatus> {\n+// let mut container_statuses = HashMap::new();\n+// for container_key in container_keys {\n+// container_statuses.insert(\n+// container_key.clone(),\n+// ContainerStatus::Terminated {\n+// timestamp: Utc::now(),\n+// message: \"Evicted on node shutdown.\".to_string(),\n+// failed: false,\n+// },\n+// );\n+// }\n+// container_statuses\n+// }\ntype PodStream = std::pin::Pin<\nBox<\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/handle.rs", "new_path": "crates/kubelet/src/pod/handle.rs", "diff": "@@ -2,7 +2,7 @@ use std::collections::HashMap;\nuse log::{debug, error, info};\nuse tokio::io::{AsyncRead, AsyncSeek};\n-use tokio::stream::{StreamExt, StreamMap};\n+use tokio::stream::StreamMap;\nuse tokio::sync::RwLock;\nuse tokio::task::JoinHandle;\n@@ -10,7 +10,7 @@ use crate::container::{ContainerMapByName, HandleMap as ContainerHandleMap};\nuse crate::handle::StopHandler;\nuse crate::log::{HandleFactory, Sender};\nuse crate::pod::Pod;\n-use crate::pod::{Status, StatusMessage};\n+// use crate::pod::{Status, StatusMessage};\nuse crate::provider::ProviderError;\nuse crate::volume::Ref;\n@@ -35,11 +35,11 @@ impl<H: StopHandler, F> Handle<H, F> {\npub async fn new(\ncontainer_handles: ContainerHandleMap<H, F>,\npod: Pod,\n- client: kube::Client,\n+ _client: kube::Client,\nvolumes: Option<HashMap<String, Ref>>,\n- initial_message: Option<String>,\n+ _initial_message: Option<String>,\n) -> anyhow::Result<Self> {\n- let container_keys: Vec<_> = container_handles.keys().cloned().collect();\n+ // let container_keys: Vec<_> = container_handles.keys().cloned().collect();\n// pod.initialise_status(&client, &container_keys, initial_message)\n// .await;\n@@ -51,27 +51,27 @@ impl<H: StopHandler, F> Handle<H, F> {\n// move the stream map and lose the ability to insert a new channel for\n// the restarted runtime. It may involve sending things to the task with\n// a channel\n- let cloned_pod = pod.clone();\n+ // let cloned_pod = pod.clone();\nlet status_handle = tokio::task::spawn(async move {\n- loop {\n- let (name, status) = match channel_map.next().await {\n- Some(s) => s,\n- // None means everything is closed, so go ahead and exit\n- None => {\n- return;\n- }\n- };\n+ // loop {\n+ // let (name, status) = match channel_map.next().await {\n+ // Some(s) => s,\n+ // // None means everything is closed, so go ahead and exit\n+ // None => {\n+ // return;\n+ // }\n+ // };\n- let mut container_statuses = HashMap::new();\n- container_statuses.insert(name, status);\n+ // let mut container_statuses = HashMap::new();\n+ // container_statuses.insert(name, status);\n- let pod_status = Status {\n- message: StatusMessage::LeaveUnchanged, // TODO: sure?\n- container_statuses,\n- };\n+ // let pod_status = Status {\n+ // message: StatusMessage::LeaveUnchanged, // TODO: sure?\n+ // container_statuses,\n+ // };\n// cloned_pod.patch_status(client.clone(), pod_status).await;\n- }\n+ // }\n});\nOk(Self {\ncontainer_handles: RwLock::new(container_handles),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/pod/manager.rs", "diff": "+use crate::pod::Handle;\n+use std::sync::Arc;\n+use tokio::sync::RwLock;\n+use std::collections::BTreeMap;\n+\n+type Name = String;\n+\n+type Namespace = String;\n+\n+#[derive(Clone)]\n+struct PodManager<H,F> {\n+ handles: Arc<RwLock<BTreeMap<(Namespace, Name),Handle<H,F>>>>\n+}\n+\n+impl <H,F> PodManager<H,F> {\n+ pub fn new() -> Self {\n+ PodManager {\n+ handles: Arc::new(RwLock::new(BTreeMap::new()))\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/mod.rs", "new_path": "crates/kubelet/src/pod/mod.rs", "diff": "@@ -4,19 +4,16 @@ mod queue;\nmod status;\npub use handle::{key_from_pod, pod_key, Handle};\n+pub use queue::PodChange;\npub(crate) use queue::Queue;\npub use status::{update_status, Phase, Status, StatusMessage};\n-use std::collections::HashMap;\n-\n-use crate::container::{Container, ContainerKey, ContainerMap};\n+use crate::container::{Container, ContainerKey};\nuse chrono::{DateTime, Utc};\nuse k8s_openapi::api::core::v1::{\n- Container as KubeContainer, ContainerStatus as KubeContainerStatus, Pod as KubePod,\n- Volume as KubeVolume,\n+ Container as KubeContainer, Pod as KubePod, Volume as KubeVolume,\n};\n-use kube::api::{Api, Meta, PatchParams};\n-use log::{debug, error};\n+use kube::api::Meta;\n/// A Kubernetes Pod\n///\n@@ -261,17 +258,17 @@ impl Pod {\n// self.patch_status(client.clone(), all_waiting).await;\n// }\n- fn all_waiting(container_keys: &[ContainerKey]) -> ContainerMap<crate::container::Status> {\n- let mut all_waiting_map = HashMap::new();\n- for key in container_keys {\n- let waiting = crate::container::Status::Waiting {\n- timestamp: chrono::Utc::now(),\n- message: \"PodInitializing\".to_owned(),\n- };\n- all_waiting_map.insert(key.clone(), waiting);\n- }\n- all_waiting_map\n- }\n+ // fn all_waiting(container_keys: &[ContainerKey]) -> ContainerMap<crate::container::Status> {\n+ // let mut all_waiting_map = HashMap::new();\n+ // for key in container_keys {\n+ // let waiting = crate::container::Status::Waiting {\n+ // timestamp: chrono::Utc::now(),\n+ // message: \"PodInitializing\".to_owned(),\n+ // };\n+ // all_waiting_map.insert(key.clone(), waiting);\n+ // }\n+ // all_waiting_map\n+ // }\n/// Get a pod's containers\npub fn containers(&self) -> Vec<Container> {\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -12,17 +12,14 @@ use crate::pod::{pod_key, Pod};\nuse crate::provider::Provider;\nuse crate::state::run_to_completion;\n-/// A per-pod queue that takes incoming Kubernetes events and broadcasts them to the correct queue\n-/// for that pod.\n-///\n-/// It will also send a error out on the given sender that can be handled in another process (namely\n-/// the main kubelet process). This queue will only handle the latest update. So if a modify comes\n-/// in while it is still handling a create and then another modify comes in after, only the second\n-/// modify will be handled, which is ok given that each event contains the whole pod object\n-pub(crate) struct Queue<P> {\n- provider: Arc<P>,\n- handlers: HashMap<String, Worker>,\n- client: KubeClient,\n+/// Possible mutations to Pod that state machine should detect.\n+pub enum PodChange {\n+ /// A container image has changed.\n+ ImageChange,\n+ /// The pod was marked for deletion.\n+ Shutdown,\n+ /// The pod was deregistered with the Kubernetes API and should be cleaned up.\n+ Delete,\n}\nstruct Worker {\n@@ -36,30 +33,57 @@ impl Worker {\nP: 'static + Provider + Sync + Send,\n{\nlet (sender, mut receiver) = watch::channel(initial_event);\n+\n+ // These should be set on the first Add.\n+ let mut pod_definition: Option<KubePod> = None;\n+ let mut state_tx: Option<tokio::sync::mpsc::Sender<PodChange>> = None;\n+\nlet worker = tokio::spawn(async move {\nwhile let Some(event) = receiver.recv().await {\n// Watch errors are handled before an event ever gets here, so it should always have\n// a pod\nmatch event {\nWatchEvent::Added(pod) => {\n+ // TODO Can we avoid having this called multiple times (multiple state machines)?.\n+ // I'm thinking we wait for an initial Pod added event before this loop to set\n+ // pod_definition and state_tx and start state machine, and after that it is handled differently.\n+\n+ let (tx, state_rx) = tokio::sync::mpsc::channel::<PodChange>(16);\n+ state_tx = Some(tx);\n+ pod_definition = Some(pod.clone());\n+\nlet client = client.clone();\n- let provider = Arc::clone(&provider);\n+ let pod_state: P::PodState = provider.initialize_pod_state().await.unwrap();\ntokio::spawn(async move {\nlet state: P::InitialState = Default::default();\nlet pod = Pod::new(pod);\nlet name = pod.name().to_string();\n- match run_to_completion(client, state, provider, pod).await {\n+ match run_to_completion(client, state, pod_state, pod, state_rx).await {\nOk(()) => info!(\"Pod {} state machine exited without error\", name),\n- Err(e) => error!(\"Pod {} state machine exited with error: {:?}\", name, e)\n+ Err(e) => {\n+ error!(\"Pod {} state machine exited with error: {:?}\", name, e)\n}\n- });\n}\n- WatchEvent::Modified(pod) => {\n- provider.modify(Pod::new(pod)).await;\n- }\n- WatchEvent::Deleted(pod) => {\n- provider.delete(Pod::new(pod)).await;\n+ });\n}\n+ WatchEvent::Modified(_pod) => {\n+ // TODO Need to actually detect what change happens. Some kind of diffing functions? Can reference and update pod_definition.\n+ match state_tx {\n+ Some(ref mut sender) => match sender.send(PodChange::Shutdown).await {\n+ Ok(_) => (),\n+ // This should only happen if the state machine has completed and rx was dropped.\n+ Err(_) => break,\n+ },\n+ None => unimplemented!(),\n+ }\n+ }\n+ WatchEvent::Deleted(_pod) => match state_tx {\n+ Some(ref mut sender) => match sender.send(PodChange::Delete).await {\n+ Ok(_) => (),\n+ Err(_) => break,\n+ },\n+ None => unimplemented!(),\n+ },\nWatchEvent::Bookmark(_) => (),\n_ => unreachable!(),\n}\n@@ -72,6 +96,19 @@ impl Worker {\n}\n}\n+/// A per-pod queue that takes incoming Kubernetes events and broadcasts them to the correct queue\n+/// for that pod.\n+///\n+/// It will also send a error out on the given sender that can be handled in another process (namely\n+/// the main kubelet process). This queue will only handle the latest update. So if a modify comes\n+/// in while it is still handling a create and then another modify comes in after, only the second\n+/// modify will be handled, which is ok given that each event contains the whole pod object\n+pub(crate) struct Queue<P> {\n+ provider: Arc<P>,\n+ handlers: HashMap<String, Worker>,\n+ client: KubeClient,\n+}\n+\nimpl<P: 'static + Provider + Sync + Send> Queue<P> {\npub fn new(provider: Arc<P>, client: KubeClient) -> Self {\nQueue {\n@@ -97,9 +134,9 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nNone => {\nself.handlers.insert(\nkey.clone(),\n- Worker::create(\n+ Worker::create::<P>(\nevent.clone(),\n- self.provider.clone(),\n+ Arc::clone(&self.provider),\nself.client.clone(),\n),\n);\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/provider/mod.rs", "new_path": "crates/kubelet/src/provider/mod.rs", "diff": "@@ -51,8 +51,11 @@ use crate::state::State;\n/// ```\n#[async_trait]\npub trait Provider: Sized {\n+ /// The state that is passed between Pod state handlers.\n+ type PodState: 'static + Send + Sync;\n+\n/// The initial state for Pod state machine.\n- type InitialState: Default + State<Self>;\n+ type InitialState: Default + State<Self::PodState>;\n/// Arch returns a string specifying what architecture this provider supports\nconst ARCH: &'static str;\n@@ -62,17 +65,9 @@ pub trait Provider: Sized {\nOk(())\n}\n- /// Given an updated Pod definition, update the given workload.\n- ///\n- /// Pods that are sent to this function have already met certain criteria for modification.\n- /// For example, updates to the `status` of a Pod will not be sent into this function.\n- async fn modify(&self, pod: Pod);\n-\n- /// Given the definition of a deleted Pod, remove the workload from the runtime.\n- ///\n- /// This does not need to actually delete the Pod definition -- just destroy the\n- /// associated workload.\n- async fn delete(&self, pod: Pod);\n+ /// Hook to allow provider to introduced shared state into Pod state.\n+ // TODO: Is there a way to provide a default implementation of this if Self::PodState: Default?\n+ async fn initialize_pod_state(&self) -> anyhow::Result<Self::PodState>;\n/// Given a Pod, get back the logs for the associated workload.\nasync fn logs(\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state.rs", "new_path": "crates/kubelet/src/state.rs", "diff": "//! Used to define a state machine of Pod states.\nuse log::info;\n-pub mod default;\n+// pub mod default;\n#[macro_use]\npub mod macros;\nuse crate::pod::Pod;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Api, PatchParams};\n-use std::sync::Arc;\n+\n+/// Tokio Receiver of PodChange events.\n+pub type PodChangeRx = tokio::sync::mpsc::Receiver<crate::pod::PodChange>;\n/// Represents result of state execution and which state to transition to next.\n#[derive(Debug)]\n@@ -23,40 +25,42 @@ pub enum Transition<S, E> {\n#[async_trait::async_trait]\n/// A trait representing a node in the state graph.\n-pub trait State<Provider>: Sync + Send + 'static + std::fmt::Debug {\n+pub trait State<PodState>: Sync + Send + 'static + std::fmt::Debug {\n/// The next state on success.\n- type Success: State<Provider>;\n+ type Success: State<PodState>;\n/// The next state on error.\n- type Error: State<Provider>;\n+ type Error: State<PodState>;\n/// Provider supplies method to be executed when in this state.\nasync fn next(\nself,\n- provider: Arc<Provider>,\n+ pod_state: &mut PodState,\npod: &Pod,\n+ state_rx: &mut PodChangeRx,\n) -> anyhow::Result<Transition<Self::Success, Self::Error>>;\n/// Provider supplies JSON status patch to apply when entering this state.\nasync fn json_status(\n&self,\n- provider: Arc<Provider>,\n+ pod_state: &mut PodState,\npod: &Pod,\n) -> anyhow::Result<serde_json::Value>;\n}\n#[async_recursion::async_recursion]\n/// Recursively evaluate state machine until a state returns Complete.\n-pub async fn run_to_completion<Provider: Send + Sync + 'static>(\n+pub async fn run_to_completion<PodState: Send + Sync + 'static>(\nclient: kube::Client,\n- state: impl State<Provider>,\n- provider: Arc<Provider>,\n+ state: impl State<PodState>,\n+ mut pod_state: PodState,\npod: Pod,\n+ mut state_rx: PodChangeRx,\n) -> anyhow::Result<()> {\ninfo!(\"Pod {} entering state {:?}\", pod.name(), state);\n// When handling a new state, we update the Pod state with Kubernetes.\nlet api: Api<KubePod> = Api::namespaced(client.clone(), pod.namespace());\n- let patch = state.json_status(Arc::clone(&provider), &pod).await?;\n+ let patch = state.json_status(&mut pod_state, &pod).await?;\ninfo!(\"Pod {} status patch: {:?}\", pod.name(), &patch);\nlet data = serde_json::to_vec(&patch)?;\napi.patch_status(&pod.name(), &PatchParams::default(), data)\n@@ -64,7 +68,7 @@ pub async fn run_to_completion<Provider: Send + Sync + 'static>(\ninfo!(\"Pod {} executing state handler {:?}\", pod.name(), state);\n// Execute state.\n- let transition = { state.next(Arc::clone(&provider), &pod).await? };\n+ let transition = { state.next(&mut pod_state, &pod, &mut state_rx).await? };\ninfo!(\n\"Pod {} state execution result: {:?}\",\n@@ -74,8 +78,8 @@ pub async fn run_to_completion<Provider: Send + Sync + 'static>(\n// Handle transition\nmatch transition {\n- Transition::Advance(s) => run_to_completion(client, s, provider, pod).await,\n- Transition::Error(s) => run_to_completion(client, s, provider, pod).await,\n+ Transition::Advance(s) => run_to_completion(client, s, pod_state, pod, state_rx).await,\n+ Transition::Error(s) => run_to_completion(client, s, pod_state, pod, state_rx).await,\nTransition::Complete(result) => result,\n}\n}\n@@ -91,15 +95,16 @@ impl<P: 'static + Sync + Send> State<P> for Stub {\nasync fn next(\nself,\n- _provider: Arc<P>,\n+ _pod_state: &mut P,\n_pod: &Pod,\n+ _state_rx: &mut PodChangeRx,\n) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\nOk(Transition::Complete(Ok(())))\n}\nasync fn json_status(\n&self,\n- _provider: Arc<P>,\n+ _pod_state: &mut P,\n_pod: &Pod,\n) -> anyhow::Result<serde_json::Value> {\nOk(serde_json::json!(null))\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state/macros.rs", "new_path": "crates/kubelet/src/state/macros.rs", "diff": "@@ -6,7 +6,7 @@ macro_rules! state {\n(\n$(#[$meta:meta])*\n$name:ident,\n- $state:path,\n+ $state:ty,\n$success:ty,\n$error: ty,\n$work:block,\n@@ -18,14 +18,15 @@ macro_rules! state {\n#[async_trait::async_trait]\n- impl <P: $state> State<P> for $name {\n+ impl State<$state> for $name {\ntype Success = $success;\ntype Error = $error;\nasync fn next(\nself,\n- #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod_state: &mut $state,\n#[allow(unused_variables)] pod: &Pod,\n+ #[allow(unused_variables)] state_rx: &mut PodChangeRx\n) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n#[allow(unused_braces)]\n$work\n@@ -33,7 +34,7 @@ macro_rules! state {\nasync fn json_status(\n&self,\n- #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod_state: &mut $state,\n#[allow(unused_variables)] pod: &Pod,\n) -> anyhow::Result<serde_json::Value> {\n#[allow(unused_braces)]\n@@ -44,7 +45,7 @@ macro_rules! state {\n(\n$(#[$meta:meta])*\n$name:ident,\n- $state:path,\n+ $state:ty,\n$success:ty,\n$error: ty,\n$work:path,\n@@ -56,21 +57,22 @@ macro_rules! state {\n#[async_trait::async_trait]\n- impl <P: $state> State<P> for $name {\n+ impl State<$state> for $name {\ntype Success = $success;\ntype Error = $error;\nasync fn next(\nself,\n- #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod_state: &mut $state,\n#[allow(unused_variables)] pod: &Pod,\n+ #[allow(unused_variables)] state_rx: &mut PodChangeRx\n) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n$work(self, pod).await\n}\nasync fn json_status(\n&self,\n- #[allow(unused_variables)] provider: Arc<P>,\n+ #[allow(unused_variables)] pod_state: &mut $state,\n#[allow(unused_variables)] pod: &Pod,\n) -> anyhow::Result<serde_json::Value> {\n#[allow(unused_braces)]\n@@ -78,7 +80,4 @@ macro_rules! state {\n}\n}\n};\n-\n-\n-\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
State Machine Attempt 2
350,426
22.08.2020 09:31:03
18,000
cfcd2d185f824536d1a5b42b4826e832ea633e7e
Wascc Provider Implementation
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "#![deny(missing_docs)]\nuse async_trait::async_trait;\n-use k8s_openapi::api::core::v1::{ContainerStatus as KubeContainerStatus, Pod as KubePod};\n-use kube::{api::{DeleteParams, WatchEvent}, Api};\n-use kubelet::container::Container;\n-use kubelet::container::{\n- ContainerKey, Handle as ContainerHandle, HandleMap as ContainerHandleMap,\n- Status as ContainerStatus,\n-};\n+use kubelet::container::{Handle as ContainerHandle, Status as ContainerStatus};\nuse kubelet::handle::StopHandler;\nuse kubelet::node::Builder;\n-use kubelet::pod::{key_from_pod, pod_key, Handle};\n-use kubelet::pod::{\n- update_status, Phase, Pod, Status as PodStatus, StatusMessage as PodStatusMessage,\n-};\n+use kubelet::pod::Phase;\n+use kubelet::pod::{pod_key, Handle};\nuse kubelet::provider::Provider;\nuse kubelet::provider::ProviderError;\nuse kubelet::store::Store;\n-use kubelet::state::default::{Registered, DefaultStateProvider};\n+\nuse kubelet::volume::Ref;\n-use log::{debug, error, info, trace};\n-use std::error::Error;\n-use std::fmt;\n+use log::{debug, info};\nuse tempfile::NamedTempFile;\n-use tokio::sync::watch::{self, Receiver};\n+use tokio::sync::watch::Receiver;\nuse tokio::sync::RwLock;\nuse wascc_fs::FileSystemProvider;\nuse wascc_host::{Actor, NativeCapability, WasccHost};\n@@ -62,13 +52,14 @@ use wascc_httpsrv::HttpServerProvider;\nuse wascc_logging::{LoggingProvider, LOG_PATH_KEY};\nextern crate rand;\n-use rand::Rng;\n-use std::collections::{HashMap, HashSet};\n-use std::ops::Deref;\n+use std::collections::HashMap;\nuse std::path::{Path, PathBuf};\nuse std::sync::{Arc, Mutex};\nuse tokio::sync::Mutex as TokioMutex;\n+mod states;\n+use states::registered::Registered;\n+\n/// The architecture that the pod targets.\nconst TARGET_WASM32_WASCC: &str = \"wasm32-wascc\";\n@@ -208,197 +199,46 @@ impl WasccProvider {\nport_map,\n})\n}\n-\n- async fn assign_container_port(&self, pod: &Pod, container: &Container) -> anyhow::Result<i32> {\n- let mut port_assigned: i32 = 0;\n- if let Some(container_vec) = container.ports().as_ref() {\n- for c_port in container_vec.iter() {\n- let container_port = c_port.container_port;\n- if let Some(host_port) = c_port.host_port {\n- let mut lock = self.port_map.lock().await;\n- if !lock.contains_key(&host_port) {\n- port_assigned = host_port;\n- lock.insert(port_assigned, pod.name().to_string());\n- } else {\n- error!(\n- \"Failed to assign hostport {}, because it's taken\",\n- &host_port\n- );\n- return Err(anyhow::anyhow!(\"Port {} is currently in use\", &host_port));\n- }\n- } else if container_port >= 0 && container_port <= 65536 {\n- port_assigned =\n- find_available_port(&self.port_map, pod.name().to_string()).await?;\n- }\n- }\n- }\n- Ok(port_assigned)\n- }\n-\n- async fn start_container(\n- &self,\n- run_context: &mut ModuleRunContext,\n- container: &Container,\n- pod: &Pod,\n- port_assigned: i32,\n- ) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> {\n- let env = Self::env_vars(&container, &pod, &self.client).await;\n- let volume_bindings: Vec<VolumeBinding> =\n- if let Some(volume_mounts) = container.volume_mounts().as_ref() {\n- volume_mounts\n- .iter()\n- .map(|vm| -> anyhow::Result<VolumeBinding> {\n- // Check the volume exists first\n- let vol = run_context.volumes.get(&vm.name).ok_or_else(|| {\n- anyhow::anyhow!(\n- \"no volume with the name of {} found for container {}\",\n- vm.name,\n- container.name()\n- )\n- })?;\n- // We can safely assume that this should be valid UTF-8 because it would have\n- // been validated by the k8s API\n- Ok(VolumeBinding {\n- name: vm.name.clone(),\n- host_path: vol.deref().clone(),\n- })\n- })\n- .collect::<anyhow::Result<_>>()?\n- } else {\n- vec![]\n- };\n-\n- debug!(\"Starting container {} on thread\", container.name());\n-\n- let module_data = run_context\n- .modules\n- .remove(container.name())\n- .expect(\"FATAL ERROR: module map not properly populated\");\n- let lp = self.log_path.clone();\n- let (status_sender, status_recv) = watch::channel(ContainerStatus::Waiting {\n- timestamp: chrono::Utc::now(),\n- message: \"No status has been received from the process\".into(),\n- });\n- let host = self.host.clone();\n- let http_result = tokio::task::spawn_blocking(move || {\n- wascc_run_http(\n- host,\n- module_data,\n- env,\n- volume_bindings,\n- &lp,\n- status_recv,\n- port_assigned,\n- )\n- })\n- .await?;\n- http_result\n- }\n}\nstruct ModuleRunContext {\nmodules: HashMap<String, Vec<u8>>,\nvolumes: HashMap<String, Ref>,\n- event_tx: tokio::sync::mpsc::Sender<WatchEvent<KubePod>>,\n- event_rx: tokio::sync::mpsc::Receiver<WatchEvent<KubePod>>,\n}\n-#[async_trait::async_trait]\n-impl DefaultStateProvider for WasccProvider {\n- /// A new Pod has been created.\n- async fn registered(&self, pod: &Pod) -> anyhow::Result<()> {\n- info!(\"Pod added: {}.\", pod.name());\n- validate_pod_runnable(&pod)?;\n- info!(\"Pod validated: {}.\", pod.name());\n- let (event_tx, event_rx) = tokio::sync::mpsc::channel(16);\n- let run_context = ModuleRunContext {\n- modules: Default::default(),\n- volumes: Default::default(),\n- event_tx,\n- event_rx\n- };\n-\n- let pod_handle_key = key_from_pod(&pod);\n- info!(\"Pod registering run context: {}\", pod.name());\n- self.run_contexts.write().await.insert(pod_handle_key, run_context);\n- info!(\"Pod registered: {}.\", pod.name());\n- Ok(())\n- }\n-\n- /// Pull images for containers.\n- async fn image_pull(&self, pod: &Pod) -> anyhow::Result<()> {\n- let pod_handle_key = key_from_pod(&pod);\n- match self.run_contexts.write().await.get_mut(&pod_handle_key) {\n- Some(mut run_context) => {\n- run_context.modules = self.store.fetch_pod_modules(&pod).await?;\n- }\n- None => anyhow::bail!(\"Could not locate pod run context: {}\", pod_handle_key)\n- }\n- Ok(())\n- }\n-\n- /// Mount volumes for containers.\n- async fn volume_mount(&self, pod: &Pod) -> anyhow::Result<()> {\n- let pod_handle_key = key_from_pod(&pod);\n- match self.run_contexts.write().await.get_mut(&pod_handle_key) {\n- Some(mut run_context) => {\n- run_context.volumes = Ref::volumes_from_pod(&self.volume_path, &pod, &self.client).await?;\n- }\n- None => anyhow::bail!(\"Could not locate pod run context: {}\", pod_handle_key)\n- }\n- Ok(())\n- }\n-\n- /// Start containers.\n- async fn starting(&self, pod: &Pod) -> anyhow::Result<()> {\n- info!(\"Starting containers for pod {:?}\", pod.name());\n-\n- let pod_handle_key = key_from_pod(&pod);\n-\n- let mut run_contexts = self.run_contexts.write().await;\n- let mut run_context = run_contexts.get_mut(&pod_handle_key).ok_or_else(|| {\n- anyhow::anyhow!(\"Could not locate pod run context: {}\", pod_handle_key)\n- })?;\n-\n- let mut container_handles = HashMap::new();\n- for container in pod.containers() {\n- let port_assigned = self.assign_container_port(&pod, &container).await?;\n- debug!(\n- \"New port assigned to {} is: {}\",\n- container.name(),\n- port_assigned\n- );\n-\n- let container_handle = self.start_container(&mut run_context, &container, &pod, port_assigned)\n- .await?;\n- container_handles.insert(ContainerKey::App(container.name().to_string()), container_handle);\n- }\n- let pod_handle = Handle::new(container_handles, pod.clone(), self.client.clone(), None, None).await?;\n-\n- // Wrap this in a block so the write lock goes out of scope when we are done\n+fn make_status(phase: Phase, reason: &str) -> anyhow::Result<serde_json::Value> {\n+ Ok(serde_json::json!(\n{\n- let mut handles = self.handles.write().await;\n- handles.insert(pod_handle_key, pod_handle);\n+ \"metadata\": {\n+ \"resourceVersion\": \"\",\n+ },\n+ \"status\": {\n+ \"phase\": phase,\n+ \"reason\": reason,\n+ \"containerStatuses\": Vec::<()>::new(),\n+ \"initContainerStatuses\": Vec::<()>::new(),\n}\n-\n- info!(\n- \"All containers started for pod {:?}.\",\n- pod.name()\n- );\n- Ok(())\n}\n-\n- /// Running state.\n- async fn running(&self, _pod: &Pod) -> anyhow::Result<()> {\n- /// Listen for pod changes.\n- loop { tokio::time::delay_for(std::time::Duration::from_secs(30)).await; }\n- Ok(())\n+ ))\n}\n+\n+/// State that is shared between pod state handlers.\n+pub struct PodState {\n+ run_context: ModuleRunContext,\n+ store: Arc<dyn Store + Sync + Send>,\n+ client: kube::Client,\n+ volume_path: std::path::PathBuf,\n+ errors: usize,\n+ port_map: Arc<TokioMutex<HashMap<i32, String>>>,\n+ handle: Option<Handle<ActorHandle, LogHandleFactory>>,\n+ log_path: PathBuf,\n+ host: Arc<Mutex<WasccHost>>,\n}\n#[async_trait]\nimpl Provider for WasccProvider {\ntype InitialState = Registered;\n+ type PodState = PodState;\nconst ARCH: &'static str = TARGET_WASM32_WASCC;\n@@ -408,15 +248,27 @@ impl Provider for WasccProvider {\nOk(())\n}\n- async fn modify(&self, pod: Pod) {\n- let pod_handle_key = key_from_pod(&pod);\n- match self.run_contexts.write().await.get_mut(&pod_handle_key) {\n- Some(mut run_context) => {\n- run_context.event_tx.send(WatchEvent::Modified(pod.into_kube_pod())).await.ok();\n- }\n- None => ()\n+ async fn initialize_pod_state(&self) -> anyhow::Result<Self::PodState> {\n+ let run_context = ModuleRunContext {\n+ modules: Default::default(),\n+ volumes: Default::default(),\n+ };\n+\n+ Ok(PodState {\n+ run_context,\n+ store: Arc::clone(&self.store),\n+ client: self.client.clone(),\n+ volume_path: self.volume_path.clone(),\n+ errors: 0,\n+ port_map: Arc::clone(&self.port_map),\n+ handle: None,\n+ log_path: self.log_path.clone(),\n+ host: Arc::clone(&self.host),\n+ })\n}\n+ // async fn modify(&self, pod: Pod) {\n+ // let pod_handle_key = key_from_pod(&pod);\n// // The only things we care about are:\n// // 1. metadata.deletionTimestamp => signal all containers to stop and then mark them\n// // as terminated\n@@ -499,39 +351,7 @@ impl Provider for WasccProvider {\n// };\n// // TODO: Implement behavior for stopping old containers and restarting when the container\n// // image changes\n- }\n-\n- async fn delete(&self, pod: Pod) {\n- let pod_handle_key = key_from_pod(&pod);\n- match self.run_contexts.write().await.get_mut(&pod_handle_key) {\n- Some(mut run_context) => {\n- run_context.event_tx.send(WatchEvent::Deleted(pod.into_kube_pod())).await.ok();\n- }\n- None => ()\n- }\n-\n- // let mut delete_key: i32 = 0;\n- // let mut lock = self.port_map.lock().await;\n- // for (key, val) in lock.iter() {\n- // if val == pod.name() {\n- // delete_key = *key\n- // }\n// }\n- // lock.remove(&delete_key);\n- // let mut handles = self.handles.write().await;\n- // match handles.remove(&key_from_pod(&pod)) {\n- // Some(_) => debug!(\n- // \"Pod {} in namespace {} removed\",\n- // pod.name(),\n- // pod.namespace()\n- // ),\n- // None => info!(\n- // \"unable to find pod {} in namespace {}, it was likely already deleted\",\n- // pod.name(),\n- // pod.namespace()\n- // ),\n- // }\n- }\nasync fn logs(\n&self,\n@@ -550,37 +370,6 @@ impl Provider for WasccProvider {\n}\n}\n-fn validate_pod_runnable(pod: &Pod) -> anyhow::Result<()> {\n- if !pod.init_containers().is_empty() {\n- return Err(anyhow::anyhow!(\n- \"Cannot run {}: spec specifies init containers which are not supported on wasCC\",\n- pod.name()\n- ));\n- }\n- for container in pod.containers() {\n- validate_container_runnable(&container)?;\n- }\n- Ok(())\n-}\n-\n-fn validate_container_runnable(container: &Container) -> anyhow::Result<()> {\n- if has_args(container) {\n- return Err(anyhow::anyhow!(\n- \"Cannot run {}: spec specifies container args which are not supported on wasCC\",\n- container.name()\n- ));\n- }\n-\n- Ok(())\n-}\n-\n-fn has_args(container: &Container) -> bool {\n- match &container.args() {\n- None => false,\n- Some(vec) => !vec.is_empty(),\n- }\n-}\n-\nstruct VolumeBinding {\nname: String,\nhost_path: PathBuf,\n@@ -609,44 +398,6 @@ fn wascc_run_http(\nwascc_run(host, data, &mut caps, volumes, log_path, status_recv)\n}\n-#[derive(Debug)]\n-struct PortAllocationError {}\n-\n-impl PortAllocationError {\n- fn new() -> PortAllocationError {\n- PortAllocationError {}\n- }\n-}\n-impl fmt::Display for PortAllocationError {\n- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n- write!(f, \"all ports are currently in use\")\n- }\n-}\n-impl Error for PortAllocationError {\n- fn description(&self) -> &str {\n- \"all ports are currently in use\"\n- }\n-}\n-\n-async fn find_available_port(\n- port_map: &Arc<TokioMutex<HashMap<i32, String>>>,\n- pod_name: String,\n-) -> Result<i32, PortAllocationError> {\n- let mut port: Option<i32> = None;\n- let mut empty_port: HashSet<i32> = HashSet::new();\n- let mut lock = port_map.lock().await;\n- while empty_port.len() < 2768 {\n- let generated_port: i32 = rand::thread_rng().gen_range(30000, 32768);\n- port.replace(generated_port);\n- empty_port.insert(port.unwrap());\n- if !lock.contains_key(&port.unwrap()) {\n- lock.insert(port.unwrap(), pod_name);\n- break;\n- }\n- }\n- port.ok_or_else(PortAllocationError::new)\n-}\n-\n/// Capability describes a waSCC capability.\n///\n/// Capabilities are made available to actors through a two-part processthread:\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states.rs", "diff": "+pub mod cleanup;\n+pub mod crash_loop_backoff;\n+pub mod error;\n+pub mod finished;\n+pub mod image_pull;\n+pub mod image_pull_backoff;\n+pub mod registered;\n+pub mod running;\n+pub mod starting;\n+pub mod terminated;\n+pub mod volume_mount;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/cleanup.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use crate::{make_status, PodState};\n+\n+state!(\n+ /// Clean up any pod resources..\n+ Cleanup,\n+ PodState,\n+ Cleanup,\n+ Cleanup,\n+ {\n+ let mut delete_key: i32 = 0;\n+ let mut lock = pod_state.port_map.lock().await;\n+ for (key, val) in lock.iter() {\n+ if val == pod.name() {\n+ delete_key = *key\n+ }\n+ }\n+ lock.remove(&delete_key);\n+\n+ Ok(Transition::Complete(Ok(())))\n+ },\n+ { make_status(Phase::Succeeded, \"Cleanup\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/crash_loop_backoff.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use crate::{make_status, PodState};\n+\n+use super::registered::Registered;\n+\n+state!(\n+ /// Pod has failed multiple times.\n+ CrashLoopBackoff,\n+ PodState,\n+ Registered,\n+ CrashLoopBackoff,\n+ {\n+ // TODO: Handle pod delete?\n+ tokio::time::delay_for(std::time::Duration::from_secs(60)).await;\n+ Ok(Transition::Advance(Registered))\n+ },\n+ { make_status(Phase::Pending, \"CrashLoopBackoff\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/error.rs", "diff": "+use kubelet::pod::{Phase, Pod};\n+use kubelet::state::{PodChangeRx, State, Transition};\n+\n+use super::crash_loop_backoff::CrashLoopBackoff;\n+use super::registered::Registered;\n+use crate::{make_status, PodState};\n+\n+#[derive(Default, Debug)]\n+/// The Pod failed to run.\n+// If we manually implement, we can allow for arguments.\n+pub struct Error {\n+ pub message: String,\n+}\n+\n+#[async_trait::async_trait]\n+impl State<PodState> for Error {\n+ type Success = Registered;\n+ type Error = CrashLoopBackoff;\n+\n+ async fn next(\n+ self,\n+ pod_state: &mut PodState,\n+ _pod: &Pod,\n+ _state_rx: &mut PodChangeRx,\n+ ) -> anyhow::Result<Transition<Self::Success, Self::Error>> {\n+ // TODO: Handle pod delete?\n+ pod_state.errors += 1;\n+ if pod_state.errors > 3 {\n+ pod_state.errors = 0;\n+ Ok(Transition::Error(CrashLoopBackoff))\n+ } else {\n+ tokio::time::delay_for(std::time::Duration::from_secs(5)).await;\n+ Ok(Transition::Advance(Registered))\n+ }\n+ }\n+\n+ async fn json_status(\n+ &self,\n+ _pod_state: &mut PodState,\n+ _pod: &Pod,\n+ ) -> anyhow::Result<serde_json::Value> {\n+ make_status(Phase::Pending, &self.message)\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/finished.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use crate::{make_status, PodState};\n+\n+use super::cleanup::Cleanup;\n+\n+state!(\n+ /// Pod execution completed with no errors.\n+ Finished,\n+ PodState,\n+ Cleanup,\n+ Finished,\n+ {\n+ // TODO: Wait for deleted.\n+ Ok(Transition::Advance(Cleanup))\n+ },\n+ { make_status(Phase::Succeeded, \"Finished\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/image_pull.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+use log::error;\n+\n+use crate::{make_status, PodState};\n+\n+use super::image_pull_backoff::ImagePullBackoff;\n+use super::volume_mount::VolumeMount;\n+\n+state!(\n+ /// Kubelet is pulling container images.\n+ ImagePull,\n+ PodState,\n+ VolumeMount,\n+ ImagePullBackoff,\n+ {\n+ pod_state.run_context.modules = match pod_state.store.fetch_pod_modules(&pod).await {\n+ Ok(modules) => modules,\n+ Err(e) => {\n+ error!(\"{:?}\", e);\n+ return Ok(Transition::Error(ImagePullBackoff));\n+ }\n+ };\n+ Ok(Transition::Advance(VolumeMount))\n+ },\n+ { make_status(Phase::Pending, \"ImagePull\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/image_pull_backoff.rs", "diff": "+use super::image_pull::ImagePull;\n+use crate::{make_status, PodState};\n+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+state!(\n+ /// Kubelet encountered an error when pulling container image.\n+ ImagePullBackoff,\n+ PodState,\n+ ImagePull,\n+ ImagePullBackoff,\n+ { Ok(Transition::Advance(ImagePull)) },\n+ { make_status(Phase::Pending, \"ImagePullBackoff\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/registered.rs", "diff": "+use log::{error, info};\n+\n+use crate::{make_status, PodState};\n+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ container::Container,\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use super::error::Error;\n+use super::image_pull::ImagePull;\n+\n+fn validate_pod_runnable(pod: &Pod) -> anyhow::Result<()> {\n+ if !pod.init_containers().is_empty() {\n+ return Err(anyhow::anyhow!(\n+ \"Cannot run {}: spec specifies init containers which are not supported on wasCC\",\n+ pod.name()\n+ ));\n+ }\n+ for container in pod.containers() {\n+ validate_container_runnable(&container)?;\n+ }\n+ Ok(())\n+}\n+\n+fn validate_container_runnable(container: &Container) -> anyhow::Result<()> {\n+ if has_args(container) {\n+ return Err(anyhow::anyhow!(\n+ \"Cannot run {}: spec specifies container args which are not supported on wasCC\",\n+ container.name()\n+ ));\n+ }\n+\n+ Ok(())\n+}\n+\n+fn has_args(container: &Container) -> bool {\n+ match &container.args() {\n+ None => false,\n+ Some(vec) => !vec.is_empty(),\n+ }\n+}\n+\n+state!(\n+ /// The Kubelet is aware of the Pod.\n+ Registered,\n+ PodState,\n+ ImagePull,\n+ Error,\n+ {\n+ info!(\"Pod added: {}.\", pod.name());\n+ match validate_pod_runnable(&pod) {\n+ Ok(_) => (),\n+ Err(e) => {\n+ let message = format!(\"{:?}\", e);\n+ error!(\"{}\", message);\n+ return Ok(Transition::Error(Error { message }));\n+ }\n+ }\n+ info!(\"Pod validated: {}.\", pod.name());\n+ info!(\"Pod registered: {}.\", pod.name());\n+ Ok(Transition::Advance(ImagePull))\n+ },\n+ { make_status(Phase::Pending, \"Registered\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/running.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use crate::{make_status, PodState};\n+\n+use super::error::Error;\n+use super::finished::Finished;\n+\n+state!(\n+ /// The Kubelet is running the Pod.\n+ Running,\n+ PodState,\n+ Finished,\n+ Error,\n+ {\n+ // Listen for pod changes.\n+ // Wait for execution to complete.\n+ Ok(Transition::Advance(Finished))\n+ },\n+ { make_status(Phase::Running, \"Running\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/starting.rs", "diff": "+use std::collections::{HashMap, HashSet};\n+use std::ops::Deref;\n+use std::sync::Arc;\n+\n+use log::{debug, error, info};\n+use tokio::sync::watch;\n+use tokio::sync::Mutex;\n+\n+use kubelet::container::{\n+ Container, ContainerKey, Handle as ContainerHandle, Status as ContainerStatus,\n+};\n+use kubelet::provider::Provider;\n+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Handle, Phase, Pod},\n+ state,\n+};\n+\n+use crate::rand::Rng;\n+use crate::VolumeBinding;\n+use crate::{make_status, PodState};\n+use crate::{wascc_run_http, ActorHandle, LogHandleFactory, WasccProvider};\n+\n+use super::error::Error;\n+use super::running::Running;\n+\n+#[derive(Debug)]\n+struct PortAllocationError {}\n+\n+impl PortAllocationError {\n+ fn new() -> PortAllocationError {\n+ PortAllocationError {}\n+ }\n+}\n+\n+impl std::fmt::Display for PortAllocationError {\n+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n+ write!(f, \"all ports are currently in use\")\n+ }\n+}\n+\n+impl std::error::Error for PortAllocationError {\n+ fn description(&self) -> &str {\n+ \"all ports are currently in use\"\n+ }\n+}\n+\n+async fn find_available_port(\n+ port_map: &Arc<Mutex<HashMap<i32, String>>>,\n+ pod_name: String,\n+) -> Result<i32, PortAllocationError> {\n+ let mut port: Option<i32> = None;\n+ let mut empty_port: HashSet<i32> = HashSet::new();\n+ let mut lock = port_map.lock().await;\n+ while empty_port.len() < 2768 {\n+ let generated_port: i32 = rand::thread_rng().gen_range(30000, 32768);\n+ port.replace(generated_port);\n+ empty_port.insert(port.unwrap());\n+ if !lock.contains_key(&port.unwrap()) {\n+ lock.insert(port.unwrap(), pod_name);\n+ break;\n+ }\n+ }\n+ port.ok_or_else(PortAllocationError::new)\n+}\n+\n+async fn assign_container_port(\n+ port_map: Arc<Mutex<HashMap<i32, String>>>,\n+ pod: &Pod,\n+ container: &Container,\n+) -> anyhow::Result<i32> {\n+ let mut port_assigned: i32 = 0;\n+ if let Some(container_vec) = container.ports().as_ref() {\n+ for c_port in container_vec.iter() {\n+ let container_port = c_port.container_port;\n+ if let Some(host_port) = c_port.host_port {\n+ let mut lock = port_map.lock().await;\n+ if !lock.contains_key(&host_port) {\n+ port_assigned = host_port;\n+ lock.insert(port_assigned, pod.name().to_string());\n+ } else {\n+ error!(\n+ \"Failed to assign hostport {}, because it's taken\",\n+ &host_port\n+ );\n+ return Err(anyhow::anyhow!(\"Port {} is currently in use\", &host_port));\n+ }\n+ } else if container_port >= 0 && container_port <= 65536 {\n+ port_assigned = find_available_port(&port_map, pod.name().to_string()).await?;\n+ }\n+ }\n+ }\n+ Ok(port_assigned)\n+}\n+\n+async fn start_container(\n+ pod_state: &mut PodState,\n+ container: &Container,\n+ pod: &Pod,\n+ port_assigned: i32,\n+) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> {\n+ let env = <WasccProvider as Provider>::env_vars(&container, &pod, &pod_state.client).await;\n+ let volume_bindings: Vec<VolumeBinding> =\n+ if let Some(volume_mounts) = container.volume_mounts().as_ref() {\n+ volume_mounts\n+ .iter()\n+ .map(|vm| -> anyhow::Result<VolumeBinding> {\n+ // Check the volume exists first\n+ let vol = pod_state.run_context.volumes.get(&vm.name).ok_or_else(|| {\n+ anyhow::anyhow!(\n+ \"no volume with the name of {} found for container {}\",\n+ vm.name,\n+ container.name()\n+ )\n+ })?;\n+ // We can safely assume that this should be valid UTF-8 because it would have\n+ // been validated by the k8s API\n+ Ok(VolumeBinding {\n+ name: vm.name.clone(),\n+ host_path: vol.deref().clone(),\n+ })\n+ })\n+ .collect::<anyhow::Result<_>>()?\n+ } else {\n+ vec![]\n+ };\n+\n+ debug!(\"Starting container {} on thread\", container.name());\n+\n+ let module_data = pod_state\n+ .run_context\n+ .modules\n+ .remove(container.name())\n+ .expect(\"FATAL ERROR: module map not properly populated\");\n+ let lp = pod_state.log_path.clone();\n+ let (_status_sender, status_recv) = watch::channel(ContainerStatus::Waiting {\n+ timestamp: chrono::Utc::now(),\n+ message: \"No status has been received from the process\".into(),\n+ });\n+ let host = pod_state.host.clone();\n+ tokio::task::spawn_blocking(move || {\n+ wascc_run_http(\n+ host,\n+ module_data,\n+ env,\n+ volume_bindings,\n+ &lp,\n+ status_recv,\n+ port_assigned,\n+ )\n+ })\n+ .await?\n+}\n+\n+state!(\n+ /// The Kubelet is starting the Pod.\n+ Starting,\n+ PodState,\n+ Running,\n+ Error,\n+ {\n+ info!(\"Starting containers for pod {:?}\", pod.name());\n+\n+ let mut container_handles = HashMap::new();\n+ for container in pod.containers() {\n+ let port_assigned =\n+ assign_container_port(Arc::clone(&pod_state.port_map), &pod, &container)\n+ .await\n+ .unwrap();\n+ debug!(\n+ \"New port assigned to {} is: {}\",\n+ container.name(),\n+ port_assigned\n+ );\n+\n+ let container_handle = start_container(pod_state, &container, &pod, port_assigned)\n+ .await\n+ .unwrap();\n+ container_handles.insert(\n+ ContainerKey::App(container.name().to_string()),\n+ container_handle,\n+ );\n+ }\n+\n+ let pod_handle = Handle::new(\n+ container_handles,\n+ pod.clone(),\n+ pod_state.client.clone(),\n+ None,\n+ None,\n+ )\n+ .await?;\n+ pod_state.handle = Some(pod_handle);\n+\n+ info!(\"All containers started for pod {:?}.\", pod.name());\n+\n+ Ok(Transition::Advance(Running))\n+ },\n+ { make_status(Phase::Pending, \"Starting\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/terminated.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use crate::{make_status, PodState};\n+\n+use super::cleanup::Cleanup;\n+\n+state!(\n+ /// Pod was deleted.\n+ Terminated,\n+ PodState,\n+ Cleanup,\n+ Terminated,\n+ {\n+ // TODO: Stop workload\n+ // TODO: Wait for deleted.\n+ Ok(Transition::Advance(Cleanup))\n+ },\n+ { make_status(Phase::Succeeded, \"Terminated\") }\n+);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/wascc-provider/src/states/volume_mount.rs", "diff": "+use kubelet::state::{PodChangeRx, State, Transition};\n+use kubelet::volume::Ref;\n+use kubelet::{\n+ pod::{Phase, Pod},\n+ state,\n+};\n+\n+use crate::{make_status, PodState};\n+\n+use super::error::Error;\n+use super::starting::Starting;\n+\n+state!(\n+ /// Kubelet is pulling container images.\n+ VolumeMount,\n+ PodState,\n+ Starting,\n+ Error,\n+ {\n+ pod_state.run_context.volumes =\n+ Ref::volumes_from_pod(&pod_state.volume_path, &pod, &pod_state.client)\n+ .await\n+ .unwrap();\n+ Ok(Transition::Advance(Starting))\n+ },\n+ { make_status(Phase::Pending, \"VolumeMount\") }\n+);\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Wascc Provider Implementation
350,426
22.08.2020 13:13:41
18,000
a6ee131a90d6089b00864e5a89ecf78c596358f1
Clean up some files.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/container/handle.rs", "new_path": "crates/kubelet/src/container/handle.rs", "diff": "use std::io::SeekFrom;\nuse tokio::io::{AsyncRead, AsyncSeek, AsyncSeekExt};\n-use tokio::sync::watch::Receiver;\n-use crate::container::{ContainerMap, Status};\n+use crate::container::ContainerMap;\nuse crate::handle::StopHandler;\nuse crate::log::{stream, HandleFactory, Sender};\n@@ -14,21 +13,15 @@ use crate::log::{stream, HandleFactory, Sender};\npub struct Handle<H, F> {\nhandle: H,\nhandle_factory: F,\n- status_channel: Receiver<Status>,\n}\nimpl<H: StopHandler, F> Handle<H, F> {\n/// Create a new runtime with the given handle for stopping the runtime,\n/// a reader for log output, and a status channel.\n- ///\n- /// The status channel is a [Tokio watch `Receiver`][Receiver]. The sender part\n- /// of the channel should be given to the running process and the receiver half\n- /// passed to this constructor to be used for reporting current status\n- pub fn new(handle: H, handle_factory: F, status_channel: Receiver<Status>) -> Self {\n+ pub fn new(handle: H, handle_factory: F) -> Self {\nSelf {\nhandle,\nhandle_factory,\n- status_channel,\n}\n}\n@@ -51,12 +44,6 @@ impl<H: StopHandler, F> Handle<H, F> {\nOk(())\n}\n- /// Returns a clone of the status_channel for use in reporting the status to\n- /// another process\n- pub fn status(&self) -> Receiver<Status> {\n- self.status_channel.clone()\n- }\n-\n/// Wait for the running process to complete. Generally speaking,\n/// [`Handle::stop`] should be called first. This uses the underlying\n/// [`StopHandler`] implementation passed to the constructor\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "//! `node` contains wrappers around the Kubernetes node API, containing ways to create and update\n//! nodes operating within the cluster.\nuse crate::config::Config;\n-// use crate::container::{ContainerKey, ContainerMap, Status as ContainerStatus};\nuse crate::pod::Pod;\n-// use crate::pod::{Status as PodStatus, StatusMessage as PodStatusMessage};\nuse crate::provider::Provider;\nuse chrono::prelude::*;\nuse futures::{StreamExt, TryStreamExt};\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/handle.rs", "new_path": "crates/kubelet/src/pod/handle.rs", "diff": "@@ -2,15 +2,12 @@ use std::collections::HashMap;\nuse log::{debug, error, info};\nuse tokio::io::{AsyncRead, AsyncSeek};\n-use tokio::stream::StreamMap;\nuse tokio::sync::RwLock;\n-use tokio::task::JoinHandle;\nuse crate::container::{ContainerMapByName, HandleMap as ContainerHandleMap};\nuse crate::handle::StopHandler;\nuse crate::log::{HandleFactory, Sender};\nuse crate::pod::Pod;\n-// use crate::pod::{Status, StatusMessage};\nuse crate::provider::ProviderError;\nuse crate::volume::Ref;\n@@ -19,7 +16,6 @@ use crate::volume::Ref;\n/// access logs\npub struct Handle<H, F> {\ncontainer_handles: RwLock<ContainerHandleMap<H, F>>,\n- status_handle: JoinHandle<()>,\npod: Pod,\n// Storage for the volume references so they don't get dropped until the runtime handle is\n// dropped\n@@ -35,47 +31,10 @@ impl<H: StopHandler, F> Handle<H, F> {\npub async fn new(\ncontainer_handles: ContainerHandleMap<H, F>,\npod: Pod,\n- _client: kube::Client,\nvolumes: Option<HashMap<String, Ref>>,\n- _initial_message: Option<String>,\n) -> anyhow::Result<Self> {\n- // let container_keys: Vec<_> = container_handles.keys().cloned().collect();\n- // pod.initialise_status(&client, &container_keys, initial_message)\n- // .await;\n-\n- let mut channel_map = StreamMap::with_capacity(container_handles.len());\n- for (key, handle) in container_handles.iter() {\n- channel_map.insert(key.clone(), handle.status());\n- }\n- // TODO: This does not allow for restarting single containers because we\n- // move the stream map and lose the ability to insert a new channel for\n- // the restarted runtime. It may involve sending things to the task with\n- // a channel\n- // let cloned_pod = pod.clone();\n- let status_handle = tokio::task::spawn(async move {\n- // loop {\n- // let (name, status) = match channel_map.next().await {\n- // Some(s) => s,\n- // // None means everything is closed, so go ahead and exit\n- // None => {\n- // return;\n- // }\n- // };\n-\n- // let mut container_statuses = HashMap::new();\n- // container_statuses.insert(name, status);\n-\n- // let pod_status = Status {\n- // message: StatusMessage::LeaveUnchanged, // TODO: sure?\n- // container_statuses,\n- // };\n-\n- // cloned_pod.patch_status(client.clone(), pod_status).await;\n- // }\n- });\nOk(Self {\ncontainer_handles: RwLock::new(container_handles),\n- status_handle,\npod,\n_volumes: volumes.unwrap_or_default(),\n})\n@@ -124,7 +83,6 @@ impl<H: StopHandler, F> Handle<H, F> {\nfor (_, handle) in handles.iter_mut() {\nhandle.wait().await?;\n}\n- (&mut self.status_handle).await?;\nOk(())\n}\n}\n" }, { "change_type": "DELETE", "old_path": "crates/kubelet/src/pod/manager.rs", "new_path": null, "diff": "-use crate::pod::Handle;\n-use std::sync::Arc;\n-use tokio::sync::RwLock;\n-use std::collections::BTreeMap;\n-\n-type Name = String;\n-\n-type Namespace = String;\n-\n-#[derive(Clone)]\n-struct PodManager<H,F> {\n- handles: Arc<RwLock<BTreeMap<(Namespace, Name),Handle<H,F>>>>\n-}\n-\n-impl <H,F> PodManager<H,F> {\n- pub fn new() -> Self {\n- PodManager {\n- handles: Arc::new(RwLock::new(BTreeMap::new()))\n- }\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/mod.rs", "new_path": "crates/kubelet/src/pod/mod.rs", "diff": "mod handle;\nmod queue;\nmod status;\n-\npub use handle::{key_from_pod, pod_key, Handle};\npub use queue::PodChange;\npub(crate) use queue::Queue;\n@@ -119,157 +118,6 @@ impl Pod {\nself.0.meta().deletion_timestamp.as_ref().map(|t| &t.0)\n}\n- // /// Patch the pod status using the given status information.\n- // pub async fn patch_status(&self, client: kube::Client, status_changes: Status) {\n- // let name = self.name();\n- // let api: Api<KubePod> = Api::namespaced(client, self.namespace());\n- // let current_k8s_status = match api.get(name).await {\n- // Ok(p) => match p.status {\n- // Some(s) => s,\n- // None => {\n- // error!(\"Pod is missing status information. This should not occur\");\n- // return;\n- // }\n- // },\n- // Err(e) => {\n- // error!(\"Unable to fetch current status of pod {}, aborting status patch (will be retried on next status update): {:?}\", name, e);\n- // return;\n- // }\n- // };\n-\n- // // This section figures out what the current phase of the pod should be\n- // // based on the container statuses\n- // let statuses_to_merge = status_changes\n- // .container_statuses\n- // .into_iter()\n- // .map(|s| (s.0.clone(), s.1.to_kubernetes(s.0.name())))\n- // .collect::<ContainerMap<KubeContainerStatus>>();\n- // let (app_statuses_to_merge, init_statuses_to_merge): (ContainerMap<_>, ContainerMap<_>) =\n- // statuses_to_merge.into_iter().partition(|(k, _)| k.is_app());\n- // // Filter out any ones we are updating and then combine them all together\n- // let mut app_container_statuses = current_k8s_status\n- // .container_statuses\n- // .unwrap_or_default()\n- // .into_iter()\n- // .filter(|s| !app_statuses_to_merge.contains_key(&ContainerKey::App(s.name.clone())))\n- // .collect::<Vec<KubeContainerStatus>>();\n- // let mut init_container_statuses = current_k8s_status\n- // .init_container_statuses\n- // .unwrap_or_default()\n- // .into_iter()\n- // .filter(|s| !init_statuses_to_merge.contains_key(&ContainerKey::Init(s.name.clone())))\n- // .collect::<Vec<KubeContainerStatus>>();\n- // app_container_statuses.extend(app_statuses_to_merge.into_iter().map(|(_, v)| v));\n- // init_container_statuses.extend(init_statuses_to_merge.into_iter().map(|(_, v)| v));\n-\n- // let mut num_succeeded: usize = 0;\n- // let mut failed = false;\n- // // TODO(thomastaylor312): Add inferring a message from these container\n- // // statuses if there is no message passed in the Status object\n- // for status in app_container_statuses\n- // .iter()\n- // .chain(init_container_statuses.iter())\n- // {\n- // // Basically anything is considered running phase in kubernetes\n- // // unless it is explicitly exited, so don't worry about considering\n- // // that state. We only really need to check terminated\n- // if let Some(terminated) = &status.state.as_ref().unwrap().terminated {\n- // if terminated.exit_code != 0 {\n- // failed = true;\n- // break;\n- // } else {\n- // num_succeeded += 1\n- // }\n- // }\n- // }\n-\n- // // TODO: should we have more general-purpose 'container phases' model\n- // // so we don't need parallel app and init logic?\n- // let container_count = app_container_statuses.len() + init_container_statuses.len();\n- // // is there ever a case when we get a status that we should end up in Phase unknown?\n- // let phase = if num_succeeded >= container_count {\n- // Phase::Succeeded\n- // } else if failed {\n- // Phase::Failed\n- // } else {\n- // Phase::Running\n- // };\n-\n- // // TODO: init container statuses need to be reported through initContainerStatuses\n-\n- // let mut json_status = serde_json::json!(\n- // {\n- // \"metadata\": {\n- // \"resourceVersion\": \"\",\n- // },\n- // \"status\": {\n- // \"phase\": phase,\n- // \"containerStatuses\": app_container_statuses,\n- // \"initContainerStatuses\": init_container_statuses,\n- // }\n- // }\n- // );\n-\n- // if let Some(map) = json_status.as_object_mut() {\n- // if let Some(status_json) = map.get_mut(\"status\") {\n- // if let Some(status_map) = status_json.as_object_mut() {\n- // let message_key = \"message\".to_owned();\n- // match status_changes.message {\n- // StatusMessage::LeaveUnchanged => (),\n- // StatusMessage::Clear => {\n- // status_map.insert(message_key, serde_json::Value::Null);\n- // }\n- // StatusMessage::Message(m) => {\n- // status_map.insert(message_key, serde_json::Value::String(m));\n- // }\n- // }\n- // }\n- // }\n- // }\n-\n- // debug!(\"Setting pod status for {} using {:?}\", name, json_status);\n-\n- // let data = serde_json::to_vec(&json_status).expect(\"Should always serialize\");\n- // match api.patch_status(&name, &PatchParams::default(), data).await {\n- // Ok(o) => debug!(\"Pod status returned: {:#?}\", o.status),\n- // Err(e) => error!(\"Pod status update failed for {}: {}\", name, e),\n- // }\n- // }\n-\n- // /// Sets the status of all specified containers to Waiting, and optionally\n- // /// sets the pod status message.\n- // pub async fn initialise_status(\n- // &self,\n- // client: &kube::Client,\n- // container_keys: &[ContainerKey],\n- // initial_message: Option<String>,\n- // ) {\n- // let all_containers_waiting = Self::all_waiting(container_keys);\n-\n- // let initial_status_message = match initial_message {\n- // Some(m) => StatusMessage::Message(m),\n- // None => StatusMessage::Clear,\n- // };\n-\n- // let all_waiting = Status {\n- // message: initial_status_message,\n- // container_statuses: all_containers_waiting,\n- // };\n- // self.patch_status(client.clone(), all_waiting).await;\n- // }\n-\n- // fn all_waiting(container_keys: &[ContainerKey]) -> ContainerMap<crate::container::Status> {\n- // let mut all_waiting_map = HashMap::new();\n- // for key in container_keys {\n- // let waiting = crate::container::Status::Waiting {\n- // timestamp: chrono::Utc::now(),\n- // message: \"PodInitializing\".to_owned(),\n- // };\n- // all_waiting_map.insert(key.clone(), waiting);\n- // }\n- // all_waiting_map\n- // }\n-\n/// Get a pod's containers\npub fn containers(&self) -> Vec<Container> {\nself.0\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -6,7 +6,6 @@ use kube::api::{Meta, WatchEvent};\nuse kube::Client as KubeClient;\nuse log::{debug, error, info};\nuse tokio::sync::watch;\n-use tokio::task::JoinHandle;\nuse crate::pod::{pod_key, Pod};\nuse crate::provider::Provider;\n@@ -22,23 +21,41 @@ pub enum PodChange {\nDelete,\n}\n-struct Worker {\n- sender: watch::Sender<WatchEvent<KubePod>>,\n- _worker: JoinHandle<()>,\n+/// A per-pod queue that takes incoming Kubernetes events and broadcasts them to the correct queue\n+/// for that pod.\n+///\n+/// It will also send a error out on the given sender that can be handled in another process (namely\n+/// the main kubelet process). This queue will only handle the latest update. So if a modify comes\n+/// in while it is still handling a create and then another modify comes in after, only the second\n+/// modify will be handled, which is ok given that each event contains the whole pod object\n+pub(crate) struct Queue<P> {\n+ provider: Arc<P>,\n+ handlers: HashMap<String, watch::Sender<WatchEvent<KubePod>>>,\n+ client: KubeClient,\n+}\n+\n+impl<P: 'static + Provider + Sync + Send> Queue<P> {\n+ pub fn new(provider: Arc<P>, client: KubeClient) -> Self {\n+ Queue {\n+ provider,\n+ handlers: HashMap::new(),\n+ client,\n+ }\n}\n-impl Worker {\n- fn create<P>(initial_event: WatchEvent<KubePod>, provider: Arc<P>, client: KubeClient) -> Self\n- where\n- P: 'static + Provider + Sync + Send,\n- {\n+ async fn run_pod(\n+ &self,\n+ initial_event: WatchEvent<KubePod>,\n+ ) -> anyhow::Result<watch::Sender<WatchEvent<KubePod>>> {\nlet (sender, mut receiver) = watch::channel(initial_event);\n// These should be set on the first Add.\nlet mut pod_definition: Option<KubePod> = None;\nlet mut state_tx: Option<tokio::sync::mpsc::Sender<PodChange>> = None;\n- let worker = tokio::spawn(async move {\n+ let task_provider = Arc::clone(&self.provider);\n+ let task_client = self.client.clone();\n+ tokio::spawn(async move {\nwhile let Some(event) = receiver.recv().await {\n// Watch errors are handled before an event ever gets here, so it should always have\n// a pod\n@@ -52,8 +69,9 @@ impl Worker {\nstate_tx = Some(tx);\npod_definition = Some(pod.clone());\n- let client = client.clone();\n- let pod_state: P::PodState = provider.initialize_pod_state().await.unwrap();\n+ let client = task_client.clone();\n+ let pod_state: P::PodState =\n+ task_provider.initialize_pod_state().await.unwrap();\ntokio::spawn(async move {\nlet state: P::InitialState = Default::default();\nlet pod = Pod::new(pod);\n@@ -89,33 +107,7 @@ impl Worker {\n}\n}\n});\n- Worker {\n- sender,\n- _worker: worker,\n- }\n- }\n-}\n-\n-/// A per-pod queue that takes incoming Kubernetes events and broadcasts them to the correct queue\n-/// for that pod.\n-///\n-/// It will also send a error out on the given sender that can be handled in another process (namely\n-/// the main kubelet process). This queue will only handle the latest update. So if a modify comes\n-/// in while it is still handling a create and then another modify comes in after, only the second\n-/// modify will be handled, which is ok given that each event contains the whole pod object\n-pub(crate) struct Queue<P> {\n- provider: Arc<P>,\n- handlers: HashMap<String, Worker>,\n- client: KubeClient,\n-}\n-\n-impl<P: 'static + Provider + Sync + Send> Queue<P> {\n- pub fn new(provider: Arc<P>, client: KubeClient) -> Self {\n- Queue {\n- provider,\n- handlers: HashMap::new(),\n- client,\n- }\n+ Ok(sender)\n}\npub async fn enqueue(&mut self, event: WatchEvent<KubePod>) -> anyhow::Result<()> {\n@@ -129,21 +121,19 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nlet key = pod_key(&pod_namespace, &pod_name);\n// We are explicitly not using the entry api here to insert to avoid the need for a\n// mutex\n- let handler = match self.handlers.get(&key) {\n- Some(h) => h,\n+ let sender = match self.handlers.get(&key) {\n+ Some(s) => s,\nNone => {\nself.handlers.insert(\nkey.clone(),\n- Worker::create::<P>(\n- event.clone(),\n- Arc::clone(&self.provider),\n- self.client.clone(),\n- ),\n+ // TODO Do we want to capture join handles? Worker wasnt using them.\n+ // TODO Does this mean we handle the Add event twice?\n+ self.run_pod(event.clone()).await?,\n);\nself.handlers.get(&key).unwrap()\n}\n};\n- match handler.sender.broadcast(event) {\n+ match sender.broadcast(event) {\nOk(_) => debug!(\n\"successfully sent event to handler for pod {} in namespace {}\",\npod_name, pod_namespace\n" }, { "change_type": "DELETE", "old_path": "crates/kubelet/src/state/default.rs", "new_path": null, "diff": "-//! Default implementation for state machine graph.\n-\n-use crate::pod::Pod;\n-use crate::pod::Phase;\n-use crate::state;\n-use crate::state::State;\n-use crate::state::Transition;\n-use log::error;\n-use std::sync::Arc;\n-\n-#[async_trait::async_trait]\n-/// Trait for implementing default state machine.\n-pub trait DefaultStateProvider: 'static + Sync + Send {\n- /// A new Pod has been created.\n- async fn registered(&self, _pod: &Pod) -> anyhow::Result<()> {\n- Ok(())\n- }\n-\n- /// Pull images for containers.\n- async fn image_pull(&self, _pod: &Pod) -> anyhow::Result<()> {\n- Ok(())\n- }\n-\n- /// Image pull has failed several times.\n- async fn image_pull_backoff(&self, _pod: &Pod) -> anyhow::Result<()> {\n- tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n- Ok(())\n- }\n-\n- /// Mount volumes for containers.\n- async fn volume_mount(&self, _pod: &Pod) -> anyhow::Result<()> {\n- Ok(())\n- }\n-\n- /// Volume mount has failed several times.\n- async fn volume_mount_backoff(&self, _pod: &Pod) -> anyhow::Result<()> {\n- tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n- Ok(())\n- }\n-\n- /// Start containers.\n- async fn starting(&self, _pod: &Pod) -> anyhow::Result<()> {\n- Ok(())\n- }\n-\n- /// Running state.\n- async fn running(&self, _pod: &Pod) -> anyhow::Result<()> {\n- Ok(())\n- }\n-\n- /// Handle any errors, on Ok, will transition to Starting again.\n- async fn error(&self, _pod: &Pod) -> anyhow::Result<()> {\n- tokio::time::delay_for(std::time::Duration::from_secs(30)).await;\n- Ok(())\n- }\n-}\n-\n-//\n-// * Would be nice to support passing types to the next state (error messages, etc.).\n-// * We probably need to explore a more concise way for describing status patches.\n-// * Can we offer a macro that doesnt require a trait?\n-// * How can we expose a nice way for updating container statuses?\n-//\n-\n-state!(\n- /// The Kubelet is aware of the Pod.\n- Registered,\n- DefaultStateProvider,\n- ImagePull,\n- Error,\n- {\n- match provider.registered(pod).await {\n- Ok(_) => Ok(Transition::Advance(ImagePull)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(Error))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Pending,\n- \"reason\": \"Registered\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Kubelet is pulling container images.\n- ImagePull,\n- DefaultStateProvider,\n- VolumeMount,\n- ImagePullBackoff,\n- {\n- match provider.image_pull(pod).await {\n- Ok(_) => Ok(Transition::Advance(VolumeMount)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(ImagePullBackoff))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Pending,\n- \"reason\": \"ImagePull\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// Image pull has failed several times.\n- ImagePullBackoff,\n- DefaultStateProvider,\n- ImagePull,\n- ImagePullBackoff,\n- {\n- match provider.image_pull_backoff(pod).await {\n- Ok(_) => Ok(Transition::Advance(ImagePull)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(ImagePullBackoff))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Pending,\n- \"reason\": \"ImagePullBackoff\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Kubelet is provisioning volumes.\n- VolumeMount,\n- DefaultStateProvider,\n- Starting,\n- VolumeMountBackoff,\n- {\n- match provider.volume_mount(pod).await {\n- Ok(_) => Ok(Transition::Advance(Starting)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(VolumeMountBackoff))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Pending,\n- \"reason\": \"VolumeMount\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// Volume mount has failed several times.\n- VolumeMountBackoff,\n- DefaultStateProvider,\n- VolumeMount,\n- VolumeMountBackoff,\n- {\n- match provider.volume_mount_backoff(pod).await {\n- Ok(_) => Ok(Transition::Advance(VolumeMount)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(VolumeMountBackoff))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Pending,\n- \"reason\": \"VolumeMountBackoff\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Kubelet is starting the containers.\n- Starting,\n- DefaultStateProvider,\n- Running,\n- Error,\n- {\n- match provider.starting(pod).await {\n- Ok(_) => Ok(Transition::Advance(Running)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(Error))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Pending,\n- \"reason\": \"Starting\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Kubelet is provisioning volumes.\n- Running,\n- DefaultStateProvider,\n- Finished,\n- Error,\n- {\n- match provider.running(pod).await {\n- Ok(_) => Ok(Transition::Advance(Finished)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(Error))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Running,\n- \"reason\": \"Running\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Pod encountered an error.\n- Error,\n- DefaultStateProvider,\n- Starting,\n- Error,\n- {\n- match provider.error(pod).await {\n- Ok(_) => Ok(Transition::Advance(Starting)),\n- Err(e) => {\n- error!(\n- \"Pod {} encountered an error in state {:?}: {:?}\",\n- pod.name(),\n- Self,\n- e\n- );\n- Ok(Transition::Error(Error))\n- }\n- }\n- },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Failed,\n- \"reason\": \"Error\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Pod was terminated before it completed.\n- Terminated,\n- DefaultStateProvider,\n- Terminated,\n- Terminated,\n- { Ok(Transition::Complete(Ok(()))) },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Failed,\n- \"reason\": \"Failed\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n-\n-state!(\n- /// The Pod completed execution with no errors.\n- Finished,\n- DefaultStateProvider,\n- Finished,\n- Finished,\n- { Ok(Transition::Complete(Ok(()))) },\n- {\n- Ok(serde_json::json!(\n- {\n- \"metadata\": {\n- \"resourceVersion\": \"\",\n- },\n- \"status\": {\n- \"phase\": Phase::Succeeded,\n- \"reason\": \"Failed\",\n- \"containerStatuses\": Vec::<()>::new(),\n- \"initContainerStatuses\": Vec::<()>::new(),\n- }\n- }\n- ))\n- }\n-);\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Clean up some files.
350,405
23.08.2020 12:01:06
-43,200
1b72d0c226c22bc9663231e4a2dee9e7d4608af8
Clippy is just very very disappointed in me
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/volume/mod.rs", "new_path": "crates/kubelet/src/volume/mod.rs", "diff": "@@ -218,13 +218,13 @@ fn pod_dir_name(pod: &Pod) -> String {\nformat!(\"{}-{}\", pod.name(), pod.namespace())\n}\n-fn mount_setting_for(key: &String, items_to_mount: &Option<Vec<KeyToPath>>) -> ItemMount {\n+fn mount_setting_for(key: &str, items_to_mount: &Option<Vec<KeyToPath>>) -> ItemMount {\nmatch items_to_mount {\nNone => ItemMount::MountAt(key.to_string()),\nSome(items) => ItemMount::from(\nitems\n.iter()\n- .find(|kp| &kp.key == key)\n+ .find(|kp| kp.key == key)\n.map(|kp| kp.path.to_string()),\n),\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -93,10 +93,13 @@ impl TryFrom<String> for Reference {\nlet tag_start = match (digest_start, first_colon) {\n// Check if a colon comes before a digest delimeter, indicating\n// that image ref is in the form registry/repo:tag@digest\n- (Some(ds), Some(fc)) => match fc < ds {\n- true => Some(fc),\n- false => None,\n- },\n+ (Some(ds), Some(fc)) => {\n+ if fc < ds {\n+ Some(fc)\n+ } else {\n+ None\n+ }\n+ }\n// No digest delimeter was found but a colon is present, so ref\n// must be in the form registry/repo:tag\n(None, Some(fc)) => Some(fc),\n" }, { "change_type": "MODIFY", "old_path": "tests/oneclick/src/main.rs", "new_path": "tests/oneclick/src/main.rs", "diff": "@@ -84,12 +84,13 @@ fn build_workspace() -> anyhow::Result<()> {\n.args(&[\"build\"])\n.output()?;\n- match build_result.status.success() {\n- true => Ok(()),\n- false => Err(anyhow::anyhow!(\n+ if build_result.status.success() {\n+ Ok(())\n+ } else {\n+ Err(anyhow::anyhow!(\n\"{}\",\nString::from_utf8(build_result.stderr).unwrap()\n- )),\n+ ))\n}\n}\n@@ -165,7 +166,7 @@ fn prepare_for_bootstrap() -> BootstrapReadiness {\n// We have now deleted all the local certificate files, and all the CSRs that\n// might get in the way of our re-bootstrapping. Let the caller know they\n// will need to re-approve once the new CSRs come up.\n- return BootstrapReadiness::NeedBootstrapAndApprove;\n+ BootstrapReadiness::NeedBootstrapAndApprove\n}\nenum AllOrNone {\n@@ -229,10 +230,10 @@ fn is_resource_gone(kubectl_output: &std::process::Output) -> bool {\nfn run_bootstrap() -> anyhow::Result<()> {\nlet (shell, ext) = match std::env::consts::OS {\n- \"windows\" => (\"powershell.exe\", \"ps1\"),\n- \"linux\" | \"macos\" => (\"bash\", \"sh\"),\n- os => Err(anyhow::anyhow!(\"Unsupported OS {}\", os))?,\n- };\n+ \"windows\" => Ok((\"powershell.exe\", \"ps1\")),\n+ \"linux\" | \"macos\" => Ok((\"bash\", \"sh\")),\n+ os => Err(anyhow::anyhow!(\"Unsupported OS {}\", os)),\n+ }?;\nlet repo_root = std::env!(\"CARGO_MANIFEST_DIR\");\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Clippy is just very very disappointed in me (#361)
350,405
23.08.2020 12:01:40
-43,200
4a0874b079a35641e104de6728beddcd7d061e03
Suppress deprecation warnings from Informer (for now)
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/bootstrapping/mod.rs", "new_path": "crates/kubelet/src/bootstrapping/mod.rs", "diff": "+#![allow(deprecated)] // TODO: remove when Informer has been replaced by kube_run::watcher\n+\nuse std::{convert::TryFrom, env, path::Path, str};\nuse futures::{StreamExt, TryStreamExt};\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/kubelet.rs", "new_path": "crates/kubelet/src/kubelet.rs", "diff": "+#![allow(deprecated)] // TODO: remove when Informer has been replaced by kube_run::watcher\n+\n///! This library contains code for running a kubelet. Use this to create a new\n///! Kubelet with a specific handler (called a `Provider`)\nuse crate::config::Config;\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Suppress deprecation warnings from Informer (for now) (#360)
350,405
24.08.2020 08:05:26
-43,200
749a0977c38e68da3cdc544ec8c8cfb564242336
Insecure registries
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/config.rs", "new_path": "crates/kubelet/src/config.rs", "diff": "@@ -56,6 +56,9 @@ pub struct Config {\n/// Whether to allow modules to be loaded directly from local\n/// filesystem paths, as well as from registries\npub allow_local_modules: bool,\n+ /// Registries that should be accessed using HTTP instead of\n+ /// HTTPS.\n+ pub insecure_registries: Option<Vec<String>>,\n}\n/// The configuration for the Kubelet server.\n#[derive(Clone, Debug)]\n@@ -111,6 +114,8 @@ struct ConfigBuilder {\npub server_tls_private_key_file: Option<PathBuf>,\n#[serde(default, rename = \"allowLocalModules\")]\npub allow_local_modules: Option<bool>,\n+ #[serde(default, rename = \"insecureRegistries\")]\n+ pub insecure_registries: Option<Vec<String>>,\n}\nstruct ConfigBuilderFallbacks {\n@@ -142,6 +147,7 @@ impl Config {\nmax_pods: DEFAULT_MAX_PODS,\nbootstrap_file: PathBuf::from(BOOTSTRAP_FILE),\nallow_local_modules: false,\n+ insecure_registries: None,\nserver_config: ServerConfig {\naddr: match preferred_ip_family {\n// Just unwrap these because they are programmer error if they\n@@ -266,6 +272,7 @@ impl ConfigBuilder {\ndata_dir: opts.data_dir,\nmax_pods: ok_result_of(opts.max_pods),\nallow_local_modules: opts.allow_local_modules,\n+ insecure_registries: opts.insecure_registries.map(parse_comma_separated),\nserver_addr: ok_result_of(opts.addr),\nserver_port: ok_result_of(opts.port),\nserver_tls_cert_file: opts.cert_file,\n@@ -301,6 +308,7 @@ impl ConfigBuilder {\nserver_tls_cert_file: other.server_tls_cert_file.or(self.server_tls_cert_file),\nbootstrap_file: other.bootstrap_file.or(self.bootstrap_file),\nallow_local_modules: other.allow_local_modules.or(self.allow_local_modules),\n+ insecure_registries: other.insecure_registries.or(self.insecure_registries),\nserver_tls_private_key_file: other\n.server_tls_private_key_file\n.or(self.server_tls_private_key_file),\n@@ -348,6 +356,7 @@ impl ConfigBuilder {\nmax_pods,\nbootstrap_file,\nallow_local_modules: self.allow_local_modules.unwrap_or(false),\n+ insecure_registries: self.insecure_registries,\nserver_config: ServerConfig {\ncert_file: server_tls_cert_file,\nprivate_key_file: server_tls_private_key_file,\n@@ -482,6 +491,13 @@ pub struct Opts {\nhelp = \"(Experimental) Whether to allow loading modules directly from the filesystem\"\n)]\nallow_local_modules: Option<bool>,\n+\n+ #[structopt(\n+ long = \"insecure-registries\",\n+ env = \"KRUSTLET_INSECURE_REGISTRIES\",\n+ help = \"Registries that should be accessed over HTTP instead of HTTPS (comma separated)\"\n+ )]\n+ insecure_registries: Option<String>,\n}\nfn default_hostname() -> anyhow::Result<String> {\n@@ -570,6 +586,10 @@ fn invalid_config_value_error(e: anyhow::Error, value_name: &str) -> anyhow::Err\ne.context(context)\n}\n+fn parse_comma_separated(source: String) -> Vec<String> {\n+ source.split(',').map(|s| s.trim().to_owned()).collect()\n+}\n+\n#[cfg(test)]\nmod test {\nuse super::*;\n@@ -607,7 +627,11 @@ mod test {\n\"tlsCertificateFile\": \"/my/secure/cert.pfx\",\n\"tlsPrivateKeyFile\": \"/the/key\",\n\"bootstrapFile\": \"/the/bootstrap/file.txt\",\n- \"allowLocalModules\": true\n+ \"allowLocalModules\": true,\n+ \"insecureRegistries\": [\n+ \"local\",\n+ \"dev\"\n+ ]\n}\"#,\n);\nlet config = config_builder.unwrap().build(fallbacks()).unwrap();\n@@ -633,6 +657,9 @@ mod test {\nassert_eq!(config.allow_local_modules, true);\nassert_eq!(config.node_labels.len(), 2);\nassert_eq!(config.node_labels.get(\"label1\"), Some(&(\"val1\".to_owned())));\n+ assert_eq!(config.insecure_registries.clone().unwrap().len(), 2);\n+ assert_eq!(&config.insecure_registries.clone().unwrap()[0], \"local\");\n+ assert_eq!(&config.insecure_registries.clone().unwrap()[1], \"dev\");\n}\n#[test]\n@@ -688,6 +715,7 @@ mod test {\nassert_eq!(config.data_dir.to_string_lossy(), \"/fallback/data/dir\");\nassert_eq!(format!(\"{}\", config.node_ip), \"4.4.4.4\");\nassert_eq!(config.allow_local_modules, false);\n+ assert_eq!(config.insecure_registries, None);\nassert_eq!(config.node_labels.len(), 0);\n}\n@@ -719,6 +747,7 @@ mod test {\n},\n\"nodeName\": \"krusty-node\",\n\"allowLocalModules\": true,\n+ \"insecureRegistries\": [\"local1\", \"local2\"],\n\"tlsCertificateFile\": \"/my/secure/cert.pfx\",\n\"tlsPrivateKeyFile\": \"/the/key\"\n}\"#,\n@@ -737,6 +766,7 @@ mod test {\n},\n\"nodeName\": \"krusty-node-2\",\n\"allowLocalModules\": false,\n+ \"insecureRegistries\": [\"local\"],\n\"tlsCertificateFile\": \"/my/secure/cert-2.pfx\",\n\"tlsPrivateKeyFile\": \"/the/2nd/key\"\n}\"#,\n@@ -759,6 +789,8 @@ mod test {\nassert_eq!(config.data_dir.to_string_lossy(), \"/krusty/data/dir/2\");\nassert_eq!(format!(\"{}\", config.node_ip), \"173.183.193.22\");\nassert_eq!(config.allow_local_modules, false);\n+ assert_eq!(config.insecure_registries.clone().unwrap().len(), 1);\n+ assert_eq!(&config.insecure_registries.clone().unwrap()[0], \"local\");\nassert_eq!(config.node_labels.len(), 2);\nassert_eq!(\nconfig.node_labels.get(\"label21\"),\n@@ -781,6 +813,7 @@ mod test {\n},\n\"nodeName\": \"krusty-node\",\n\"allowLocalModules\": true,\n+ \"insecureRegistries\": [\"local\"],\n\"tlsCertificateFile\": \"/my/secure/cert.pfx\",\n\"tlsPrivateKeyFile\": \"/the/key\"\n}\"#,\n@@ -809,6 +842,8 @@ mod test {\nassert_eq!(config.data_dir.to_string_lossy(), \"/krusty/data/dir\");\nassert_eq!(format!(\"{}\", config.node_ip), \"173.183.193.2\");\nassert_eq!(config.allow_local_modules, true);\n+ assert_eq!(config.insecure_registries.clone().unwrap().len(), 1);\n+ assert_eq!(&config.insecure_registries.clone().unwrap()[0], \"local\");\nassert_eq!(config.node_labels.len(), 2);\nassert_eq!(config.node_labels.get(\"label1\"), Some(&(\"val1\".to_owned())));\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "crates/kubelet/src/config_interpreter.rs", "diff": "+//! Functions for constructing 'useful' objects from configuration\n+//! data in 'sensible' ways.\n+\n+use crate::config::Config;\n+use oci_distribution::client::{ClientConfig, ClientConfigSource, ClientProtocol};\n+\n+impl ClientConfigSource for Config {\n+ fn client_config(&self) -> ClientConfig {\n+ let protocol = match &self.insecure_registries {\n+ None => ClientProtocol::default(),\n+ Some(registries) => ClientProtocol::HttpsExcept(registries.clone()),\n+ };\n+ ClientConfig { protocol }\n+ }\n+}\n+\n+#[cfg(test)]\n+mod test {\n+ use super::*;\n+\n+ fn empty_config() -> Config {\n+ // We can't use Config::default() because it can panic when trying\n+ // to derive a node IP address\n+ Config {\n+ allow_local_modules: false,\n+ bootstrap_file: std::path::PathBuf::from(\"/nope\"),\n+ data_dir: std::path::PathBuf::from(\"/nope\"),\n+ hostname: \"nope\".to_owned(),\n+ insecure_registries: None,\n+ max_pods: 0,\n+ node_ip: \"127.0.0.1\".parse().unwrap(),\n+ node_labels: std::collections::HashMap::new(),\n+ node_name: \"nope\".to_owned(),\n+ server_config: crate::config::ServerConfig {\n+ addr: \"127.0.0.1\".parse().unwrap(),\n+ port: 0,\n+ cert_file: std::path::PathBuf::from(\"/nope\"),\n+ private_key_file: std::path::PathBuf::from(\"/nope\"),\n+ },\n+ }\n+ }\n+\n+ #[test]\n+ fn oci_config_defaults_to_https() {\n+ let config = empty_config();\n+ let client_config = config.client_config();\n+ assert_eq!(ClientProtocol::Https, client_config.protocol);\n+ }\n+\n+ #[test]\n+ fn oci_config_respects_config_insecure_registries() {\n+ let mut config = empty_config();\n+ config.insecure_registries = Some(vec![\"local\".to_owned(), \"dev\".to_owned()]);\n+ let client_config = config.client_config();\n+\n+ let expected_protocol =\n+ ClientProtocol::HttpsExcept(vec![\"local\".to_owned(), \"dev\".to_owned()]);\n+ assert_eq!(expected_protocol, client_config.protocol);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/lib.rs", "new_path": "crates/kubelet/src/lib.rs", "diff": "#![cfg_attr(feature = \"docs\", feature(doc_cfg))]\nmod bootstrapping;\n+mod config_interpreter;\nmod kubelet;\npub(crate) mod kubeconfig;\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "@@ -753,6 +753,7 @@ mod test {\n},\nbootstrap_file: \"doesnt/matter\".into(),\nallow_local_modules: false,\n+ insecure_registries: None,\ndata_dir: PathBuf::new(),\nnode_labels,\nmax_pods: 110,\n" }, { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -47,6 +47,14 @@ pub struct Client {\nclient: reqwest::Client,\n}\n+/// A source that can provide a `ClientConfig`.\n+/// If you are using this crate in your own application, you can implement this\n+/// trait on your configuration type so that it can be passed to `Client::from_source`.\n+pub trait ClientConfigSource {\n+ /// Provides a `ClientConfig`.\n+ fn client_config(&self) -> ClientConfig;\n+}\n+\nimpl Client {\n/// Create a new client with the supplied config\npub fn new(config: ClientConfig) -> Self {\n@@ -57,6 +65,11 @@ impl Client {\n}\n}\n+ /// Create a new client with the supplied config\n+ pub fn from_source(config_source: &impl ClientConfigSource) -> Self {\n+ Self::new(config_source.client_config())\n+ }\n+\n/// Pull an image and return the bytes\n///\n/// The client will check if it's already been authenticated and if\n@@ -105,7 +118,7 @@ impl Client {\n// The version request will tell us where to go.\nlet url = format!(\n\"{}://{}/v2/\",\n- self.config.protocol.as_str(),\n+ self.config.protocol.scheme_for(image.registry()),\nimage.registry()\n);\nlet res = self.client.get(&url).send().await?;\n@@ -268,7 +281,7 @@ impl Client {\nif let Some(digest) = reference.digest() {\nformat!(\n\"{}://{}/v2/{}/manifests/{}\",\n- self.config.protocol.as_str(),\n+ self.config.protocol.scheme_for(reference.registry()),\nreference.registry(),\nreference.repository(),\ndigest,\n@@ -276,7 +289,7 @@ impl Client {\n} else {\nformat!(\n\"{}://{}/v2/{}/manifests/{}\",\n- self.config.protocol.as_str(),\n+ self.config.protocol.scheme_for(reference.registry()),\nreference.registry(),\nreference.repository(),\nreference.tag().unwrap_or(\"latest\")\n@@ -288,7 +301,7 @@ impl Client {\nfn to_v2_blob_url(&self, registry: &str, repository: &str, digest: &str) -> String {\nformat!(\n\"{}://{}/v2/{}/blobs/{}\",\n- self.config.protocol.as_str(),\n+ self.config.protocol.scheme_for(registry),\nregistry,\nrepository,\ndigest,\n@@ -319,12 +332,14 @@ pub struct ClientConfig {\n}\n/// The protocol that the client should use to connect\n-#[derive(Debug, Clone)]\n+#[derive(Debug, Clone, PartialEq)]\npub enum ClientProtocol {\n#[allow(missing_docs)]\nHttp,\n#[allow(missing_docs)]\nHttps,\n+ #[allow(missing_docs)]\n+ HttpsExcept(Vec<String>),\n}\nimpl Default for ClientProtocol {\n@@ -334,10 +349,17 @@ impl Default for ClientProtocol {\n}\nimpl ClientProtocol {\n- fn as_str(&self) -> &str {\n+ fn scheme_for(&self, registry: &str) -> &str {\nmatch self {\nClientProtocol::Https => \"https\",\nClientProtocol::Http => \"http\",\n+ ClientProtocol::HttpsExcept(exceptions) => {\n+ if exceptions.contains(&registry.to_owned()) {\n+ \"http\"\n+ } else {\n+ \"https\"\n+ }\n+ }\n}\n}\n}\n@@ -453,6 +475,96 @@ mod test {\n}\n}\n+ #[test]\n+ fn manifest_url_generation_respects_http_protocol() {\n+ let c = Client::new(ClientConfig {\n+ protocol: ClientProtocol::Http,\n+ });\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\".to_owned())\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"http://webassembly.azurecr.io/v2/hello/manifests/v1\",\n+ c.to_v2_manifest_url(&reference)\n+ );\n+ }\n+\n+ #[test]\n+ fn blob_url_generation_respects_http_protocol() {\n+ let c = Client::new(ClientConfig {\n+ protocol: ClientProtocol::Http,\n+ });\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello@sha256:1234\".to_owned())\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"http://webassembly.azurecr.io/v2/hello/blobs/sha256:1234\",\n+ c.to_v2_blob_url(\n+ &reference.registry(),\n+ reference.repository(),\n+ reference.digest().unwrap()\n+ )\n+ );\n+ }\n+\n+ #[test]\n+ fn manifest_url_generation_uses_https_if_not_on_exception_list() {\n+ let insecure_registries = vec![\"localhost\".to_owned(), \"oci.registry.local\".to_owned()];\n+ let protocol = ClientProtocol::HttpsExcept(insecure_registries);\n+ let c = Client::new(ClientConfig { protocol });\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello:v1\".to_owned())\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"https://webassembly.azurecr.io/v2/hello/manifests/v1\",\n+ c.to_v2_manifest_url(&reference)\n+ );\n+ }\n+\n+ #[test]\n+ fn manifest_url_generation_uses_http_if_on_exception_list() {\n+ let insecure_registries = vec![\"localhost\".to_owned(), \"oci.registry.local\".to_owned()];\n+ let protocol = ClientProtocol::HttpsExcept(insecure_registries);\n+ let c = Client::new(ClientConfig { protocol });\n+ let reference = Reference::try_from(\"oci.registry.local/hello:v1\".to_owned())\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"http://oci.registry.local/v2/hello/manifests/v1\",\n+ c.to_v2_manifest_url(&reference)\n+ );\n+ }\n+\n+ #[test]\n+ fn blob_url_generation_uses_https_if_not_on_exception_list() {\n+ let insecure_registries = vec![\"localhost\".to_owned(), \"oci.registry.local\".to_owned()];\n+ let protocol = ClientProtocol::HttpsExcept(insecure_registries);\n+ let c = Client::new(ClientConfig { protocol });\n+ let reference = Reference::try_from(\"webassembly.azurecr.io/hello@sha256:1234\".to_owned())\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"https://webassembly.azurecr.io/v2/hello/blobs/sha256:1234\",\n+ c.to_v2_blob_url(\n+ &reference.registry(),\n+ reference.repository(),\n+ reference.digest().unwrap()\n+ )\n+ );\n+ }\n+\n+ #[test]\n+ fn blob_url_generation_uses_http_if_on_exception_list() {\n+ let insecure_registries = vec![\"localhost\".to_owned(), \"oci.registry.local\".to_owned()];\n+ let protocol = ClientProtocol::HttpsExcept(insecure_registries);\n+ let c = Client::new(ClientConfig { protocol });\n+ let reference = Reference::try_from(\"oci.registry.local/hello@sha256:1234\".to_owned())\n+ .expect(\"Could not parse reference\");\n+ assert_eq!(\n+ \"http://oci.registry.local/v2/hello/blobs/sha256:1234\",\n+ c.to_v2_blob_url(\n+ &reference.registry(),\n+ reference.repository(),\n+ reference.digest().unwrap()\n+ )\n+ );\n+ }\n+\n#[tokio::test]\nasync fn test_auth() {\nfor &image in TEST_IMAGES {\n" }, { "change_type": "MODIFY", "old_path": "docs/topics/configuration.md", "new_path": "docs/topics/configuration.md", "diff": "@@ -26,6 +26,7 @@ kubelet implementers\" section below.\n| -p, --port | KRUSTLET_PORT | listenerPort | The port on which the kubelet should listen. The default is 3000 |\n| --cert-file | KRUSTLET_CERT_FILE | tlsCertificateFile | The path to the TLS certificate for the kubelet. The default is `(data directory)/config/krustlet.crt` |\n| --private-key-file | KRUSTLET_PRIVATE_KEY_FILE | tlsPrivateKeyFile | The path to the private key for the TLS certificate. The default is `(data directory)/config/krustlet.key` |\n+| --insecure-registries | KRUSTLET_INSECURE_REGISTRIES | insecureRegistries | A list of registries that should be accessed using HTTP instead of HTTPS. On the command line or environment variable, use commas to separate multiple registries |\n| --x-allow-local-modules | KRUSTLET_ALLOW_LOCAL_MODULES | allowLocalModules | If true, the kubelet should recognise references prefixed with 'fs' as indicating a filesystem path rather than a registry location. This is an experimental flag for use in development scenarios where you don't want to repeatedly push your local builds to a registry; it is likely to be removed in a future version when we have a more comprehensive toolchain for local development. |\n## Node labels format\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wascc.rs", "new_path": "src/krustlet-wascc.rs", "diff": "@@ -24,7 +24,7 @@ async fn main() -> anyhow::Result<()> {\n}\nfn make_store(config: &Config) -> Arc<dyn kubelet::store::Store + Send + Sync> {\n- let client = oci_distribution::Client::default();\n+ let client = oci_distribution::Client::from_source(config);\nlet mut store_path = config.data_dir.join(\".oci\");\nstore_path.push(\"modules\");\nlet file_store = Arc::new(FileStore::new(client, &store_path));\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wasi.rs", "new_path": "src/krustlet-wasi.rs", "diff": "@@ -24,7 +24,7 @@ async fn main() -> anyhow::Result<()> {\n}\nfn make_store(config: &Config) -> Arc<dyn kubelet::store::Store + Send + Sync> {\n- let client = oci_distribution::Client::default();\n+ let client = oci_distribution::Client::from_source(config);\nlet mut store_path = config.data_dir.join(\".oci\");\nstore_path.push(\"modules\");\nlet file_store = Arc::new(FileStore::new(client, &store_path));\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Insecure registries (#359)
350,426
24.08.2020 08:46:26
18,000
d48e63929dd5f127f495f2de56e28be8f7401ca9
Clean up pod queue
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -4,8 +4,7 @@ use std::sync::Arc;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Meta, WatchEvent};\nuse kube::Client as KubeClient;\n-use log::{debug, error, info};\n-use tokio::sync::watch;\n+use log::{debug, error, info, warn};\nuse crate::pod::{pod_key, Pod};\nuse crate::provider::Provider;\n@@ -30,7 +29,7 @@ pub enum PodChange {\n/// modify will be handled, which is ok given that each event contains the whole pod object\npub(crate) struct Queue<P> {\nprovider: Arc<P>,\n- handlers: HashMap<String, watch::Sender<WatchEvent<KubePod>>>,\n+ handlers: HashMap<String, tokio::sync::mpsc::Sender<WatchEvent<KubePod>>>,\nclient: KubeClient,\n}\n@@ -46,64 +45,56 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nasync fn run_pod(\n&self,\ninitial_event: WatchEvent<KubePod>,\n- ) -> anyhow::Result<watch::Sender<WatchEvent<KubePod>>> {\n- let (sender, mut receiver) = watch::channel(initial_event);\n+ ) -> anyhow::Result<tokio::sync::mpsc::Sender<WatchEvent<KubePod>>> {\n+ let (sender, mut receiver) = tokio::sync::mpsc::channel::<WatchEvent<KubePod>>(16);\n- // These should be set on the first Add.\n- let mut pod_definition: Option<KubePod> = None;\n- let mut state_tx: Option<tokio::sync::mpsc::Sender<PodChange>> = None;\n-\n- let task_provider = Arc::clone(&self.provider);\n- let task_client = self.client.clone();\n- tokio::spawn(async move {\n- while let Some(event) = receiver.recv().await {\n- // Watch errors are handled before an event ever gets here, so it should always have\n- // a pod\n- match event {\n+ let (mut state_tx, mut pod_definition) = match initial_event {\nWatchEvent::Added(pod) => {\n- // TODO Can we avoid having this called multiple times (multiple state machines)?.\n- // I'm thinking we wait for an initial Pod added event before this loop to set\n- // pod_definition and state_tx and start state machine, and after that it is handled differently.\n-\n- let (tx, state_rx) = tokio::sync::mpsc::channel::<PodChange>(16);\n- state_tx = Some(tx);\n- pod_definition = Some(pod.clone());\n+ let task_client = self.client.clone();\n+ let (state_tx, state_rx) = tokio::sync::mpsc::channel::<PodChange>(16);\n+ let pod_definition = pod.clone();\n- let client = task_client.clone();\n- let pod_state: P::PodState =\n- task_provider.initialize_pod_state().await.unwrap();\n+ let pod_state: P::PodState = self.provider.initialize_pod_state().await?;\ntokio::spawn(async move {\nlet state: P::InitialState = Default::default();\nlet pod = Pod::new(pod);\nlet name = pod.name().to_string();\n- match run_to_completion(client, state, pod_state, pod, state_rx).await {\n+ match run_to_completion(task_client, state, pod_state, pod, state_rx).await {\nOk(()) => info!(\"Pod {} state machine exited without error\", name),\n- Err(e) => {\n- error!(\"Pod {} state machine exited with error: {:?}\", name, e)\n- }\n+ Err(e) => error!(\"Pod {} state machine exited with error: {:?}\", name, e),\n}\n});\n+\n+ (state_tx, pod_definition)\n}\n- WatchEvent::Modified(_pod) => {\n- // TODO Need to actually detect what change happens. Some kind of diffing functions? Can reference and update pod_definition.\n- match state_tx {\n- Some(ref mut sender) => match sender.send(PodChange::Shutdown).await {\n+ _ => anyhow::bail!(\"Pod with initial event not Added: {:?}\", &initial_event),\n+ };\n+\n+ tokio::spawn(async move {\n+ while let Some(event) = receiver.recv().await {\n+ // Watch errors are handled before an event ever gets here, so it should always have\n+ // a pod\n+ match event {\n+ WatchEvent::Modified(pod) => {\n+ // Not really using this right now but will be useful for detecting changes.\n+ pod_definition = pod.clone();\n+ let pod = Pod::new(pod);\n+ // TODO, detect other changes we want to support, or should this just forward the new pod def to state machine?\n+ if let Some(_timestamp) = pod.deletion_timestamp() {\n+ match state_tx.send(PodChange::Shutdown).await {\nOk(_) => (),\n- // This should only happen if the state machine has completed and rx was dropped.\nErr(_) => break,\n- },\n- None => unimplemented!(),\n}\n}\n- WatchEvent::Deleted(_pod) => match state_tx {\n- Some(ref mut sender) => match sender.send(PodChange::Delete).await {\n+ }\n+ WatchEvent::Deleted(pod) => {\n+ pod_definition = pod;\n+ match state_tx.send(PodChange::Delete).await {\nOk(_) => (),\nErr(_) => break,\n- },\n- None => unimplemented!(),\n- },\n- WatchEvent::Bookmark(_) => (),\n- _ => unreachable!(),\n+ }\n+ }\n+ _ => warn!(\"Pod got unexpected event, ignoring: {:?}\", &event),\n}\n}\n});\n@@ -121,7 +112,7 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\nlet key = pod_key(&pod_namespace, &pod_name);\n// We are explicitly not using the entry api here to insert to avoid the need for a\n// mutex\n- let sender = match self.handlers.get(&key) {\n+ let sender = match self.handlers.get_mut(&key) {\nSome(s) => s,\nNone => {\nself.handlers.insert(\n@@ -130,10 +121,10 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n// TODO Does this mean we handle the Add event twice?\nself.run_pod(event.clone()).await?,\n);\n- self.handlers.get(&key).unwrap()\n+ self.handlers.get_mut(&key).unwrap()\n}\n};\n- match sender.broadcast(event) {\n+ match sender.send(event).await {\nOk(_) => debug!(\n\"successfully sent event to handler for pod {} in namespace {}\",\npod_name, pod_namespace\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "#![deny(missing_docs)]\nuse async_trait::async_trait;\n-use kubelet::container::{Handle as ContainerHandle, Status as ContainerStatus};\n+use kubelet::container::Handle as ContainerHandle;\nuse kubelet::handle::StopHandler;\nuse kubelet::node::Builder;\nuse kubelet::pod::Phase;\n@@ -44,7 +44,6 @@ use kubelet::store::Store;\nuse kubelet::volume::Ref;\nuse log::{debug, info};\nuse tempfile::NamedTempFile;\n-use tokio::sync::watch::Receiver;\nuse tokio::sync::RwLock;\nuse wascc_fs::FileSystemProvider;\nuse wascc_host::{Actor, NativeCapability, WasccHost};\n@@ -384,7 +383,6 @@ fn wascc_run_http(\nmut env: EnvVars,\nvolumes: Vec<VolumeBinding>,\nlog_path: &Path,\n- status_recv: Receiver<ContainerStatus>,\nport_assigned: i32,\n) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> {\nlet mut caps: Vec<Capability> = Vec::new();\n@@ -395,7 +393,7 @@ fn wascc_run_http(\nbinding: None,\nenv,\n});\n- wascc_run(host, data, &mut caps, volumes, log_path, status_recv)\n+ wascc_run(host, data, &mut caps, volumes, log_path)\n}\n/// Capability describes a waSCC capability.\n@@ -431,7 +429,6 @@ fn wascc_run(\ncapabilities: &mut Vec<Capability>,\nvolumes: Vec<VolumeBinding>,\nlog_path: &Path,\n- status_recv: Receiver<ContainerStatus>,\n) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> {\ninfo!(\"sending actor to wascc host\");\nlet log_output = NamedTempFile::new_in(log_path)?;\n@@ -500,6 +497,5 @@ fn wascc_run(\nvolumes,\n},\nlog_handle_factory,\n- status_recv,\n))\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/starting.rs", "new_path": "crates/wascc-provider/src/states/starting.rs", "diff": "@@ -3,12 +3,9 @@ use std::ops::Deref;\nuse std::sync::Arc;\nuse log::{debug, error, info};\n-use tokio::sync::watch;\nuse tokio::sync::Mutex;\n-use kubelet::container::{\n- Container, ContainerKey, Handle as ContainerHandle, Status as ContainerStatus,\n-};\n+use kubelet::container::{Container, ContainerKey, Handle as ContainerHandle};\nuse kubelet::provider::Provider;\nuse kubelet::state::{PodChangeRx, State, Transition};\nuse kubelet::{\n@@ -133,21 +130,9 @@ async fn start_container(\n.remove(container.name())\n.expect(\"FATAL ERROR: module map not properly populated\");\nlet lp = pod_state.log_path.clone();\n- let (_status_sender, status_recv) = watch::channel(ContainerStatus::Waiting {\n- timestamp: chrono::Utc::now(),\n- message: \"No status has been received from the process\".into(),\n- });\nlet host = pod_state.host.clone();\ntokio::task::spawn_blocking(move || {\n- wascc_run_http(\n- host,\n- module_data,\n- env,\n- volume_bindings,\n- &lp,\n- status_recv,\n- port_assigned,\n- )\n+ wascc_run_http(host, module_data, env, volume_bindings, &lp, port_assigned)\n})\n.await?\n}\n@@ -182,14 +167,7 @@ state!(\n);\n}\n- let pod_handle = Handle::new(\n- container_handles,\n- pod.clone(),\n- pod_state.client.clone(),\n- None,\n- None,\n- )\n- .await?;\n+ let pod_handle = Handle::new(container_handles, pod.clone(), None).await?;\npod_state.handle = Some(pod_handle);\ninfo!(\"All containers started for pod {:?}.\", pod.name());\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Clean up pod queue
350,426
29.08.2020 09:02:33
18,000
257448cede01a5a66b343f675dcc83b932a78dac
Clean up some states
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -124,9 +124,13 @@ impl StopHandler for ActorHandle {\n/// from Kubernetes.\n#[derive(Clone)]\npub struct WasccProvider {\n+ shared: SharedPodState\n+}\n+\n+#[derive(Clone)]\n+struct SharedPodState {\nclient: kube::Client,\nhandles: Arc<RwLock<HashMap<String, Handle<ActorHandle, LogHandleFactory>>>>,\n- run_contexts: Arc<RwLock<HashMap<String, ModuleRunContext>>>,\nstore: Arc<dyn Store + Sync + Send>,\nvolume_path: PathBuf,\nlog_path: PathBuf,\n@@ -188,14 +192,15 @@ impl WasccProvider {\n})\n.await??;\nOk(Self {\n+ shared: SharedPodState {\nclient,\nhandles: Default::default(),\n- run_contexts: Default::default(),\nstore,\nvolume_path,\nlog_path,\nhost,\nport_map,\n+ }\n})\n}\n}\n@@ -224,14 +229,8 @@ fn make_status(phase: Phase, reason: &str) -> anyhow::Result<serde_json::Value>\n/// State that is shared between pod state handlers.\npub struct PodState {\nrun_context: ModuleRunContext,\n- store: Arc<dyn Store + Sync + Send>,\n- client: kube::Client,\n- volume_path: std::path::PathBuf,\nerrors: usize,\n- port_map: Arc<TokioMutex<HashMap<i32, String>>>,\n- handle: Option<Handle<ActorHandle, LogHandleFactory>>,\n- log_path: PathBuf,\n- host: Arc<Mutex<WasccHost>>,\n+ shared: SharedPodState\n}\n#[async_trait]\n@@ -255,103 +254,11 @@ impl Provider for WasccProvider {\nOk(PodState {\nrun_context,\n- store: Arc::clone(&self.store),\n- client: self.client.clone(),\n- volume_path: self.volume_path.clone(),\nerrors: 0,\n- port_map: Arc::clone(&self.port_map),\n- handle: None,\n- log_path: self.log_path.clone(),\n- host: Arc::clone(&self.host),\n+ shared: self.shared.clone()\n})\n}\n- // async fn modify(&self, pod: Pod) {\n- // let pod_handle_key = key_from_pod(&pod);\n- // // The only things we care about are:\n- // // 1. metadata.deletionTimestamp => signal all containers to stop and then mark them\n- // // as terminated\n- // // 2. spec.containers[*].image, spec.initContainers[*].image => stop the currently\n- // // running containers and start new ones?\n- // // 3. spec.activeDeadlineSeconds => Leaving unimplemented for now\n- // // TODO: Determine what the proper behavior should be if labels change\n- // let pod_name = pod.name().to_owned();\n- // let pod_namespace = pod.namespace().to_owned();\n- // debug!(\n- // \"Got pod modified event for {} in namespace {}\",\n- // pod_name, pod_namespace\n- // );\n- // trace!(\"Modified pod spec: {:#?}\", pod.as_kube_pod());\n- // if let Some(_timestamp) = pod.deletion_timestamp() {\n- // debug!(\n- // \"Found delete timestamp for pod {} in namespace {}. Stopping running actors\",\n- // pod_name, pod_namespace\n- // );\n- // let mut handles = self.handles.write().await;\n- // match handles.get_mut(&key_from_pod(&pod)) {\n- // Some(h) => {\n- // h.stop().await.unwrap();\n-\n- // debug!(\n- // \"All actors stopped for pod {} in namespace {}, updating status\",\n- // pod_name, pod_namespace\n- // );\n- // // Having to do this here isn't my favorite thing, but we need to update the\n- // // status of the container so it can be deleted. We will probably need to have\n- // // some sort of provider that can send a message about status to the Kube API\n- // let now = chrono::Utc::now();\n- // let terminated = ContainerStatus::Terminated {\n- // timestamp: now,\n- // message: \"Pod stopped\".to_owned(),\n- // failed: false,\n- // };\n-\n- // let container_statuses: Vec<KubeContainerStatus> = pod\n- // .into_kube_pod()\n- // .spec\n- // .unwrap_or_default()\n- // .containers\n- // .into_iter()\n- // .map(|c| terminated.to_kubernetes(c.name))\n- // .collect();\n-\n- // let json_status = serde_json::json!(\n- // {\n- // \"metadata\": {\n- // \"resourceVersion\": \"\",\n- // },\n- // \"status\": {\n- // \"message\": \"Pod stopped\",\n- // \"phase\": Phase::Succeeded,\n- // \"containerStatuses\": container_statuses,\n- // }\n- // }\n- // );\n- // update_status(self.client.clone(), &pod_namespace, &pod_name, &json_status).await.unwrap();\n-\n- // let pod_client: Api<KubePod> = Api::namespaced(self.client.clone(), &pod_namespace);\n- // let dp = DeleteParams {\n- // grace_period_seconds: Some(0),\n- // ..Default::default()\n- // };\n- // pod_client.delete(&pod_name, &dp).await.unwrap();\n- // }\n- // None => {\n- // // This isn't an error with the pod, so don't return an error (otherwise it will\n- // // get updated in its status). This is an unlikely case to get into and means\n- // // that something is likely out of sync, so just log the error\n- // error!(\n- // \"Unable to find pod {} in namespace {} when trying to stop all containers\",\n- // pod_name, pod_namespace\n- // );\n- // }\n- // }\n- // } else {\n- // };\n- // // TODO: Implement behavior for stopping old containers and restarting when the container\n- // // image changes\n- // }\n-\nasync fn logs(\n&self,\nnamespace: String,\n@@ -359,7 +266,7 @@ impl Provider for WasccProvider {\ncontainer_name: String,\nsender: kubelet::log::Sender,\n) -> anyhow::Result<()> {\n- let mut handles = self.handles.write().await;\n+ let mut handles = self.shared.handles.write().await;\nlet handle = handles\n.get_mut(&pod_key(&namespace, &pod_name))\n.ok_or_else(|| ProviderError::PodNotFound {\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states.rs", "new_path": "crates/wascc-provider/src/states.rs", "diff": "-pub mod cleanup;\n-pub mod crash_loop_backoff;\n-pub mod error;\n-pub mod finished;\n-pub mod image_pull;\n-pub mod image_pull_backoff;\n-pub mod registered;\n-pub mod running;\n-pub mod starting;\n-pub mod terminated;\n-pub mod volume_mount;\n+pub(crate) mod cleanup;\n+pub(crate) mod crash_loop_backoff;\n+pub(crate) mod error;\n+pub(crate) mod finished;\n+pub(crate) mod image_pull;\n+pub(crate) mod image_pull_backoff;\n+pub(crate) mod registered;\n+pub(crate) mod running;\n+pub(crate) mod starting;\n+pub(crate) mod terminated;\n+pub(crate) mod volume_mount;\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/cleanup.rs", "new_path": "crates/wascc-provider/src/states/cleanup.rs", "diff": "use kubelet::state::{PodChangeRx, State, Transition};\nuse kubelet::{\n- pod::{Phase, Pod},\n+ pod::{Phase, Pod, key_from_pod},\nstate,\n};\n@@ -14,7 +14,7 @@ state!(\nCleanup,\n{\nlet mut delete_key: i32 = 0;\n- let mut lock = pod_state.port_map.lock().await;\n+ let mut lock = pod_state.shared.port_map.lock().await;\nfor (key, val) in lock.iter() {\nif val == pod.name() {\ndelete_key = *key\n@@ -22,6 +22,12 @@ state!(\n}\nlock.remove(&delete_key);\n+ let pod_key = key_from_pod(&pod);\n+ {\n+ let mut handles = pod_state.shared.handles.write().await;\n+ handles.remove(&pod_key);\n+ }\n+\nOk(Transition::Complete(Ok(())))\n},\n{ make_status(Phase::Succeeded, \"Cleanup\") }\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/image_pull.rs", "new_path": "crates/wascc-provider/src/states/image_pull.rs", "diff": "@@ -17,7 +17,7 @@ state!(\nVolumeMount,\nImagePullBackoff,\n{\n- pod_state.run_context.modules = match pod_state.store.fetch_pod_modules(&pod).await {\n+ pod_state.run_context.modules = match pod_state.shared.store.fetch_pod_modules(&pod).await {\nOk(modules) => modules,\nErr(e) => {\nerror!(\"{:?}\", e);\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/starting.rs", "new_path": "crates/wascc-provider/src/states/starting.rs", "diff": "@@ -9,7 +9,7 @@ use kubelet::container::{Container, ContainerKey, Handle as ContainerHandle};\nuse kubelet::provider::Provider;\nuse kubelet::state::{PodChangeRx, State, Transition};\nuse kubelet::{\n- pod::{Handle, Phase, Pod},\n+ pod::{Handle, Phase, Pod, key_from_pod},\nstate,\n};\n@@ -96,7 +96,7 @@ async fn start_container(\npod: &Pod,\nport_assigned: i32,\n) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> {\n- let env = <WasccProvider as Provider>::env_vars(&container, &pod, &pod_state.client).await;\n+ let env = <WasccProvider as Provider>::env_vars(&container, &pod, &pod_state.shared.client).await;\nlet volume_bindings: Vec<VolumeBinding> =\nif let Some(volume_mounts) = container.volume_mounts().as_ref() {\nvolume_mounts\n@@ -129,8 +129,8 @@ async fn start_container(\n.modules\n.remove(container.name())\n.expect(\"FATAL ERROR: module map not properly populated\");\n- let lp = pod_state.log_path.clone();\n- let host = pod_state.host.clone();\n+ let lp = pod_state.shared.log_path.clone();\n+ let host = pod_state.shared.host.clone();\ntokio::task::spawn_blocking(move || {\nwascc_run_http(host, module_data, env, volume_bindings, &lp, port_assigned)\n})\n@@ -149,7 +149,7 @@ state!(\nlet mut container_handles = HashMap::new();\nfor container in pod.containers() {\nlet port_assigned =\n- assign_container_port(Arc::clone(&pod_state.port_map), &pod, &container)\n+ assign_container_port(Arc::clone(&pod_state.shared.port_map), &pod, &container)\n.await\n.unwrap();\ndebug!(\n@@ -168,7 +168,11 @@ state!(\n}\nlet pod_handle = Handle::new(container_handles, pod.clone(), None).await?;\n- pod_state.handle = Some(pod_handle);\n+ let pod_key = key_from_pod(&pod);\n+ {\n+ let mut handles = pod_state.shared.handles.write().await;\n+ handles.insert(pod_key, pod_handle);\n+ }\ninfo!(\"All containers started for pod {:?}.\", pod.name());\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/volume_mount.rs", "new_path": "crates/wascc-provider/src/states/volume_mount.rs", "diff": "@@ -18,7 +18,7 @@ state!(\nError,\n{\npod_state.run_context.volumes =\n- Ref::volumes_from_pod(&pod_state.volume_path, &pod, &pod_state.client)\n+ Ref::volumes_from_pod(&pod_state.shared.volume_path, &pod, &pod_state.shared.client)\n.await\n.unwrap();\nOk(Transition::Advance(Starting))\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Clean up some states
350,426
02.09.2020 20:20:33
18,000
aada5f8f51b428d26ca31d5de2a9c56f50114c3d
Mark pod terminated on node shutdown.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/node/mod.rs", "new_path": "crates/kubelet/src/node/mod.rs", "diff": "//! `node` contains wrappers around the Kubernetes node API, containing ways to create and update\n//! nodes operating within the cluster.\nuse crate::config::Config;\n-use crate::pod::Pod;\n+use crate::container::Status as ContainerStatus;\n+use crate::pod::{Phase, Pod};\nuse crate::provider::Provider;\nuse chrono::prelude::*;\nuse futures::{StreamExt, TryStreamExt};\nuse k8s_openapi::api::coordination::v1::Lease;\n+use k8s_openapi::api::core::v1::ContainerStatus as KubeContainerStatus;\nuse k8s_openapi::api::core::v1::Node as KubeNode;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;\n@@ -204,14 +206,29 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\ninfo!(\"Skipping eviction of DaemonSet '{}'\", pod.name());\ncontinue;\n} else if pod.is_static() {\n- // TODO How to mark this with state machine architecture?\n- // let container_statuses = all_terminated_due_to_shutdown(&pod.all_containers());\n-\n- // let status = PodStatus {\n- // message: PodStatusMessage::Message(\"Evicted on node shutdown.\".to_string()),\n- // container_statuses,\n- // };\n- // pod.patch_status(client.clone(), status).await;\n+ let api: Api<KubePod> = Api::namespaced(client.clone(), pod.namespace());\n+ let patch = serde_json::json!(\n+ {\n+ \"metadata\": {\n+ \"resourceVersion\": \"\",\n+ },\n+ \"status\": {\n+ \"phase\": Phase::Succeeded,\n+ \"reason\": \"Pod terminated on node shutdown.\",\n+ \"containerStatuses\": pod.all_containers().iter().map(|key| {\n+ ContainerStatus::Terminated {\n+ timestamp: Utc::now(),\n+ message: \"Evicted on node shutdown\".to_string(),\n+ failed: false\n+ }.to_kubernetes(key.name())\n+ }).collect::<Vec<KubeContainerStatus>>()\n+ }\n+ }\n+ );\n+ let data = serde_json::to_vec(&patch)?;\n+ api.patch_status(&pod.name(), &PatchParams::default(), data)\n+ .await?;\n+\ninfo!(\"Marked static pod as terminated.\");\ncontinue;\n} else {\n@@ -227,23 +244,6 @@ pub async fn evict_pods(client: &kube::Client, node_name: &str) -> anyhow::Resul\nOk(())\n}\n-// fn all_terminated_due_to_shutdown(\n-// container_keys: &[ContainerKey],\n-// ) -> ContainerMap<ContainerStatus> {\n-// let mut container_statuses = HashMap::new();\n-// for container_key in container_keys {\n-// container_statuses.insert(\n-// container_key.clone(),\n-// ContainerStatus::Terminated {\n-// timestamp: Utc::now(),\n-// message: \"Evicted on node shutdown.\".to_string(),\n-// failed: false,\n-// },\n-// );\n-// }\n-// container_statuses\n-// }\n-\ntype PodStream = std::pin::Pin<\nBox<\ndyn futures::Stream<Item = Result<kube::api::WatchEvent<KubePod>, kube::error::Error>>\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Mark pod terminated on node shutdown.
350,426
02.09.2020 20:42:11
18,000
40a375ccc99fa3d87c60c4de55afa10517b50eed
Remove PodChange enum
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/mod.rs", "new_path": "crates/kubelet/src/pod/mod.rs", "diff": "@@ -3,7 +3,6 @@ mod handle;\nmod queue;\nmod status;\npub use handle::{key_from_pod, pod_key, Handle};\n-pub use queue::PodChange;\npub(crate) use queue::Queue;\npub use status::{update_status, Phase, Status, StatusMessage};\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -11,16 +11,6 @@ use crate::pod::{pod_key, Phase, Pod};\nuse crate::provider::Provider;\nuse crate::state::{run_to_completion, AsyncDrop};\n-/// Possible mutations to Pod that state machine should detect.\n-pub enum PodChange {\n- /// A container image has changed.\n- ImageChange,\n- /// The pod was marked for deletion.\n- Shutdown,\n- /// The pod was deregistered with the Kubernetes API and should be cleaned up.\n- Delete,\n-}\n-\n/// A per-pod queue that takes incoming Kubernetes events and broadcasts them to the correct queue\n/// for that pod.\n///\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Remove PodChange enum
350,426
02.09.2020 21:05:14
18,000
34d1b3462949c1bff1429cf046aa7667c3b6443e
Reduce logging verbosity and handle pod force delete
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -4,7 +4,7 @@ use std::sync::Arc;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\nuse kube::api::{Meta, WatchEvent};\nuse kube::Client as KubeClient;\n-use log::{debug, error, info, warn};\n+use log::{debug, error, warn};\nuse tokio::sync::RwLock;\nuse crate::pod::{pod_key, Phase, Pod};\n@@ -63,7 +63,7 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\ntokio::select! {\nresult = run_to_completion(&task_client, state, &mut pod_state, &pod) => match result {\n- Ok(()) => info!(\"Pod {} state machine exited without error\", name),\n+ Ok(()) => debug!(\"Pod {} state machine exited without error\", name),\nErr(e) => {\nerror!(\"Pod {} state machine exited with error: {:?}\", name, e);\nlet api: kube::Api<KubePod> = kube::Api::namespaced(task_client.clone(), pod.namespace());\n@@ -87,19 +87,19 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n},\n_ = check => {\nlet state: P::TerminatedState = Default::default();\n- info!(\"Pod {} terminated. Jumping to state {:?}.\", name, state);\n+ debug!(\"Pod {} terminated. Jumping to state {:?}.\", name, state);\nmatch run_to_completion(&task_client, state, &mut pod_state, &pod).await {\n- Ok(()) => info!(\"Pod {} state machine exited without error\", name),\n+ Ok(()) => debug!(\"Pod {} state machine exited without error\", name),\nErr(e) => error!(\"Pod {} state machine exited with error: {:?}\", name, e),\n}\n}\n}\n- info!(\"Pod {} waiting for deregistration.\", name);\n+ debug!(\"Pod {} waiting for deregistration.\", name);\nloop {\ntokio::time::delay_for(std::time::Duration::from_secs(1)).await;\nif *check_pod_deleted.read().await {\n- info!(\"Pod {} deleted.\", name);\n+ debug!(\"Pod {} deleted.\", name);\nbreak;\n}\n}\n@@ -114,10 +114,11 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n};\nmatch pod_client.delete(&pod.name(), &dp).await {\nOk(_) => {\n- info!(\"Pod {} deregistered.\", name);\n+ debug!(\"Pod {} deregistered.\", name);\n}\nErr(e) => {\n- error!(\"Unable to deregister {} with Kubernetes API: {:?}\", name, e);\n+ // This could happen if Pod was force deleted.\n+ warn!(\"Unable to deregister {} with Kubernetes API: {:?}\", name, e);\n}\n}\n});\n@@ -131,7 +132,7 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n// a pod\nmatch event {\nWatchEvent::Modified(pod) => {\n- info!(\"Pod {} modified.\", Pod::new(pod.clone()).name());\n+ debug!(\"Pod {} modified.\", Pod::new(pod.clone()).name());\n// Not really using this right now but will be useful for detecting changes.\nlet pod = Pod::new(pod);\n// TODO, detect other changes we want to support, or should this just forward the new pod def to state machine?\n@@ -144,7 +145,8 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n// Modified event, and I think we only get this after *we* delete the pod.\n// There is the case where someone force deletes, but we want to go through\n// our normal terminate and deregister flow anyway.\n- info!(\"Pod {} deleted.\", Pod::new(pod).name());\n+ debug!(\"Pod {} deleted.\", Pod::new(pod).name());\n+ *(pod_deleted.write().await) = true;\nbreak;\n}\n_ => warn!(\"Pod got unexpected event, ignoring: {:?}\", &event),\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state.rs", "new_path": "crates/kubelet/src/state.rs", "diff": "//! Used to define a state machine of Pod states.\n-use log::info;\n+use log::debug;\n// pub mod default;\n#[macro_use]\n@@ -57,18 +57,18 @@ pub async fn run_to_completion<PodState: Send + Sync + 'static>(\nlet mut state: Box<dyn State<PodState>> = Box::new(state);\nloop {\n- info!(\"Pod {} entering state {:?}\", pod.name(), state);\n+ debug!(\"Pod {} entering state {:?}\", pod.name(), state);\nlet patch = state.json_status(pod_state, &pod).await?;\n- info!(\"Pod {} status patch: {:?}\", pod.name(), &patch);\n+ debug!(\"Pod {} status patch: {:?}\", pod.name(), &patch);\nlet data = serde_json::to_vec(&patch)?;\napi.patch_status(&pod.name(), &PatchParams::default(), data)\n.await?;\n- info!(\"Pod {} executing state handler {:?}\", pod.name(), state);\n+ debug!(\"Pod {} executing state handler {:?}\", pod.name(), state);\nlet transition = { state.next(pod_state, &pod).await? };\n- info!(\n+ debug!(\n\"Pod {} state execution result: {:?}\",\npod.name(),\ntransition\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Reduce logging verbosity and handle pod force delete
350,426
02.09.2020 21:12:58
18,000
c2022b98a67e7e15a610bd2000af66534ab444f3
Make AsyncDrop drop on complete.
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/queue.rs", "new_path": "crates/kubelet/src/pod/queue.rs", "diff": "@@ -104,7 +104,6 @@ impl<P: 'static + Provider + Sync + Send> Queue<P> {\n}\n}\npod_state.async_drop().await;\n- drop(pod_state);\nlet pod_client: kube::Api<KubePod> =\nkube::Api::namespaced(task_client, pod.namespace());\n" }, { "change_type": "MODIFY", "old_path": "crates/kubelet/src/state.rs", "new_path": "crates/kubelet/src/state.rs", "diff": "@@ -21,10 +21,10 @@ pub enum Transition<S, E> {\n}\n#[async_trait::async_trait]\n-/// Allow for asyncronous cleanup up of PodState.\n-pub trait AsyncDrop {\n+/// Allow for asynchronous cleanup up of PodState.\n+pub trait AsyncDrop: Sized {\n/// Clean up PodState.\n- async fn async_drop(&mut self);\n+ async fn async_drop(self);\n}\n#[async_trait::async_trait]\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/lib.rs", "new_path": "crates/wascc-provider/src/lib.rs", "diff": "@@ -238,7 +238,7 @@ pub struct PodState {\n// No cleanup state needed, we clean up when dropping PodState.\n#[async_trait]\nimpl kubelet::state::AsyncDrop for PodState {\n- async fn async_drop(&mut self) {\n+ async fn async_drop(self) {\n{\ninfo!(\"Pod {} releasing ports.\", &self.key);\nlet mut lock = self.shared.port_map.lock().await;\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/error.rs", "new_path": "crates/wascc-provider/src/states/error.rs", "diff": "@@ -19,7 +19,6 @@ impl State<PodState> for Error {\npod_state: &mut PodState,\n_pod: &Pod,\n) -> anyhow::Result<Transition<Box<dyn State<PodState>>, Box<dyn State<PodState>>>> {\n- // TODO: Handle pod delete?\npod_state.errors += 1;\nif pod_state.errors > 3 {\npod_state.errors = 0;\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Make AsyncDrop drop on complete.
350,405
10.09.2020 09:34:48
-43,200
c4adaa49da41ce82209ac84f93abe6f86157bc94
Image pull secrets CI test
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -76,6 +76,8 @@ jobs:\nKRUSTLET_NODE_IP: \"172.17.0.1\"\n# The default location for the cert is not accessible on build hosts, so do it in the current dir\nCONFIG_DIR: \"./config\"\n+ KRUSTLET_TEST_ENV: \"ci\"\n+ KRUSTLET_E2E_IMAGE_PULL_SECRET: ${{ secrets.KRUSTLET_E2E_IMAGE_PULL_SECRET }}\nrun: |\njust bootstrap\njust build\n" }, { "change_type": "MODIFY", "old_path": "justfile", "new_path": "justfile", "diff": "@@ -19,6 +19,12 @@ test-e2e:\ntest-e2e-standalone:\ncargo run --bin oneclick\n+test-e2e-ci:\n+ KRUSTLET_TEST_ENV=ci cargo test --test integration_tests\n+\n+test-e2e-standalone-ci:\n+ KRUSTLET_TEST_ENV=ci cargo run --bin oneclick\n+\nrun-wascc +FLAGS='': bootstrap\nKUBECONFIG=$(eval echo $CONFIG_DIR)/kubeconfig-wascc cargo run --bin krustlet-wascc {{FLAGS}} -- --node-name krustlet-wascc --port 3000 --bootstrap-file $(eval echo $CONFIG_DIR)/bootstrap.conf --cert-file $(eval echo $CONFIG_DIR)/krustlet-wascc.crt --private-key-file $(eval echo $CONFIG_DIR)/krustlet-wascc.key\n" }, { "change_type": "MODIFY", "old_path": "tests/integration_tests.rs", "new_path": "tests/integration_tests.rs", "diff": "@@ -14,6 +14,10 @@ use pod_builder::{\nuse pod_setup::{wait_for_pod_complete, wait_for_pod_ready, OnFailure};\nuse test_resource_manager::{TestResource, TestResourceManager, TestResourceSpec};\n+fn in_ci_environment() -> bool {\n+ std::env::var(\"KRUSTLET_TEST_ENV\") == Ok(\"ci\".to_owned())\n+}\n+\n#[tokio::test]\nasync fn test_wascc_provider() -> Result<(), Box<dyn std::error::Error>> {\nlet client = kube::Client::try_default().await?;\n@@ -208,6 +212,7 @@ const MULTI_ITEMS_MOUNT_WASI_POD: &str = \"multi-mount-items-pod\";\nconst LOGGY_POD: &str = \"loggy-pod\";\nconst INITY_WASI_POD: &str = \"hello-wasi-with-inits\";\nconst FAILY_INITS_POD: &str = \"faily-inits-pod\";\n+const PRIVATE_REGISTRY_POD: &str = \"private-registry-pod\";\nasync fn create_wasi_pod(\nclient: kube::Client,\n@@ -347,9 +352,7 @@ async fn create_multi_mount_pod(\n) -> anyhow::Result<()> {\nlet pod_name = MULTI_MOUNT_WASI_POD;\n- let containers = vec![WasmerciserContainerSpec {\n- name: \"multimount\",\n- args: &[\n+ let containers = vec![WasmerciserContainerSpec::named(\"multimount\").with_args(&[\n\"assert_exists(file:/mcm/mcm1)\",\n\"assert_exists(file:/mcm/mcm2)\",\n\"assert_exists(file:/mcm/mcm5)\",\n@@ -364,8 +367,7 @@ async fn create_multi_mount_pod(\n\"write(var:mcm5)to(stm:stdout)\",\n\"write(var:ms1)to(stm:stdout)\",\n\"write(var:ms3)to(stm:stdout)\",\n- ],\n- }];\n+ ])];\nlet volumes = vec![\nWasmerciserVolumeSpec {\n@@ -400,9 +402,7 @@ async fn create_multi_items_mount_pod(\n) -> anyhow::Result<()> {\nlet pod_name = MULTI_ITEMS_MOUNT_WASI_POD;\n- let containers = vec![WasmerciserContainerSpec {\n- name: \"multimount\",\n- args: &[\n+ let containers = vec![WasmerciserContainerSpec::named(\"multimount\").with_args(&[\n\"assert_exists(file:/mcm/mcm1)\",\n\"assert_not_exists(file:/mcm/mcm2)\",\n\"assert_exists(file:/mcm/mcm-five)\",\n@@ -417,8 +417,7 @@ async fn create_multi_items_mount_pod(\n\"write(var:mcm5)to(stm:stdout)\",\n\"write(var:ms1)to(stm:stdout)\",\n\"write(var:ms3)to(stm:stdout)\",\n- ],\n- }];\n+ ])];\nlet volumes = vec![\nWasmerciserVolumeSpec {\n@@ -460,14 +459,8 @@ async fn create_loggy_pod(\nlet pod_name = LOGGY_POD;\nlet containers = vec![\n- WasmerciserContainerSpec {\n- name: \"floofycat\",\n- args: &[\"write(lit:slats)to(stm:stdout)\"],\n- },\n- WasmerciserContainerSpec {\n- name: \"neatcat\",\n- args: &[\"write(lit:kiki)to(stm:stdout)\"],\n- },\n+ WasmerciserContainerSpec::named(\"floofycat\").with_args(&[\"write(lit:slats)to(stm:stdout)\"]),\n+ WasmerciserContainerSpec::named(\"neatcat\").with_args(&[\"write(lit:kiki)to(stm:stdout)\"]),\n];\nwasmercise_wasi(\n@@ -490,10 +483,8 @@ async fn create_faily_pod(\n) -> anyhow::Result<()> {\nlet pod_name = FAILY_POD;\n- let containers = vec![WasmerciserContainerSpec {\n- name: pod_name,\n- args: &[\"assert_exists(file:/nope.nope.nope.txt)\"],\n- }];\n+ let containers = vec![WasmerciserContainerSpec::named(pod_name)\n+ .with_args(&[\"assert_exists(file:/nope.nope.nope.txt)\"])];\nwasmercise_wasi(\npod_name,\n@@ -536,26 +527,19 @@ async fn create_pod_with_init_containers(\nlet pod_name = INITY_WASI_POD;\nlet inits = vec![\n- WasmerciserContainerSpec {\n- name: \"init-1\",\n- args: &[\"write(lit:slats)to(file:/hp/floofycat.txt)\"],\n- },\n- WasmerciserContainerSpec {\n- name: \"init-2\",\n- args: &[\"write(lit:kiki)to(file:/hp/neatcat.txt)\"],\n- },\n+ WasmerciserContainerSpec::named(\"init-1\")\n+ .with_args(&[\"write(lit:slats)to(file:/hp/floofycat.txt)\"]),\n+ WasmerciserContainerSpec::named(\"init-2\")\n+ .with_args(&[\"write(lit:kiki)to(file:/hp/neatcat.txt)\"]),\n];\n- let containers = vec![WasmerciserContainerSpec {\n- name: pod_name,\n- args: &[\n+ let containers = vec![WasmerciserContainerSpec::named(pod_name).with_args(&[\n\"assert_exists(file:/hp/floofycat.txt)\",\n\"assert_exists(file:/hp/neatcat.txt)\",\n\"read(file:/hp/floofycat.txt)to(var:fcat)\",\n\"assert_value(var:fcat)is(lit:slats)\",\n\"write(var:fcat)to(stm:stdout)\",\n- ],\n- }];\n+ ])];\nlet volumes = vec![WasmerciserVolumeSpec {\nvolume_name: \"hostpath-test\",\n@@ -584,20 +568,14 @@ async fn create_pod_with_failing_init_container(\nlet pod_name = FAILY_INITS_POD;\nlet inits = vec![\n- WasmerciserContainerSpec {\n- name: \"init-that-fails\",\n- args: &[\"assert_exists(file:/nope.nope.nope.txt)\"],\n- },\n- WasmerciserContainerSpec {\n- name: \"init-that-would-succeed-if-it-ran\",\n- args: &[\"write(lit:slats)to(stm:stdout)\"],\n- },\n+ WasmerciserContainerSpec::named(\"init-that-fails\")\n+ .with_args(&[\"assert_exists(file:/nope.nope.nope.txt)\"]),\n+ WasmerciserContainerSpec::named(\"init-that-would-succeed-if-it-ran\")\n+ .with_args(&[\"write(lit:slats)to(stm:stdout)\"]),\n];\n- let containers = vec![WasmerciserContainerSpec {\n- name: pod_name,\n- args: &[\"assert_exists(file:/also.nope.txt)\"],\n- }];\n+ let containers = vec![WasmerciserContainerSpec::named(pod_name)\n+ .with_args(&[\"assert_exists(file:/also.nope.txt)\"])];\nwasmercise_wasi(\npod_name,\n@@ -612,6 +590,35 @@ async fn create_pod_with_failing_init_container(\n.await\n}\n+async fn create_private_registry_pod(\n+ client: kube::Client,\n+ pods: &Api<Pod>,\n+ resource_manager: &mut TestResourceManager,\n+) -> anyhow::Result<()> {\n+ let pod_name = PRIVATE_REGISTRY_POD;\n+\n+ let containers = vec![\n+ WasmerciserContainerSpec::named(\"floofycat\")\n+ .with_args(&[\"write(lit:slats)to(stm:stdout)\"])\n+ .private(),\n+ WasmerciserContainerSpec::named(\"neatcat\")\n+ .with_args(&[\"write(lit:kiki)to(stm:stdout)\"])\n+ .private(),\n+ ];\n+\n+ wasmercise_wasi(\n+ pod_name,\n+ client,\n+ pods,\n+ vec![],\n+ containers,\n+ vec![],\n+ OnFailure::Panic,\n+ resource_manager,\n+ )\n+ .await\n+}\n+\nasync fn set_up_test(\ntest_ns: &str,\n) -> anyhow::Result<(kube::Client, Api<Pod>, TestResourceManager)> {\n@@ -842,3 +849,20 @@ async fn test_failing_init_containers() -> anyhow::Result<()> {\nOk(())\n}\n+\n+#[tokio::test]\n+async fn test_pull_from_private_registry() -> anyhow::Result<()> {\n+ if !in_ci_environment() {\n+ return Ok(());\n+ }\n+\n+ let test_ns = \"wasi-e2e-private-registry\";\n+ let (client, pods, mut resource_manager) = set_up_test(test_ns).await?;\n+\n+ create_private_registry_pod(client.clone(), &pods, &mut resource_manager).await?;\n+ assert::pod_container_log_contains(&pods, PRIVATE_REGISTRY_POD, \"floofycat\", r#\"slats\"#)\n+ .await?;\n+ assert::pod_container_log_contains(&pods, PRIVATE_REGISTRY_POD, \"neatcat\", r#\"kiki\"#).await?;\n+\n+ Ok(())\n+}\n" }, { "change_type": "MODIFY", "old_path": "tests/pod_builder.rs", "new_path": "tests/pod_builder.rs", "diff": "-use k8s_openapi::api::core::v1::{Container, Pod, Volume, VolumeMount};\n+use k8s_openapi::api::core::v1::{Container, LocalObjectReference, Pod, Volume, VolumeMount};\nuse serde_json::json;\nuse std::sync::Arc;\n@@ -8,8 +8,29 @@ pub struct PodLifetimeOwner {\n}\npub struct WasmerciserContainerSpec {\n- pub name: &'static str,\n- pub args: &'static [&'static str],\n+ name: &'static str,\n+ args: &'static [&'static str],\n+ use_private_registry: bool,\n+}\n+\n+impl WasmerciserContainerSpec {\n+ pub fn named(name: &'static str) -> Self {\n+ WasmerciserContainerSpec {\n+ name,\n+ args: &[],\n+ use_private_registry: false,\n+ }\n+ }\n+\n+ pub fn with_args(mut self, args: &'static [&'static str]) -> Self {\n+ self.args = args;\n+ self\n+ }\n+\n+ pub fn private(mut self) -> Self {\n+ self.use_private_registry = true;\n+ self\n+ }\n}\npub struct WasmerciserVolumeSpec {\n@@ -26,6 +47,9 @@ pub enum WasmerciserVolumeSource {\nSecretItems(&'static str, Vec<(&'static str, &'static str)>),\n}\n+const DEFAULT_TEST_REGISTRY: &str = \"webassembly\";\n+const PRIVATE_TEST_REGISTRY: &str = \"krustletintegrationtestprivate\";\n+\nfn wasmerciser_container(\nspec: &WasmerciserContainerSpec,\nvolumes: &Vec<WasmerciserVolumeSpec>,\n@@ -34,9 +58,14 @@ fn wasmerciser_container(\n.iter()\n.map(|v| wasmerciser_volume_mount(v).unwrap())\n.collect();\n+ let registry = if spec.use_private_registry {\n+ PRIVATE_TEST_REGISTRY\n+ } else {\n+ DEFAULT_TEST_REGISTRY\n+ };\nlet container: Container = serde_json::from_value(json!({\n\"name\": spec.name,\n- \"image\": \"webassembly.azurecr.io/wasmerciser:v0.2.0\",\n+ \"image\": format!(\"{}.azurecr.io/wasmerciser:v0.2.0\", registry),\n\"args\": spec.args,\n\"volumeMounts\": volume_mounts,\n}))?;\n@@ -134,6 +163,13 @@ pub fn wasmerciser_pod(\n.collect();\nlet (volumes, tempdirs) = unzip(&volume_maps);\n+ let use_private_registry = containers.iter().any(|c| c.use_private_registry);\n+ let image_pull_secrets = if use_private_registry {\n+ Some(local_object_references(&[\"registry-creds\"]))\n+ } else {\n+ None\n+ };\n+\nlet pod = serde_json::from_value(json!({\n\"apiVersion\": \"v1\",\n\"kind\": \"Pod\",\n@@ -155,6 +191,7 @@ pub fn wasmerciser_pod(\n\"kubernetes.io/arch\": architecture\n},\n\"volumes\": volumes,\n+ \"imagePullSecrets\": image_pull_secrets,\n}\n}))?;\n@@ -173,3 +210,12 @@ fn unzip<T, U: Clone>(source: &Vec<(T, U)>) -> (Vec<&T>, Vec<U>) {\nfn option_values<T: Clone>(source: &Vec<Option<T>>) -> Vec<T> {\nsource.iter().filter_map(|t| t.clone()).collect()\n}\n+\n+fn local_object_references(names: &[&str]) -> Vec<LocalObjectReference> {\n+ names\n+ .iter()\n+ .map(|n| LocalObjectReference {\n+ name: Some(n.to_string()),\n+ })\n+ .collect()\n+}\n" }, { "change_type": "MODIFY", "old_path": "tests/test_resource_manager.rs", "new_path": "tests/test_resource_manager.rs", "diff": "@@ -95,6 +95,28 @@ impl TestResourceManager {\n// through the system. TODO: make this less worse\ntokio::time::delay_for(tokio::time::Duration::from_millis(100)).await;\n+ let image_pull_secret_opt = std::env::var(\"KRUSTLET_E2E_IMAGE_PULL_SECRET\");\n+\n+ if let Ok(image_pull_secret) = image_pull_secret_opt {\n+ let secrets: Api<Secret> = Api::namespaced(client.clone(), namespace);\n+ secrets\n+ .create(\n+ &PostParams::default(),\n+ &serde_json::from_value(json!({\n+ \"apiVersion\": \"v1\",\n+ \"kind\": \"Secret\",\n+ \"metadata\": {\n+ \"name\": \"registry-creds\",\n+ },\n+ \"type\": \"kubernetes.io/dockerconfigjson\",\n+ \"data\": {\n+ \".dockerconfigjson\": image_pull_secret,\n+ },\n+ }))?,\n+ )\n+ .await?;\n+ };\n+\nOk(TestResourceManager {\nnamespace: namespace.to_owned(),\nclient: client.clone(),\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Image pull secrets CI test (#380)
350,405
10.09.2020 09:36:06
-43,200
18c7118a39ac94c515f870f8529a91116628771d
Warn if a kubelet crashes during integration testing
[ { "change_type": "MODIFY", "old_path": "tests/oneclick/src/main.rs", "new_path": "tests/oneclick/src/main.rs", "diff": "@@ -398,6 +398,11 @@ impl OwnedChildProcess {\n)),\n}\n}\n+\n+ fn exited(&mut self) -> anyhow::Result<bool> {\n+ let exit_status = self.child.try_wait()?;\n+ Ok(exit_status.is_some())\n+ }\n}\nimpl Drop for OwnedChildProcess {\n@@ -441,6 +446,8 @@ fn run_tests(readiness: BootstrapReadiness) -> anyhow::Result<()> {\nlet mut wascc_process = wascc_process_result.unwrap();\nif matches!(test_result, Err(_)) {\n+ warn_if_premature_exit(&mut wasi_process, \"krustlet-wasi\");\n+ warn_if_premature_exit(&mut wascc_process, \"krustlet-wascc\");\n// TODO: ideally we shouldn't have to wait for termination before getting logs\nlet terminate_result = wasi_process\n.terminate()\n@@ -470,6 +477,17 @@ fn run_tests(readiness: BootstrapReadiness) -> anyhow::Result<()> {\ntest_result\n}\n+fn warn_if_premature_exit(process: &mut OwnedChildProcess, name: &str) {\n+ match process.exited() {\n+ Err(e) => eprintln!(\n+ \"FAILED checking kubelet process {} exit state ({})\",\n+ name, e\n+ ),\n+ Ok(false) => eprintln!(\"WARNING: Kubelet process {} exited prematurely\", name),\n+ _ => (),\n+ };\n+}\n+\nfn run_test_suite() -> anyhow::Result<()> {\nprintln!(\"Launching integration tests\");\nlet test_process = std::process::Command::new(\"cargo\")\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Warn if a kubelet crashes during integration testing (#382)
350,405
10.09.2020 09:36:59
-43,200
716e70a603b854b02310f5e0401816f9c4fed90a
The podsmiter
[ { "change_type": "MODIFY", "old_path": "Cargo.toml", "new_path": "Cargo.toml", "diff": "@@ -42,7 +42,9 @@ rustls-tls = [\"kube/rustls-tls\", \"kubelet/rustls-tls\", \"wascc-provider/rustls-tl\nanyhow = \"1.0\"\ntokio = { version = \"0.2\", features = [\"macros\", \"rt-threaded\", \"time\"] }\nkube = { version= \"0.35\", default-features = false }\n+k8s-openapi = { version = \"0.8\", default-features = false, features = [\"v1_17\"] }\nenv_logger = \"0.7\"\n+futures = \"0.3\"\nkubelet = { path = \"./crates/kubelet\", version = \"0.4\", default-features = false, features = [\"cli\"] }\nwascc-provider = { path = \"./crates/wascc-provider\", version = \"0.4\", default-features = false }\n# wasi-provider = { path = \"./crates/wasi-provider\", version = \"0.4\", default-features = false }\n@@ -52,11 +54,9 @@ hostname = \"0.3\"\nregex = \"1.3\"\n[dev-dependencies]\n-futures = \"0.3\"\nserde_derive = \"1.0\"\nserde_json = \"1.0\"\nserde = \"1.0\"\n-k8s-openapi = { version = \"0.8\", default-features = false, features = [\"v1_17\"] }\nreqwest = { version = \"0.10\", default-features = false }\ntempfile = \"3.1\"\n@@ -81,3 +81,7 @@ path = \"src/krustlet-wascc.rs\"\n[[bin]]\nname = \"oneclick\"\npath = \"tests/oneclick/src/main.rs\"\n+\n+[[bin]]\n+name = \"podsmiter\"\n+path = \"tests/podsmiter/src/main.rs\"\n" }, { "change_type": "MODIFY", "old_path": "docs/community/developers.md", "new_path": "docs/community/developers.md", "diff": "@@ -167,6 +167,17 @@ kind of Kubernetes cluster you're using and so doesn't know how to infer a node\n_WARNING:_ The standalone integration tester has not been, er, tested on Windows.\nHashtag irony.\n+### Integration test debris\n+\n+There are some failure modes - for example image pull timeout - where the integration\n+tests are not able to complete cleanup of their resources. Specifically you can\n+sometimes get pods stuck in `Terminating`, which prevents namespace cleanup and\n+causes the next test run to break.\n+\n+You can forcibly clean up such debris by running `cargo run --bin podsmiter`. You\n+may need to wait a couple of minutes after pod deletion for the namespaces to be\n+collected.\n+\n## Creating your own Kubelets with Krustlet\nIf you want to create your own Kubelet based on Krustlet, all you need to do is implement a\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tests/podsmiter/src/main.rs", "diff": "+use k8s_openapi::api::core::v1::{Namespace, Pod};\n+use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;\n+use k8s_openapi::Metadata;\n+use kube::api::{Api, DeleteParams, ListParams};\n+\n+const E2E_NS_PREFIXES: &[&str] = &[\"wascc-e2e\", \"wasi-e2e\"];\n+\n+#[tokio::main(threaded_scheduler)]\n+async fn main() -> anyhow::Result<()> {\n+ let result = smite_all_integration_test_pods().await;\n+\n+ match &result {\n+ Ok(message) => println!(\"{}\", message),\n+ Err(e) => println!(\"{}\", e),\n+ };\n+\n+ result.map(|_| ())\n+}\n+\n+async fn smite_all_integration_test_pods() -> anyhow::Result<&'static str> {\n+ let client = match kube::Client::try_default().await {\n+ Ok(c) => c,\n+ Err(e) => {\n+ return Err(anyhow::anyhow!(\n+ \"Failed to acquire Kubernetes client: {}\",\n+ e\n+ ))\n+ }\n+ };\n+\n+ let namespaces = list_e2e_namespaces(client.clone()).await?;\n+\n+ if namespaces.is_empty() {\n+ return Ok(\"No e2e namespaces found\");\n+ }\n+ if !confirm_smite(&namespaces) {\n+ return Ok(\"Operation cancelled\");\n+ }\n+\n+ let pod_smite_operations = namespaces\n+ .iter()\n+ .map(|ns| smite_namespace_pods(client.clone(), ns));\n+ let pod_smite_results = futures::future::join_all(pod_smite_operations).await;\n+ let (_, pod_smite_errors) = pod_smite_results.partition_success();\n+\n+ if !pod_smite_errors.is_empty() {\n+ return Err(smite_failure_error(&pod_smite_errors));\n+ }\n+\n+ println!(\"Requested force-delete of all pods; requesting delete of namespaces...\");\n+\n+ let ns_smite_operations = namespaces\n+ .iter()\n+ .map(|ns| smite_namespace(client.clone(), ns));\n+ let ns_smite_results = futures::future::join_all(ns_smite_operations).await;\n+ let (_, ns_smite_errors) = ns_smite_results.partition_success();\n+\n+ if !ns_smite_errors.is_empty() {\n+ return Err(smite_failure_error(&ns_smite_errors));\n+ }\n+\n+ Ok(\"All e2e pods force-deleted; namespace cleanup may take a couple of minutes\")\n+}\n+\n+async fn list_e2e_namespaces(client: kube::Client) -> anyhow::Result<Vec<String>> {\n+ println!(\"Finding e2e namespaces...\");\n+\n+ let nsapi: Api<Namespace> = Api::all(client.clone());\n+ let nslist = nsapi.list(&ListParams::default()).await?;\n+\n+ Ok(nslist\n+ .iter()\n+ .map(name_of)\n+ .filter(|n| is_e2e_namespace(n))\n+ .collect())\n+}\n+\n+fn name_of(ns: &impl Metadata<Ty = ObjectMeta>) -> String {\n+ ns.metadata().unwrap().name.as_ref().unwrap().to_owned()\n+}\n+\n+fn is_e2e_namespace(namespace: &str) -> bool {\n+ E2E_NS_PREFIXES\n+ .iter()\n+ .any(|prefix| namespace.starts_with(prefix))\n+}\n+\n+async fn smite_namespace_pods(client: kube::Client, namespace: &str) -> anyhow::Result<()> {\n+ println!(\"Finding pods in namespace {}...\", namespace);\n+\n+ let podapi: Api<Pod> = Api::namespaced(client.clone(), namespace);\n+ let pods = podapi.list(&ListParams::default()).await?;\n+\n+ println!(\"Deleting pods in namespace {}...\", namespace);\n+\n+ let delete_operations = pods.iter().map(|p| smite_pod(&podapi, p));\n+ let delete_results = futures::future::join_all(delete_operations).await;\n+ let (_, errors) = delete_results.partition_success();\n+\n+ if !errors.is_empty() {\n+ return Err(smite_pods_failure_error(namespace, &errors));\n+ }\n+\n+ Ok(())\n+}\n+\n+async fn smite_pod(podapi: &Api<Pod>, pod: &Pod) -> anyhow::Result<()> {\n+ let pod_name = name_of(pod);\n+ let _ = podapi\n+ .delete(\n+ &pod_name,\n+ &DeleteParams {\n+ grace_period_seconds: Some(0),\n+ ..DeleteParams::default()\n+ },\n+ )\n+ .await?;\n+ Ok(())\n+}\n+\n+async fn smite_namespace(client: kube::Client, namespace: &str) -> anyhow::Result<()> {\n+ let nsapi: Api<Namespace> = Api::all(client.clone());\n+ nsapi.delete(namespace, &DeleteParams::default()).await?;\n+ Ok(())\n+}\n+\n+fn smite_failure_error(errors: &[anyhow::Error]) -> anyhow::Error {\n+ let message_list = errors\n+ .iter()\n+ .map(|e| format!(\"{}\", e))\n+ .collect::<Vec<_>>()\n+ .join(\"\\n\");\n+ anyhow::anyhow!(\n+ \"Some integration test resources were not cleaned up:\\n{}\",\n+ message_list\n+ )\n+}\n+\n+fn smite_pods_failure_error(namespace: &str, errors: &[anyhow::Error]) -> anyhow::Error {\n+ let message_list = errors\n+ .iter()\n+ .map(|e| format!(\" - {}\", e))\n+ .collect::<Vec<_>>()\n+ .join(\"\\n\");\n+ anyhow::anyhow!(\n+ \"- Namespace {}: pod delete(s) failed:\\n{}\",\n+ namespace,\n+ message_list\n+ )\n+}\n+\n+fn confirm_smite(namespaces: &[String]) -> bool {\n+ println!(\n+ \"Smite these namespaces and all resources within them: {}? (y/n) \",\n+ namespaces.join(\", \")\n+ );\n+ let mut response = String::new();\n+ match std::io::stdin().read_line(&mut response) {\n+ Err(e) => {\n+ eprintln!(\"Error reading response: {}\", e);\n+ confirm_smite(namespaces)\n+ }\n+ Ok(_) => response.starts_with('y') || response.starts_with('Y'),\n+ }\n+}\n+\n+// TODO: deduplicate with oneclick\n+\n+trait ResultSequence {\n+ type SuccessItem;\n+ type FailureItem;\n+ fn partition_success(self) -> (Vec<Self::SuccessItem>, Vec<Self::FailureItem>);\n+}\n+\n+impl<T, E: std::fmt::Debug> ResultSequence for Vec<Result<T, E>> {\n+ type SuccessItem = T;\n+ type FailureItem = E;\n+ fn partition_success(self) -> (Vec<Self::SuccessItem>, Vec<Self::FailureItem>) {\n+ let (success_results, error_results): (Vec<_>, Vec<_>) =\n+ self.into_iter().partition(|r| r.is_ok());\n+ let success_values = success_results.into_iter().map(|r| r.unwrap()).collect();\n+ let error_values = error_results\n+ .into_iter()\n+ .map(|r| r.err().unwrap())\n+ .collect();\n+ (success_values, error_values)\n+ }\n+}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
The podsmiter (#371)
350,405
11.09.2020 16:50:00
-43,200
66edbeb1134a3d71ed720c7716dba87d5f269f4e
Run secrets tests only when secrets are available
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -76,8 +76,6 @@ jobs:\nKRUSTLET_NODE_IP: \"172.17.0.1\"\n# The default location for the cert is not accessible on build hosts, so do it in the current dir\nCONFIG_DIR: \"./config\"\n- KRUSTLET_TEST_ENV: \"ci\"\n- KRUSTLET_E2E_IMAGE_PULL_SECRET: ${{ secrets.KRUSTLET_E2E_IMAGE_PULL_SECRET }}\nrun: |\njust bootstrap\njust build\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".github/workflows/ci.yml", "diff": "+name: Build and Test\n+on:\n+ push:\n+ branches:\n+ - master\n+ paths-ignore:\n+ - \"docs/**\"\n+jobs:\n+ build:\n+ runs-on: ${{ matrix.config.os }}\n+ strategy:\n+ fail-fast: false\n+ matrix:\n+ config:\n+ - {\n+ os: \"ubuntu-latest\",\n+ url: \"https://github.com/casey/just/releases/download/v0.5.11/just-v0.5.11-x86_64-unknown-linux-musl.tar.gz\",\n+ name: \"just\",\n+ pathInArchive: \"just\",\n+ }\n+ - {\n+ os: \"macos-latest\",\n+ url: \"https://github.com/casey/just/releases/download/v0.5.11/just-v0.5.11-x86_64-apple-darwin.tar.gz\",\n+ name: \"just\",\n+ pathInArchive: \"just\",\n+ }\n+ steps:\n+ - uses: actions/checkout@v2\n+ - uses: engineerd/[email protected]\n+ with:\n+ name: ${{ matrix.config.name }}\n+ url: ${{ matrix.config.url }}\n+ pathInArchive: ${{ matrix.config.pathInArchive }}\n+ # hack(bacongobbler): install rustfmt to work around darwin toolchain issues\n+ - name: \"(macOS) install dev tools\"\n+ if: runner.os == 'macOS'\n+ run: |\n+ rustup component add rustfmt --toolchain stable-x86_64-apple-darwin\n+ rustup component add clippy --toolchain stable-x86_64-apple-darwin\n+ - name: Build\n+ run: |\n+ just build\n+ just test\n+ windows-build:\n+ runs-on: windows-latest\n+ defaults:\n+ run:\n+ # For some reason, running with the default powershell doesn't work with the `Build` step,\n+ # but bash does!\n+ shell: bash\n+ steps:\n+ - uses: actions/checkout@v2\n+ - uses: engineerd/[email protected]\n+ with:\n+ name: just\n+ url: \"https://github.com/casey/just/releases/download/v0.5.11/just-v0.5.11-x86_64-pc-windows-msvc.zip\"\n+ pathInArchive: just.exe\n+ - name: Build\n+ run: |\n+ just --justfile justfile-windows build\n+ just --justfile justfile-windows test\n+ # TODO: Figure out how to get kind or minikube running on a windows test host and see how we can\n+ # get things working with rustls\n+ # windows-e2e:\n+ # runs-on: windows-latest\n+ e2e:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: actions/checkout@v2\n+ - uses: engineerd/[email protected]\n+ - uses: engineerd/[email protected]\n+ with:\n+ name: just\n+ url: https://github.com/casey/just/releases/download/v0.5.11/just-v0.5.11-x86_64-unknown-linux-musl.tar.gz\n+ pathInArchive: just\n+ - name: Run e2e tests\n+ env:\n+ KRUSTLET_NODE_IP: \"172.17.0.1\"\n+ # The default location for the cert is not accessible on build hosts, so do it in the current dir\n+ CONFIG_DIR: \"./config\"\n+ KRUSTLET_TEST_ENV: \"ci\"\n+ KRUSTLET_E2E_IMAGE_PULL_SECRET: ${{ secrets.KRUSTLET_E2E_IMAGE_PULL_SECRET }}\n+ run: |\n+ just bootstrap\n+ just build\n+ KUBECONFIG=${CONFIG_DIR}/kubeconfig-wascc ./target/debug/krustlet-wascc --node-name krustlet-wascc --port 3000 --bootstrap-file ${CONFIG_DIR}/bootstrap.conf --cert-file ./config/krustlet-wascc.crt --private-key-file ./config/krustlet-wascc.key &\n+ # Wait for things to start before approving certs and then delete so we don't overlap with the same hostname\n+ sleep 5 && kubectl certificate approve $(hostname)-tls\n+ sleep 2 && kubectl delete csr $(hostname)-tls\n+ KUBECONFIG=${CONFIG_DIR}/kubeconfig-wasi ./target/debug/krustlet-wasi --node-name krustlet-wasi --port 3001 --bootstrap-file ${CONFIG_DIR}/bootstrap.conf --cert-file ./config/krustlet-wasi.crt --private-key-file ./config/krustlet-wasi.key &\n+ sleep 5 && kubectl certificate approve $(hostname)-tls\n+ sleep 2 && kubectl delete csr $(hostname)-tls\n+ just test-e2e\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Run secrets tests only when secrets are available (#383)
350,405
22.09.2020 11:49:57
-43,200
5dd4610939d974fecbc2414519c72da0afb3b720
WASCC pods should transition to error state instead of kerploding
[ { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/starting.rs", "new_path": "crates/wascc-provider/src/states/starting.rs", "diff": "@@ -16,6 +16,7 @@ use crate::PodState;\nuse crate::VolumeBinding;\nuse crate::{wascc_run, ActorHandle, LogHandleFactory, WasccProvider};\n+use super::error::Error;\nuse super::running::Running;\n#[derive(Debug)]\n@@ -120,7 +121,13 @@ async fn start_container(\n.run_context\n.modules\n.remove(container.name())\n- .expect(\"FATAL ERROR: module map not properly populated\");\n+ .ok_or_else(|| {\n+ anyhow::anyhow!(\n+ \"FATAL ERROR: module map not properly populated ({}/{})\",\n+ pod.name(),\n+ container.name()\n+ )\n+ })?;\nlet lp = pod_state.shared.log_path.clone();\nlet host = pod_state.shared.host.clone();\ntokio::task::spawn_blocking(move || {\n@@ -144,25 +151,62 @@ impl State<PodState> for Starting {\nlet mut container_handles = HashMap::new();\nfor container in pod.containers() {\n- let port_assigned =\n- assign_container_port(Arc::clone(&pod_state.shared.port_map), &pod, &container)\n- .await?;\n+ let port_assigned = match assign_container_port(\n+ Arc::clone(&pod_state.shared.port_map),\n+ &pod,\n+ &container,\n+ )\n+ .await\n+ {\n+ Ok(port) => port,\n+ Err(e) => {\n+ error!(\"{:?}\", e);\n+ let error_state = Error {\n+ message: e.to_string(),\n+ };\n+ return Ok(Transition::next(self, error_state));\n+ }\n+ };\ndebug!(\n\"New port assigned to {} is: {}\",\ncontainer.name(),\nport_assigned\n);\n- let container_handle = start_container(pod_state, &container, &pod, port_assigned)\n- .await\n- .unwrap();\n+ let container_handle =\n+ match start_container(pod_state, &container, &pod, port_assigned).await {\n+ Ok(handle) => handle,\n+ Err(e) => {\n+ // TODO: identify if any of the start_container errors are fatal\n+ // enough that we should return an Err and exit the run loop\n+ error!(\"{:?}\", e);\n+ let error_state = Error {\n+ message: e.to_string(),\n+ };\n+ return Ok(Transition::next(self, error_state));\n+ }\n+ };\ncontainer_handles.insert(\nContainerKey::App(container.name().to_string()),\ncontainer_handle,\n);\n}\n- let pod_handle = Handle::new(container_handles, pod.clone(), None).await?;\n+ // TODO: I don't think Handle::new can ever return an Error.\n+ // Can we safely change it to return a Self instead of a Result<Self>?\n+ // Then we could get rid of all this.\n+ // TODO: Does Handle::new still need to be async? It doesn't seem to\n+ // await anything.\n+ let pod_handle = match Handle::new(container_handles, pod.clone(), None).await {\n+ Ok(handle) => handle,\n+ Err(e) => {\n+ error!(\"{:?}\", e);\n+ let error_state = Error {\n+ message: e.to_string(),\n+ };\n+ return Ok(Transition::next(self, error_state));\n+ }\n+ };\nlet pod_key = key_from_pod(&pod);\n{\nlet mut handles = pod_state.shared.handles.write().await;\n@@ -184,3 +228,4 @@ impl State<PodState> for Starting {\n}\nimpl TransitionTo<Running> for Starting {}\n+impl TransitionTo<Error> for Starting {}\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/terminated.rs", "new_path": "crates/wascc-provider/src/states/terminated.rs", "diff": "@@ -14,7 +14,7 @@ impl State<PodState> for Terminated {\n) -> anyhow::Result<Transition<PodState>> {\nlet mut lock = pod_state.shared.handles.write().await;\nif let Some(handle) = lock.get_mut(&pod_state.key) {\n- handle.stop().await.unwrap()\n+ handle.stop().await?;\n}\nOk(Transition::Complete(Ok(())))\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/wascc-provider/src/states/volume_mount.rs", "new_path": "crates/wascc-provider/src/states/volume_mount.rs", "diff": "use crate::PodState;\nuse kubelet::state::prelude::*;\nuse kubelet::volume::Ref;\n+use log::error;\n+use super::error::Error;\nuse super::starting::Starting;\n/// Kubelet is pulling container images.\n@@ -15,13 +17,22 @@ impl State<PodState> for VolumeMount {\npod_state: &mut PodState,\npod: &Pod,\n) -> anyhow::Result<Transition<PodState>> {\n- pod_state.run_context.volumes = Ref::volumes_from_pod(\n+ pod_state.run_context.volumes = match Ref::volumes_from_pod(\n&pod_state.shared.volume_path,\n&pod,\n&pod_state.shared.client,\n)\n.await\n- .unwrap();\n+ {\n+ Ok(volumes) => volumes,\n+ Err(e) => {\n+ error!(\"{:?}\", e);\n+ let error_state = Error {\n+ message: e.to_string(),\n+ };\n+ return Ok(Transition::next(self, error_state));\n+ }\n+ };\nOk(Transition::next(self, Starting))\n}\n@@ -35,3 +46,4 @@ impl State<PodState> for VolumeMount {\n}\nimpl TransitionTo<Starting> for VolumeMount {}\n+impl TransitionTo<Error> for VolumeMount {}\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/states/terminated.rs", "new_path": "crates/wasi-provider/src/states/terminated.rs", "diff": "@@ -14,7 +14,7 @@ impl State<PodState> for Terminated {\n) -> anyhow::Result<Transition<PodState>> {\nlet mut lock = pod_state.shared.handles.write().await;\nif let Some(handle) = lock.get_mut(&pod_state.key) {\n- handle.stop().await.unwrap()\n+ handle.stop().await?;\n}\nOk(Transition::Complete(Ok(())))\n}\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/src/states/volume_mount.rs", "new_path": "crates/wasi-provider/src/states/volume_mount.rs", "diff": "use crate::PodState;\nuse kubelet::state::prelude::*;\nuse kubelet::volume::Ref;\n+use log::error;\n+use super::error::Error;\nuse super::initializing::Initializing;\n/// Kubelet is pulling container images.\n@@ -17,9 +19,16 @@ impl State<PodState> for VolumeMount {\n) -> anyhow::Result<Transition<PodState>> {\nlet client = kube::Client::new(pod_state.shared.kubeconfig.clone());\npod_state.run_context.volumes =\n- Ref::volumes_from_pod(&pod_state.shared.volume_path, &pod, &client)\n- .await\n- .unwrap();\n+ match Ref::volumes_from_pod(&pod_state.shared.volume_path, &pod, &client).await {\n+ Ok(volumes) => volumes,\n+ Err(e) => {\n+ error!(\"{:?}\", e);\n+ let error_state = Error {\n+ message: e.to_string(),\n+ };\n+ return Ok(Transition::next(self, error_state));\n+ }\n+ };\nOk(Transition::next(self, Initializing))\n}\n@@ -33,3 +42,4 @@ impl State<PodState> for VolumeMount {\n}\nimpl TransitionTo<Initializing> for VolumeMount {}\n+impl TransitionTo<Error> for VolumeMount {}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
WASCC pods should transition to error state instead of kerploding (#389)
350,405
29.09.2020 13:02:55
-46,800
c4e55aa3a2c4f9dc08ab6c3da8629434c7012724
Remove accidentally committed log files
[ { "change_type": "DELETE", "old_path": "krustlet-wascc-e2e.stderr.txt", "new_path": null, "diff": "-[2020-09-23T20:10:21Z INFO wascc_host::bus::inproc] Initialized Message Bus (internal)\n-[2020-09-23T20:10:21Z INFO wascc_host] Host ID is NABATKGUA76KCMPPVETB2XCWU5JNSIVUGIOML35V65UGCLZWCUF2CYYD (v0.10.1)\n-[2020-09-23T20:10:21Z INFO wascc_host::capability] Loaded native capability provider 'waSCC Extras (Internal)' v0.10.1 (2) for wascc:extras/default\n-[2020-09-23T20:10:21Z INFO wascc_host::spawns] Native capability provider '(default,wascc:extras)' ready\n-[2020-09-23T20:10:21Z INFO wascc_provider] Loading HTTP capability\n-[2020-09-23T20:10:21Z INFO wascc_host::capability] Loaded native capability provider 'Default waSCC HTTP Server Provider (Actix)' v0.7.0 (2) for wascc:http_server/default\n-[2020-09-23T20:10:21Z INFO wascc_host::spawns] Native capability provider '(default,wascc:http_server)' ready\n-[2020-09-23T20:10:21Z INFO wascc_provider] Loading log capability\n-[2020-09-23T20:10:21Z INFO wascc_host::capability] Loaded native capability provider 'krustlet Logging Provider' v0.1.0 (1) for wascc:logging/default\n-[2020-09-23T20:10:21Z INFO wascc_host::spawns] Native capability provider '(default,wascc:logging)' ready\n-[2020-09-23T20:10:21Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:21Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:26Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:26Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:31Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:31Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:36Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:36Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:38Z INFO wascc_provider::states::registered] Pod added: greet-wascc.\n-[2020-09-23T20:10:38Z INFO wascc_provider::states::starting] Starting containers for pod \"greet-wascc\"\n-[2020-09-23T20:10:38Z DEBUG wascc_provider::states::starting] New port assigned to greet-wascc is: 30000\n-[2020-09-23T20:10:38Z DEBUG wascc_provider::states::starting] Starting container greet-wascc on thread\n-[2020-09-23T20:10:38Z INFO wascc_provider] sending actor to wascc host\n-[2020-09-23T20:10:38Z INFO wascc_host::authz] Discovered capability attestations for actor MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC: wascc:http_server,wascc:logging\n-[2020-09-23T20:10:39Z INFO wascc_provider] configuring capability wascc:logging\n-[2020-09-23T20:10:39Z INFO wascc_host] Attempting to bind actor MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC to default,wascc:logging\n-[2020-09-23T20:10:39Z INFO wascc_host] Binding subject: wasmbus.provider.wascc.logging.default\n-[2020-09-23T20:10:39Z INFO wascc_provider] configuring capability wascc:http_server\n-[2020-09-23T20:10:39Z INFO wascc_host] Attempting to bind actor MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC to default,wascc:http_server\n-[2020-09-23T20:10:39Z INFO wascc_host] Binding subject: wasmbus.provider.wascc.http_server.default\n-[2020-09-23T20:10:39Z INFO wascc_provider] wascc actor executing\n-[2020-09-23T20:10:39Z INFO wascc_provider::states::starting] All containers started for pod \"greet-wascc\".\n-[2020-09-23T20:10:40Z DEBUG wascc_provider] stopping wascc instance MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC\n-[2020-09-23T20:10:40Z INFO wascc_host::spawns] Terminating actor MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC\n-[2020-09-23T20:10:40Z INFO wascc_host::inthost] Unbinding actor MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC from default,wascc:logging\n-[2020-09-23T20:10:40Z INFO wascc_host::inthost] Unbinding actor MDXEE6PA62JOB2L3GC7UVOGL7A746PLGCKGSBI2G4SV5H36CGAYLRQZC from default,wascc:http_server\n-[2020-09-23T20:10:41Z DEBUG wascc_provider] Pod default:greet-wascc releasing ports [30000].\n-[2020-09-23T20:10:46Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:46Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:51Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:51Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:56Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:10:56Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:11:01Z INFO wascc_provider::states::registered] Pod added: kube-proxy-4n9zb.\n-[2020-09-23T20:11:01Z ERROR wascc_provider::states::registered] Cannot run kube-proxy\n" }, { "change_type": "DELETE", "old_path": "krustlet-wascc-e2e.stdout.txt", "new_path": "krustlet-wascc-e2e.stdout.txt", "diff": "" }, { "change_type": "DELETE", "old_path": "krustlet-wasi-e2e.stderr.txt", "new_path": null, "diff": "-[2020-09-23T20:10:21Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:26Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:31Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: hello-wasi-with-inits.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: hello-world-verbose.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: faily-inits-pod.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: multi-mount-pod.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: faily-pod.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Starting init container \"init-1\" for pod \"hello-wasi-with-inits\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: hello-wasi.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: loggy-pod.\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container init-1 on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /tmp/.tmpd63UZP as guestpath /hp\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-wasi-with-inits-wasi-e2e-init-containers/default-token-xcrrh as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Finished init containers for pod \"hello-world-verbose\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::registered] Pod added: multi-mount-items-pod.\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] Starting containers for pod \"hello-world-verbose\"\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container hello-world-verbose on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-world-verbose-wasi-e2e-container-args/default-token-4x4jp as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] All containers started for pod \"hello-world-verbose\".\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Finished init containers for pod \"multi-mount-pod\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] Starting containers for pod \"multi-mount-pod\"\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container multimount on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/multi-mount-pod-wasi-e2e-can-mount-multi-values/multisecret as guestpath /ms\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/multi-mount-pod-wasi-e2e-can-mount-multi-values/multicm as guestpath /mcm\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/multi-mount-pod-wasi-e2e-can-mount-multi-values/default-token-4v5ql as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] All containers started for pod \"multi-mount-pod\".\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Finished init containers for pod \"faily-pod\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Finished init containers for pod \"hello-wasi\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Starting init container \"init-that-fails\" for pod \"faily-inits-pod\"\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container init-that-fails on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-inits-pod-wasi-e2e-failing-init-containers/default-token-cbzr6 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Finished init containers for pod \"loggy-pod\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] Starting containers for pod \"loggy-pod\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] Starting containers for pod \"faily-pod\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] Starting containers for pod \"hello-wasi\"\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container floofycat on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/loggy-pod-wasi-e2e-container-logging/default-token-lppdj as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container faily-pod on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container hello-wasi on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-wasi-wasi-e2e-pod-logs-and-mounts/secret-test as guestpath /foo\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-wasi-wasi-e2e-pod-logs-and-mounts/configmap-test as guestpath /bar\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /tmp/.tmp9N6W0M as guestpath /baz\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-wasi-wasi-e2e-pod-logs-and-mounts/default-token-g7kfc as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] All containers started for pod \"hello-wasi\".\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container neatcat on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-pod-wasi-e2e-module-exit-error/default-token-wtl88 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/loggy-pod-wasi-e2e-container-logging/default-token-lppdj as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] All containers started for pod \"loggy-pod\".\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] All containers started for pod \"faily-pod\".\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::initializing] Finished init containers for pod \"multi-mount-items-pod\"\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] Starting containers for pod \"multi-mount-items-pod\"\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::states::starting] Starting container multimount on thread\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/multi-mount-items-pod-wasi-e2e-can-mount-individual-values/default-token-k67gm as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/multi-mount-items-pod-wasi-e2e-can-mount-individual-values/multicm as guestpath /mcm\n-[2020-09-23T20:10:33Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/multi-mount-items-pod-wasi-e2e-can-mount-individual-values/multisecret as guestpath /ms\n-[2020-09-23T20:10:33Z INFO wasi_provider::states::starting] All containers started for pod \"multi-mount-items-pod\".\n-[2020-09-23T20:10:36Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z ERROR wasi_provider::wasi_runtime] unable to run module: Exited with i32 exit status 1\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:37Z ERROR wasi_provider::wasi_runtime] unable to run module: Exited with i32 exit status 1\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:37Z INFO wasi_provider::states::initializing] Starting init container \"init-2\" for pod \"hello-wasi-with-inits\"\n-[2020-09-23T20:10:37Z DEBUG wasi_provider::states::starting] Starting container init-2 on thread\n-[2020-09-23T20:10:37Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-wasi-with-inits-wasi-e2e-init-containers/default-token-xcrrh as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:37Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /tmp/.tmpd63UZP as guestpath /hp\n-[2020-09-23T20:10:38Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:38Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:38Z INFO wasi_provider::states::initializing] Finished init containers for pod \"hello-wasi-with-inits\"\n-[2020-09-23T20:10:38Z INFO wasi_provider::states::starting] Starting containers for pod \"hello-wasi-with-inits\"\n-[2020-09-23T20:10:38Z DEBUG wasi_provider::states::starting] Starting container hello-wasi-with-inits on thread\n-[2020-09-23T20:10:38Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/hello-wasi-with-inits-wasi-e2e-init-containers/default-token-xcrrh as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:38Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /tmp/.tmpd63UZP as guestpath /hp\n-[2020-09-23T20:10:38Z INFO wasi_provider::states::starting] All containers started for pod \"hello-wasi-with-inits\".\n-[2020-09-23T20:10:39Z INFO wasi_provider::wasi_runtime] starting run of module\n-[2020-09-23T20:10:39Z INFO wasi_provider::wasi_runtime] module run complete\n-[2020-09-23T20:10:42Z INFO wasi_provider::states::registered] Pod added: faily-pod.\n-[2020-09-23T20:10:42Z INFO wasi_provider::states::registered] Pod added: faily-inits-pod.\n-[2020-09-23T20:10:42Z INFO wasi_provider::states::initializing] Finished init containers for pod \"faily-pod\"\n-[2020-09-23T20:10:42Z INFO wasi_provider::states::starting] Starting containers for pod \"faily-pod\"\n-[2020-09-23T20:10:42Z DEBUG wasi_provider::states::starting] Starting container faily-pod on thread\n-[2020-09-23T20:10:42Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-pod-wasi-e2e-module-exit-error/default-token-wtl88 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:42Z ERROR wasi_provider::states::starting] channel closed\n-[2020-09-23T20:10:42Z INFO wasi_provider::states::initializing] Starting init container \"init-that-fails\" for pod \"faily-inits-pod\"\n-[2020-09-23T20:10:42Z DEBUG wasi_provider::states::starting] Starting container init-that-fails on thread\n-[2020-09-23T20:10:42Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-inits-pod-wasi-e2e-failing-init-containers/default-token-cbzr6 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:42Z ERROR wasi_provider::states::initializing] channel closed\n-[2020-09-23T20:10:46Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:47Z INFO wasi_provider::states::registered] Pod added: faily-pod.\n-[2020-09-23T20:10:47Z INFO wasi_provider::states::registered] Pod added: faily-inits-pod.\n-[2020-09-23T20:10:48Z INFO wasi_provider::states::initializing] Starting init container \"init-that-fails\" for pod \"faily-inits-pod\"\n-[2020-09-23T20:10:48Z DEBUG wasi_provider::states::starting] Starting container init-that-fails on thread\n-[2020-09-23T20:10:48Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-inits-pod-wasi-e2e-failing-init-containers/default-token-cbzr6 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:48Z ERROR wasi_provider::states::initializing] channel closed\n-[2020-09-23T20:10:48Z INFO wasi_provider::states::initializing] Finished init containers for pod \"faily-pod\"\n-[2020-09-23T20:10:48Z INFO wasi_provider::states::starting] Starting containers for pod \"faily-pod\"\n-[2020-09-23T20:10:48Z DEBUG wasi_provider::states::starting] Starting container faily-pod on thread\n-[2020-09-23T20:10:48Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-pod-wasi-e2e-module-exit-error/default-token-wtl88 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:48Z ERROR wasi_provider::states::starting] channel closed\n-[2020-09-23T20:10:51Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:10:53Z INFO wasi_provider::states::registered] Pod added: faily-inits-pod.\n-[2020-09-23T20:10:53Z INFO wasi_provider::states::initializing] Starting init container \"init-that-fails\" for pod \"faily-inits-pod\"\n-[2020-09-23T20:10:53Z DEBUG wasi_provider::states::starting] Starting container init-that-fails on thread\n-[2020-09-23T20:10:53Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-inits-pod-wasi-e2e-failing-init-containers/default-token-cbzr6 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:53Z ERROR wasi_provider::states::initializing] channel closed\n-[2020-09-23T20:10:53Z INFO wasi_provider::states::registered] Pod added: faily-pod.\n-[2020-09-23T20:10:53Z INFO wasi_provider::states::initializing] Finished init containers for pod \"faily-pod\"\n-[2020-09-23T20:10:53Z INFO wasi_provider::states::starting] Starting containers for pod \"faily-pod\"\n-[2020-09-23T20:10:53Z DEBUG wasi_provider::states::starting] Starting container faily-pod on thread\n-[2020-09-23T20:10:53Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-pod-wasi-e2e-module-exit-error/default-token-wtl88 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:10:53Z ERROR wasi_provider::states::starting] channel closed\n-[2020-09-23T20:10:56Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:11:01Z ERROR wasi_provider::states::registered] Cannot run kube-proxy\n-[2020-09-23T20:11:03Z INFO wasi_provider::states::registered] Pod added: faily-inits-pod.\n-[2020-09-23T20:11:03Z INFO wasi_provider::states::registered] Pod added: faily-pod.\n-[2020-09-23T20:11:03Z INFO wasi_provider::states::initializing] Starting init container \"init-that-fails\" for pod \"faily-inits-pod\"\n-[2020-09-23T20:11:03Z DEBUG wasi_provider::states::starting] Starting container init-that-fails on thread\n-[2020-09-23T20:11:03Z DEBUG wasi_provider::wasi_runtime] mounting hostpath /home/ivan/.krustlet/volumes/faily-inits-pod-wasi-e2e-failing-init-containers/default-token-cbzr6 as guestpath /var/run/secrets/kubernetes.io/serviceaccount\n-[2020-09-23T20:11:03Z ERROR wasi_provider::states::initializing] channel closed\n" }, { "change_type": "DELETE", "old_path": "krustlet-wasi-e2e.stdout.txt", "new_path": "krustlet-wasi-e2e.stdout.txt", "diff": "" } ]
Rust
Apache License 2.0
krustlet/krustlet
Remove accidentally committed log files (#411)
350,426
08.10.2020 09:41:12
18,000
b59b5df67ba74e9f1b8faffd64030271d3897c91
Remove Type Length Patch Rust `1.47.0` appears to have fixed this issue.
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -196,7 +196,7 @@ impl TryFrom<String> for Reference {\n_ => return Err(ParseError::DigestUnsupported),\n}\n}\n- return Ok(reference);\n+ Ok(reference)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wascc.rs", "new_path": "src/krustlet-wascc.rs", "diff": "-#![type_length_limit = \"1271125\"]\nuse kubelet::config::Config;\nuse kubelet::store::composite::ComposableStore;\nuse kubelet::store::oci::FileStore;\n" }, { "change_type": "MODIFY", "old_path": "src/krustlet-wasi.rs", "new_path": "src/krustlet-wasi.rs", "diff": "-#![type_length_limit = \"1271125\"]\nuse kubelet::config::Config;\nuse kubelet::store::composite::ComposableStore;\nuse kubelet::store::oci::FileStore;\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Remove Type Length Patch Rust `1.47.0` appears to have fixed this issue.
350,405
11.11.2020 11:29:02
-46,800
0ceaf0803eb30774f333499728d5c1c74dde7712
References were formatted incorrectly on Windows
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "use std::convert::{Into, TryFrom};\nuse std::error::Error;\nuse std::fmt;\n-use std::path::PathBuf;\nuse std::str::FromStr;\nuse crate::regexp;\n@@ -90,10 +89,11 @@ impl Reference {\n/// full_name returns the full repository name and path.\nfn full_name(&self) -> String {\n- let mut path = PathBuf::new();\n- path.push(self.registry());\n- path.push(self.repository());\n- path.to_str().unwrap_or(\"\").to_owned()\n+ if self.registry() == \"\" {\n+ format!(\"{}\", self.repository())\n+ } else {\n+ format!(\"{}/{}\", self.registry(), self.repository())\n+ }\n}\n/// whole returns the whole reference.\n@@ -273,6 +273,7 @@ mod test {\nassert_eq!(repository, reference.repository());\nassert_eq!(tag, reference.tag());\nassert_eq!(digest, reference.digest());\n+ assert_eq!(input, reference.whole());\n}\n#[rstest(input, err,\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
References were formatted incorrectly on Windows (#451)
350,426
21.12.2020 22:22:36
25,200
fad7754fcb314d67ecee9044e9fd8c802a09df6c
Add markdownlint to ci process.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -9,6 +9,25 @@ on:\npaths-ignore:\n- \"docs/**\"\njobs:\n+ lint_docs:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: actions/checkout@v2\n+ - uses: engineerd/[email protected]\n+ with:\n+ version: \"v0.9.0\"\n+ - uses: engineerd/[email protected]\n+ with:\n+ name: just\n+ url: https://github.com/casey/just/releases/download/v0.5.11/just-v0.5.11-x86_64-unknown-linux-musl.tar.gz\n+ pathInArchive: just\n+ - uses: actions/setup-node@v2\n+ with:\n+ node-version: '14'\n+ - name: Install markdownlint\n+ run: npm install -g markdownlint-cli\n+ - name: markdownlint\n+ run: just lint-docs\nbuild:\nruns-on: ${{ matrix.config.os }}\nenv: ${{ matrix.config.env }}\n" }, { "change_type": "MODIFY", "old_path": "justfile", "new_path": "justfile", "diff": "@@ -7,6 +7,9 @@ run: build\nbuild +FLAGS='':\ncargo build {{FLAGS}}\n+lint-docs:\n+ markdownlint '**/*.md' -c .markdownlint.json\n+\ntest:\ncargo fmt --all -- --check\ncargo clippy --workspace\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Add markdownlint to ci process.
350,426
21.12.2020 22:26:04
25,200
08fde3a5f811c7e955aac77194617dee3de3eae8
Dont setup Kind for markdown linting.
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -13,9 +13,6 @@ jobs:\nruns-on: ubuntu-latest\nsteps:\n- uses: actions/checkout@v2\n- - uses: engineerd/[email protected]\n- with:\n- version: \"v0.9.0\"\n- uses: engineerd/[email protected]\nwith:\nname: just\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Dont setup Kind for markdown linting.
350,426
21.12.2020 22:28:44
25,200
af6f1e6d30eca46c3590bf9b816d5ec1c3d22cd5
Bump configurator version
[ { "change_type": "MODIFY", "old_path": ".github/workflows/build.yml", "new_path": ".github/workflows/build.yml", "diff": "@@ -13,7 +13,7 @@ jobs:\nruns-on: ubuntu-latest\nsteps:\n- uses: actions/checkout@v2\n- - uses: engineerd/[email protected]\n+ - uses: engineerd/[email protected]\nwith:\nname: just\nurl: https://github.com/casey/just/releases/download/v0.5.11/just-v0.5.11-x86_64-unknown-linux-musl.tar.gz\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Bump configurator version
350,427
13.01.2021 13:45:14
18,000
21dba7b6847aeba2938976b653cad1e198223117
adding gke to the docs to make it easy
[ { "change_type": "MODIFY", "old_path": "docs/howto/README.md", "new_path": "docs/howto/README.md", "diff": "@@ -8,6 +8,7 @@ quickly accomplish common tasks.\n- [Running Krustlet on Azure](krustlet-on-azure.md)\n- [Running Krustlet on Amazon Elastic Kubernetes Service\n(EKS)](krustlet-on-eks.md)\n+- [Running Krustlet on Google Kubernetes Engine (GKE)](krustlet-on-gke.ms)\n- [Running Krustlet on Kubernetes-in-Docker (KinD)](krustlet-on-kind.md)\n- [Running Krustlet on Minikube](krustlet-on-minikube.md)\n- [Running Krustlet on any Kubernetes cluster with\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
adding gke to the docs to make it easy
350,427
13.01.2021 13:59:22
18,000
69ad615c62571fa5b37267ba849a63827b746701
typo because I'm an idiot
[ { "change_type": "MODIFY", "old_path": "docs/howto/README.md", "new_path": "docs/howto/README.md", "diff": "@@ -8,7 +8,7 @@ quickly accomplish common tasks.\n- [Running Krustlet on Azure](krustlet-on-azure.md)\n- [Running Krustlet on Amazon Elastic Kubernetes Service\n(EKS)](krustlet-on-eks.md)\n-- [Running Krustlet on Google Kubernetes Engine (GKE)](krustlet-on-gke.ms)\n+- [Running Krustlet on Google Kubernetes Engine (GKE)](krustlet-on-gke.md)\n- [Running Krustlet on Kubernetes-in-Docker (KinD)](krustlet-on-kind.md)\n- [Running Krustlet on Minikube](krustlet-on-minikube.md)\n- [Running Krustlet on any Kubernetes cluster with\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
typo because I'm an idiot
350,422
20.01.2021 12:35:39
28,800
1a3aafdbdb60c0be046e774d4b41e7368902a748
Added clarity|explanation
[ { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-microk8s.md", "new_path": "docs/howto/krustlet-on-microk8s.md", "diff": "@@ -42,6 +42,8 @@ that you generated through another process, you can proceed to the next step.\nHowever, the credentials Krustlet uses must be part of the `system:nodes` group\nin order for things to function properly.\n+> **NOTE** You should now have a file `bootstrap.conf` in `${HOME}/.krustlet/config`\n+\n## Step 2: Install and configure Krustlet\nInstall the latest release of Krustlet following [the install\n@@ -51,12 +53,22 @@ There are 2 binaries (`krustlet-wasi` and `krustlet-wascc`), let's start the\nfirst:\n```console\n-$ ./krustlet-wasi \\\n+$ ./KUBECONFIG=${PWD}/krustlet-config \\\n+ krustlet-wasi \\\n--node-ip=127.0.0.1 \\\n--node-name=krustlet \\\n---bootstrap-file=~/.krustlet/config/bootstrap.conf\n+ --bootstrap-file=${HOME}/.krustlet/config/bootstrap.conf\n```\n+> **NOTE**: To avoid the Krustlet using your default Kubernetes credentials (`~/.kube/config`),\n+it is a good idea to override the default value here using `KUBECONFIG`. For bootstrapping,\n+`KUBECONFIG` must point to a non-existent file (!). Bootstrapping will write a new\n+configuration file to this location for you.\n+\n+> **NOTE**: If you receive an error that the CSR already exists, you may safely delete\n+the existing CSR (`kubectl delete csr <hostname>-tls`) and try again.\n+\n+\n### Step 2a: Approving the serving CSR\nOnce you have started Krustlet, there is one more manual step (though this could\n@@ -71,7 +83,7 @@ run:\n$ microk8s.kubectl certificate approve <hostname>-tls\n```\n-NOTE: You will only need to do this approval step the first time Krustlet\n+> **NOTE**: You will only need to do this approval step the first time Krustlet\nstarts. It will generate and save all of the needed credentials to your machine\n## Step 3: Test that things work\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Added clarity|explanation
350,422
26.01.2021 11:30:43
28,800
df704a4065481f063ae55fb3fa7488c5e39ece87
DigitalOcean documentation
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/howto/krustlet-on-do.md", "diff": "+# Running Krustlet on Managed Kubernetes on DigitalOcean\n+\n+These steps are for running a Krustlet node on a DigitalOcean Droplet in a\n+Managed Kubernetes DigitalOcean cluster.\n+\n+## Prerequisites\n+\n+You will require a Managed Kubernetes on DigitalOcean cluster. See the [how-to\n+guide for running Managed Kubernetes on DigitalOcean](kubernetes-on-do.md) for\n+more information.\n+\n+This tutorial runs Krustlet on a DigitalOcean Droplet (VM); however you may\n+follow these steps from any device that can start a web server on an IP\n+accessible from the Kubernetes control plane.\n+\n+In the [how-to guide for running Managed Kubernetes on DigitalOcean](kubernetes-on-do.md),\n+several environment variables were used to define the cluster. Let's reuse\n+those values:\n+\n+```console\n+$ CLUSTER=[[YOUR-CLUSTER-NAME]]\n+$ VERSION=\"1.19.3-do.3\"\n+$ SIZE=\"s-1vcpu-2gb\"\n+$ REGION=\"sfo3\"\n+```\n+\n+Let's also confirm that the cluster exists:\n+\n+```console\n+$ doctl kubernetes cluster list\n+```\n+\n+## Step 1: Create DigitalOcean Droplet (VM)\n+\n+As with the cluster, there are several values (size, region) that you will need\n+to determine before you create the Droplet. `doctl compute` includes commands\n+to help you determine slugs for these values:\n+\n+```console\n+$ doctl compute size list\n+$ doctl compute region list\n+$ doctl compute image list --public\n+```\n+\n+If you'd prefer, you may use the values below. However, it is strongly\n+recommended that you use SSH keys to authenticate with Droplets. DigitalOcean\n+provides [instructions](https://www.digitalocean.com/docs/droplets/how-to/add-ssh-keys/).\n+\n+You may then list your SSH keys:\n+\n+```console\n+$ doctl compute ssh-key list\n+```\n+\n+> **NOTE** In this case, you reference the key using an `ID` value\n+\n+We can create a new DigitalOcean Droplet using the following command:\n+\n+```console\n+$ INSTANCE=[[YOUR-INSTANCE-NAME]]\n+$ SIZE=\"s-1vcpu-2gb\" # Need not be the same size as the cluster node(s)\n+$ REGION=\"sfo3\" # Need not be the same region as the cluster\n+IMAGE=\"debian-10-x64\"\n+SSH_KEY=[[YOUR-SSH-KEY]]\n+\n+doctl compute droplet create ${INSTANCE} \\\n+--region ${REGION} \\\n+--size ${SIZE} \\\n+--ssh-keys ${SSH_KEY} \\\n+--tag-names krustlet,wasm \\\n+--image ${IMAGE}\n+```\n+\n+> **NOTE** The service will response with an `ID` value for the Droplet. As long\n+as the Droplet name (`INSTANCE`) is unique, you may refer to the Droplet by its\n+name value too.\n+\n+You will need the Droplet's IPv4 public address so make a note of it (`IP`):\n+\n+```console\n+$ doctl compute droplet get ${INSTANCE} \\\n+ --format PublicIPv4 \\\n+ --no-header\n+```\n+\n+## Step 2: Get a bootstrap config for your Kustlet node\n+\n+Krustlet requires a bootstrap token and config the first time it runs. Follow\n+the guide [here](bootstrapping.md), setting the `CONFIG_DIR` variable to `./`,\n+to generate a bootstrap config and then return to this document. If you already\n+have a kubeconfig available that you generated through another process, you can\n+proceed to the next step. However, the credentials Krustlet uses must be part of\n+the `system:nodes` group in order for things to function properly.\n+\n+NOTE: You may be wondering why you can't run this on the VM you just\n+provisioned. We need access to the Kubernetes API in order to create the\n+bootstrap token, so the script used to generate the bootstrap config needs to be\n+run on a machine with the proper Kubernetes credentials.\n+\n+## Step 3: Copy bootstrap config to Droplet\n+\n+The first thing we'll need to do is copy up the assets we generated in steps 1\n+and 2. Copy them to the VM by typing:\n+\n+```console\n+scp -i ${PRIVATE_KEY} \\\n+ ${HOME}/.krustlet/config/bootstrap.conf \\\n+ root@${IP}:.\n+```\n+\n+> **NOTE** `IP` is the Droplet's IPv4 address from step #1 and `PRIVATE_KEY` is\n+the location of the file containing the private (!) key that corresponds to the\n+public key that you used when you created the Droplet.\n+\n+We can then SSH into the Droplet by typing:\n+\n+```console\n+$ doctl compute ssh ${INSTANCE} \\\n+ --ssh-key-path ${PRIVATE_KEY}\n+```\n+\n+If you'd prefer, you may use `ssh` directly:\n+\n+```console\n+$ ssh -i ${PRIVATE_KEY} root@${IP}\n+```\n+\n+## Step 4: Install and configure Kruslet\n+\n+Install the latest release of krustlet following [the install\n+guide](../intro/install.md).\n+\n+There are two flavors of Krustlet (`krustlet-wasi` and `krustlet-wascc`), let's\n+use the first:\n+\n+```console\n+$ KUBECONFIG=${PWD}/kubeconfig ${PWD}/krustlet-wasi \\\n+ --node-ip=${IP} \\\n+ --node-name=\"krustlet\" \\\n+ --bootstrap-file=${PWD}/bootstrap.conf \\\n+ --cert-file=${PWD}/krustlet.crt \\\n+ --private-key-file=${PWD}/krustlet.key\n+```\n+\n+> **NOTE** You'll need the `IP` of the Droplet from step 1.\n+\n+> **NOTE** To increase the level of debugging, you may prefix the command with\n+`RUST_LOG=info` or `RUST_LOG=debug`.\n+\n+If you restart the Krustlet after successfully (!) bootstrapping, you may run:\n+\n+```console\n+$ KUBECONFIG=${PWD}/kubeconfig ${PWD}/krustlet-wasi \\\n+ --node-ip=${IP} \\\n+ --node-name=\"krustlet\" \\\n+ --cert-file=${PWD}/krustlet.crt \\\n+ --private-key-file=${PWD}/krustlet.key\n+```\n+\n+If bootstrapping fails, you should delete the CSR and try to bootstrap again:\n+\n+```console\n+$ kubectl delete csr ${INSTANCE}-tls\n+```\n+\n+## Step 4a: Approving the serving CSR\n+\n+Once you have started Krustlet, there is one more manual step (though this could\n+be automated depending on your setup) to perform. The client certs Krustlet\n+needs are generally approved automatically by the API. However, the serving\n+certs require manual approval. To do this, you'll need the hostname you\n+specified for the `--hostname` flag or the output of `hostname` if you didn't\n+specify anything. From another terminal that's configured to access the cluster,\n+run:\n+\n+```console\n+$ kubectl certificate approve ${INSTANCE}-tls\n+```\n+\n+> **NOTE** You will only need to do this approval step the first time Krustlet\n+starts. It will generate and save all of the needed credentials to your machine.\n+\n+You should be able to enumerate the cluster's nodes including the Krustlet by\n+typing:\n+\n+```console\n+$ kubectl get nodes\n+NAME STATUS ROLES AGE VERSION\n+krustlet Ready <none> 60s 0.5.0\n+${CLUSTER}-default-pool-39yh5 Ready <none> 10m v1.19.3\n+```\n+\n+## Step 5: Test that things work\n+\n+We may test that the Krustlet is working by running one of the demos:\n+\n+```console\n+$ kubectl apply --filename=https://raw.githubusercontent.com/deislabs/krustlet/master/demos/wasi/hello-world-rust/k8s.yaml\n+$ kubectl get pods\n+NAME READY STATUS RESTARTS AGE\n+hello-world-wasi-rust 0/1 ExitCode:0 0 12s\n+\n+$ kubectl logs pods/hello-world-wasi-rust\n+hello from stdout!\n+hello from stderr!\n+FOO=bar\n+CONFIG_MAP_VAL=cool stuff\n+POD_NAME=hello-world-wasi-rust\n+Args are: []\n+\n+Bacon ipsum dolor amet chuck turducken porchetta, tri-tip spare ribs t-bone ham hock. Meatloaf\n+pork belly leberkas, ham beef pig corned beef boudin ground round meatball alcatra jerky.\n+Pancetta brisket pastrami, flank pork chop ball tip short loin burgdoggen. Tri-tip kevin\n+shoulder cow andouille. Prosciutto chislic cupim, short ribs venison jerky beef ribs ham hock\n+short loin fatback. Bresaola meatloaf capicola pancetta, prosciutto chicken landjaeger andouille\n+swine kielbasa drumstick cupim tenderloin chuck shank. Flank jowl leberkas turducken ham tongue\n+beef ribs shankle meatloaf drumstick pork t-bone frankfurter tri-tip.\n+```\n+\n+## Step 6: Run Krustlet as a service\n+\n+Create `krustlet.service` in `/etc/systemd/system/krustlet.service` on the VM.\n+\n+```text\n+[Unit]\n+Description=Krustlet, a kubelet implementation for running WASM\n+\n+[Service]\n+Restart=on-failure\n+RestartSec=5s\n+Environment=KUBECONFIG=/etc/krustlet/config/kubeconfig\n+Environment=KRUSTLET_NODE_IP=[[REPLACE-WITH-IP]]\n+Environment=KRUSTLET_NODE_NAME=krustlet\n+Environment=KRUSTLET_CERT_FILE=/etc/krustlet/config/krustlet.crt\n+Environment=KRUSTLET_PRIVATE_KEY_FILE=/etc/krustlet/config/krustlet.key\n+Environment=KRUSTLET_DATA_DIR=/etc/krustlet\n+Environment=RUST_LOG=wascc_provider=info,wasi_provider=info,main=info\n+ExecStart=/usr/local/bin/krustlet-wasi\n+User=root\n+Group=root\n+\n+[Install]\n+WantedBy=multi-user.target\n+```\n+\n+Ensure that the `krustlet.service` has the correct ownership and permissions\n+with:\n+\n+```console\n+$ sudo chown root:root /etc/systemd/system/krustlet.service\n+$ sudo chmod 644 /etc/systemd/system/krustlet.service\n+```\n+\n+Then:\n+\n+```console\n+$ sudo mkdir -p /etc/krustlet/config && sudo chown -R root:root /etc/krustlet\n+$ sudo mv {krustlet.*,kubeconfig} /etc/krustlet/config && chmod 600 /etc/krustlet/*\n+```\n+\n+Once you have done that, run the following commands to make sure the unit is\n+configured to start on boot:\n+\n+```console\n+$ sudo systemctl enable krustlet && sudo systemctl start krustlet\n+```\n+\n+You may confirm the status of the service and review logs using:\n+\n+```console\n+$ systemctl status krustlet.service\n+$ journalctl --unit=krustlet.service --follow\n+\n+## Delete the VM\n+\n+When you are finished with the VM, you can delete it by typing:\n+\n+```console\n+$ doctl compute droplet delete ${INSTANCE}\n+```\n+\n+When you are finished with the cluster, you can delete it by typing:\n+\n+```console\n+$ doctl kubernetes cluster delete ${CLUSTER}\n+```\n+\n+`doctl kubernetes cluster delete` will also attempt to delete the cluster's\n+configuration (cluster, context, user) from the default Kubernetes config file\n+(Linux: `${HOME}/.kube/config`). You will neeed to set a new default context.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "docs/howto/kubernetes-on-do.md", "diff": "+# Managed Kubernetes on DigitalOcean\n+\n+[Managed Kubernetes on DigitalOcean](https://www.digitalocean.com/products/kubernetes/)\n+is an inexpensive, professionally-managed Kubernetes service.\n+\n+You'll need a DigitalOcean account and will need to have provided a payment method.\n+DigitalOcean offers a [free trial](https://try.digitalocean.com/freetrialoffer).\n+\n+## Prerequisites\n+\n+You may provision Kubernetes clusters and Droplets (DigitalOcean VMs) using the\n+[console](https://cloud.digitalocean.com) but DigitalOcean's CLI [doctl](https://github.com/digitalocean/doctl)\n+is comprehensive and recommended. The instructions that follow assume you've\n+installed doctl and [authenticated](https://github.com/digitalocean/doctl#authenticating-with-digitalocean)\n+to a DigitalOcean account.\n+\n+> **NOTE** If you use the doctl [Snap](https://github.com/digitalocean/doctl#snap-supported-os),\n+> consider connecting [kubectl](https://github.com/digitalocean/doctl#use-with-kubectl)\n+> and [ssh-keys](https://github.com/digitalocean/doctl#using-doctl-compute-ssh) to\n+> simplify the experience.\n+\n+## Create Managed Kubernetes cluster\n+\n+`doctl kubernetes` includes commands for provisioning clusters. In order to create\n+a cluster, you'll need to provide a Kubernetes version, a node instance size, a\n+DigitalOcean region and the number of nodes. Values for some of the values may\n+be obtained using the following `doctl kubernetes` commands:\n+\n+```console\n+$ doctl kubernetes options versions\n+$ doctl kubernetes options regions\n+$ doctl kubernetes options sizes\n+```\n+\n+> **NOTE** DigitalOcean uses unique identifiers called \"slugs\". \"slugs\" are the\n+> identifiers used as values in many of `doctl`'s commands, e.g. `1.19.3-do.3` is\n+> the slug for Kubernetes version `1.19.3`.\n+\n+If you'd prefer to use some reasonable default values, you may use the following\n+command to create a cluster in DigitalOcean's San Francisco region, using\n+Kubernetes `1.19.3` with a single worker node (the master node is free). The\n+worker node has 1 vCPU and 2GB RAM (currently $10/month).\n+\n+```console\n+$ CLUSTER=[[YOUR-CLUSTER-NAME]]\n+$ VERSION=\"1.19.3-do.3\"\n+$ SIZE=\"s-1vcpu-2gb\"\n+$ REGION=\"sfo3\"\n+\n+$ doctl kubernetes cluster create ${CLUSTER} \\\n+ --auto-upgrade \\\n+ --count 1 \\\n+ --version ${VERSION} \\\n+ --size ${SIZE} \\\n+ --region ${REGION}\n+```\n+\n+`doctl kubernetes cluster create` should automatically update your default\n+Kubernetes config (Linux: `${HOME}/.kube/config`). `doctl kubernetes cluster delete`\n+will remove this entry when it deletes the cluster. You should be able to:\n+\n+```console\n+$ kubectl get nodes\n+NAME STATUS ROLES AGE VERSION\n+${CLUSTER}-default-pool-39yh5 Ready <none> 1m v1.19.3\n+```\n+\n+## Delete Managed Kubernetes cluster\n+\n+When you are finished with the cluster, you may delete it with:\n+\n+```console\n+$ doctl kubernetes cluster delete ${CLUSTER}\n+```\n+\n+> **NOTE** This command should (!) delete the cluster's entries (context, user)\n+> from the default Kubernetes config (Linux `{$HOME}/.kube/config) too.\n+\n+To confirm that the cluster has been deleted, if you try listing the clusters,\n+the cluster you deleted should no longer be present:\n+\n+```console\n+$ doctl kubernetes cluster list\n+```\n+\n+Or you may confirm that the Droplets have been deleted:\n+\n+```console\n+$ doctl compute droplet list\n+```\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
DigitalOcean documentation
350,426
27.01.2021 20:34:54
21,600
5f815e7165609572ef4fee648b29fd3bd6125fde
Fix UI and doc tests
[ { "change_type": "MODIFY", "old_path": "Cargo.lock", "new_path": "Cargo.lock", "diff": "@@ -2031,7 +2031,7 @@ dependencies = [\nname = \"krator-derive\"\nversion = \"0.1.0\"\ndependencies = [\n- \"kubelet\",\n+ \"krator\",\n\"quote 1.0.7\",\n\"syn 1.0.42\",\n]\n" }, { "change_type": "MODIFY", "old_path": "crates/krator-derive/Cargo.toml", "new_path": "crates/krator-derive/Cargo.toml", "diff": "@@ -32,7 +32,7 @@ quote = \"1.0\"\n[dev-dependencies]\n# For docs builds\n-kubelet = { path = \"../kubelet\", version = \"0.5\", default-features = false }\n+krator = { path = \"../krator\", version = \"0.1\", default-features = false }\n[package.metadata.docs.rs]\nfeatures = [\"docs\"]\n" }, { "change_type": "MODIFY", "old_path": "docs/howto/krustlet-on-do.md", "new_path": "docs/howto/krustlet-on-do.md", "diff": "@@ -143,7 +143,6 @@ $ KUBECONFIG=${PWD}/kubeconfig ${PWD}/krustlet-wasi \\\n```\n> **NOTE** You'll need the `IP` of the Droplet from step 1.\n-\n> **NOTE** To increase the level of debugging, you may prefix the command with\n`RUST_LOG=info` or `RUST_LOG=debug`.\n" }, { "change_type": "MODIFY", "old_path": "tests/ui/state/next_must_be_state.rs", "new_path": "tests/ui/state/next_must_be_state.rs", "diff": "// Test that State<T> can only transition to State<T>\n// edition:2018\nextern crate async_trait;\n+extern crate krator;\nextern crate kubelet;\nextern crate anyhow;\n" }, { "change_type": "MODIFY", "old_path": "tests/ui/state/next_must_be_state.stderr", "new_path": "tests/ui/state/next_must_be_state.stderr", "diff": "-error[E0277]: the trait bound `NotState: kubelet::state::State<PodState>` is not satisfied\n- --> $DIR/next_must_be_state.rs:37:9\n+error[E0277]: the trait bound `NotState: krator::State<PodState>` is not satisfied\n+ --> $DIR/next_must_be_state.rs:38:9\n|\n-37 | Transition::next(self, NotState)\n- | ^^^^^^^^^^^^^^^^ the trait `kubelet::state::State<PodState>` is not implemented for `NotState`\n+38 | Transition::next(self, NotState)\n+ | ^^^^^^^^^^^^^^^^ the trait `krator::State<PodState>` is not implemented for `NotState`\n|\n- = note: required by `kubelet::state::Transition::<S>::next`\n+ = note: required by `krator::Transition::<S>::next`\nerror: aborting due to previous error\n" }, { "change_type": "MODIFY", "old_path": "tests/ui/state/require_same_object_state.rs", "new_path": "tests/ui/state/require_same_object_state.rs", "diff": "// edition:2018\nextern crate async_trait;\nextern crate kubelet;\n+extern crate krator;\nextern crate anyhow;\nuse kubelet::pod::Pod;\n" }, { "change_type": "MODIFY", "old_path": "tests/ui/state/require_same_object_state.stderr", "new_path": "tests/ui/state/require_same_object_state.stderr", "diff": "-error[E0277]: the trait bound `OtherState: kubelet::state::State<PodState>` is not satisfied\n- --> $DIR/require_same_object_state.rs:47:9\n+error[E0277]: the trait bound `OtherState: krator::State<PodState>` is not satisfied\n+ --> $DIR/require_same_object_state.rs:48:9\n|\n-47 | Transition::next(self, OtherState)\n- | ^^^^^^^^^^^^^^^^ the trait `kubelet::state::State<PodState>` is not implemented for `OtherState`\n+48 | Transition::next(self, OtherState)\n+ | ^^^^^^^^^^^^^^^^ the trait `krator::State<PodState>` is not implemented for `OtherState`\n|\n= help: the following implementations were found:\n- <OtherState as kubelet::state::State<OtherPodState>>\n- = note: required by `kubelet::state::Transition::<S>::next`\n+ <OtherState as krator::State<OtherPodState>>\n+ = note: required by `krator::Transition::<S>::next`\nerror: aborting due to previous error\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix UI and doc tests
350,408
04.02.2021 07:14:48
-3,600
a8b2ccf17d595f5208d232d112002c09dda476c5
added information on the image pull secret
[ { "change_type": "MODIFY", "old_path": "docs/intro/tutorial03.md", "new_path": "docs/intro/tutorial03.md", "diff": "@@ -25,6 +25,8 @@ spec:\ncontainers:\n- name: krustlet-tutorial\nimage: mycontainerregistry007.azurecr.io/krustlet-tutorial:v1.0.0\n+ imagePullSecrets:\n+ - name: <acr-secret>\ntolerations:\n- key: \"kubernetes.io/arch\"\noperator: \"Equal\"\n@@ -43,6 +45,7 @@ Let's break this file down:\n- `metadata.name`: what is the name of our workload?\n- `spec.containers[0].name`: what should I name this module?\n- `spec.containers[0].image`: where can I find the module?\n+- `spec.imagePullSecrets[0].name`: which name has the image pull secret?\n- `spec.tolerations`: what kind of node am I allowed to run on?\nTo deploy this workload to Kubernetes, we use `kubectl`.\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
added information on the image pull secret
350,408
05.02.2021 07:00:02
-3,600
9dd2d0ddad4faabcfc4d853e44ff15bb502312ff
Fixed typo and wrapping long lines
[ { "change_type": "MODIFY", "old_path": "docs/intro/tutorial02.md", "new_path": "docs/intro/tutorial02.md", "diff": "@@ -133,13 +133,20 @@ $ wasm-to-oci push demo.wasm mycontainerregistry007.azurecr.io/krustlet-tutorial\n## Create a container registry pull secret\n-Unless your container registry is enabled with anonymous access, you need to authenticate krustlet to pull images from it. At the moment, there is no flag in the Azure portal to make a registry public, but you can [create a support ticket](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-faq#how-do-i-enable-anonymous-pull-access) to have it enabled manually.\n+Unless your container registry is enabled with anonymous access, you need to\n+authenticate krustlet to pull images from it. At the moment, there is no flag in the\n+Azure portal to make a registry public, but you can [create a support ticket](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-faq#how-do-i-enable-anonymous-pull-access)\n+to have it enabled manually.\n-Without public access to the container registry, you need to create a _Kubernetes pull secret_. The steps below for Azure are [extracted from the Azure documentation](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-kubernetes), and repeated herefor convenience.\n+Without public access to the container registry, you need to create a _Kubernetes\n+pull secret_. The steps below for Azure are\n+[extracted from the Azure documentation](https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-kubernetes),\n+and repeated here for convenience.\n### Create a service principal and assign a role in Azure\n-Below is a bash script that will create a service principal for the registry. Replace `<container-registry-name>` with `mycontainerregistry007`.\n+Below is a bash script that will create a service principal for pulling images for\n+the registry. Replace `<container-registry-name>` with `mycontainerregistry007`.\n```bash\n#!/bin/bash\n@@ -168,7 +175,12 @@ echo \"Service principal ID: $SP_APP_ID\"\necho \"Service principal password: $SP_PASSWD\"\n```\n-If you do not want to create a service principal in Azure, you can also use the registry `Admin` username and password which gives full access to the registry and is not generally recommended. This is not enabled by default. Go to the Azure portal and the settings for your registry and the `Access keys` menu. There you can enable `Admin` access and use the associated username instead of hte service principal ID and the password when creating the pull secret below.\n+If you do not want to create a service principal in Azure, you can also use the\n+registry `Admin` username and password which gives full access to the registry and\n+is not generally recommended. This is not enabled by default. Go to the Azure portal\n+and the settings for your registry and the `Access keys` menu. There you can enable\n+`Admin` access and use the associated username instead of hte service principal ID\n+and the password when creating the pull secret below.\n### Use the service principal\n@@ -182,7 +194,10 @@ kubectl create secret docker-registry <acr-secret-name> \\\n--docker-password=<service-principal-password>\n```\n-where `<acr-secret-name>` is a name you give this secret, `<service-principal-ID>`and `<service-principal-password>` are taken from the output of the bash script above. The `--namespace` can be omitted if you are using the default Kubernetes namespace.\n+where `<acr-secret-name>` is a name you give this secret, `<service-principal-ID>`\n+and `<service-principal-password>` are taken from the output of the bash script\n+above. The `--namespace` can be omitted if you are using the default Kubernetes\n+namespace.\n## Next steps\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fixed typo and wrapping long lines
350,432
28.02.2021 14:54:50
-3,600
e3e567d277ed65bd1fd511288499490421682a3e
Output CRD in moose example * Output CRD in moose example It's handy to have this in the example program as it might not be apparent, that the CRD can be auto-generated if you are not familiar with the kube library yet. * Remove unused dependency:
[ { "change_type": "MODIFY", "old_path": "crates/krator/Cargo.toml", "new_path": "crates/krator/Cargo.toml", "diff": "@@ -49,7 +49,9 @@ warp = { version = \"0.2\", optional = true, features = [\"tls\"] }\njson-patch = { version = \"0.2\", optional = true }\n[dev-dependencies]\n-kube-derive = \"0.42\"\n+kube-derive = \"0.48\"\n+schemars = \"0.8.0\"\n+serde_yaml = \"0.8\"\nchrono = \"0.4\"\nenv_logger = \"0.8\"\nrand = \"0.8\"\n" }, { "change_type": "MODIFY", "old_path": "crates/krator/examples/moose.rs", "new_path": "crates/krator/examples/moose.rs", "diff": "@@ -7,12 +7,13 @@ use kube_derive::CustomResource;\nuse log::info;\nuse rand::seq::IteratorRandom;\nuse rand::Rng;\n+use schemars::JsonSchema;\nuse serde::{Deserialize, Serialize};\nuse std::collections::{HashMap, HashSet};\nuse std::sync::Arc;\nuse tokio::sync::RwLock;\n-#[derive(CustomResource, Debug, Serialize, Deserialize, Clone, Default)]\n+#[derive(CustomResource, Debug, Serialize, Deserialize, Clone, Default, JsonSchema)]\n#[kube(\ngroup = \"animals.com\",\nversion = \"v1\",\n@@ -27,14 +28,14 @@ struct MooseSpec {\nantlers: bool,\n}\n-#[derive(Debug, Serialize, Deserialize, Clone)]\n+#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)]\nenum MoosePhase {\nAsleep,\nHungry,\nRoaming,\n}\n-#[derive(Debug, Serialize, Deserialize, Clone)]\n+#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)]\nstruct MooseStatus {\nphase: Option<MoosePhase>,\nmessage: Option<String>,\n@@ -337,6 +338,8 @@ async fn main() -> anyhow::Result<()> {\nlet kubeconfig = kube::Config::infer().await?;\nlet tracker = MooseTracker::new();\n+ info!(\"crd:\\n{}\", serde_yaml::to_string(&Moose::crd()).unwrap());\n+\n// Only track mooses in Glacier NP\nlet params = ListParams::default().labels(\"nps.gov/park=glacier\");\n" }, { "change_type": "MODIFY", "old_path": "crates/wasi-provider/Cargo.toml", "new_path": "crates/wasi-provider/Cargo.toml", "diff": "@@ -38,7 +38,6 @@ wat = \"1.0\"\ntokio = { version = \"1.0\", features = [\"fs\", \"macros\", \"io-util\", \"sync\"] }\nchrono = { version = \"0.4\", features = [\"serde\"] }\nfutures = \"0.3\"\n-k8s-openapi = { version = \"0.9\", default-features = false, features = [\"v1_18\"] }\n[dev-dependencies]\noci-distribution = { path = \"../oci-distribution\", version = \"0.5\" }\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Output CRD in moose example (#522) * Output CRD in moose example It's handy to have this in the example program as it might not be apparent, that the CRD can be auto-generated if you are not familiar with the kube library yet. * Remove unused dependency:
350,440
22.03.2021 16:22:32
-3,600
1b1273a7cd0b511790682ce01a7e68ba6389ac20
Pod conditions added to the StatusBuilder in kubelet
[ { "change_type": "MODIFY", "old_path": "crates/kubelet/src/pod/status.rs", "new_path": "crates/kubelet/src/pod/status.rs", "diff": "@@ -4,6 +4,7 @@ use super::Pod;\nuse crate::container::make_initial_container_status;\nuse k8s_openapi::api::core::v1::ContainerStatus as KubeContainerStatus;\nuse k8s_openapi::api::core::v1::Pod as KubePod;\n+use k8s_openapi::api::core::v1::PodCondition as KubePodCondition;\nuse k8s_openapi::api::core::v1::PodStatus as KubePodStatus;\nuse krator::{Manifest, ObjectStatus};\nuse kube::api::PatchParams;\n@@ -191,6 +192,12 @@ impl StatusBuilder {\nself\n}\n+ /// Set Pod conditions.\n+ pub fn conditions(mut self, conditions: Vec<KubePodCondition>) -> StatusBuilder {\n+ self.0.conditions = Some(conditions);\n+ self\n+ }\n+\n/// Finalize Pod Status from builder.\npub fn build(self) -> Status {\nStatus(self.0)\n@@ -249,6 +256,10 @@ impl ObjectStatus for Status {\nstatus.insert(\"initContainerStatuses\".to_string(), serde_json::json!(s));\n};\n+ if let Some(s) = self.0.conditions.clone() {\n+ status.insert(\"conditions\".to_string(), serde_json::json!(s));\n+ };\n+\nserde_json::json!(\n{\n\"metadata\": {\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Pod conditions added to the StatusBuilder in kubelet
350,450
24.03.2021 20:54:44
-28,800
090e2efb1db897afcc75ee15ee26692a6c78a057
fix(bootstrap): Handle busybox date
[ { "change_type": "MODIFY", "old_path": "docs/howto/assets/bootstrap.sh", "new_path": "docs/howto/assets/bootstrap.sh", "diff": "@@ -6,9 +6,10 @@ export LC_ALL=C\ntoken_id=\"$(</dev/urandom tr -dc a-z0-9 | head -c \"${1:-6}\";echo;)\"\ntoken_secret=\"$(< /dev/urandom tr -dc a-z0-9 | head -c \"${1:-16}\";echo;)\"\n-# support gnu and BSD date command\n+# support gnu, BSD and busybox date command\nexpiration=$(date -u \"+%Y-%m-%dT%H:%M:%SZ\" --date \"1 hour\" 2>/dev/null ||\n- date -v+1H -u \"+%Y-%m-%dT%H:%M:%SZ\" 2>/dev/null)\n+ date -v+1H -u \"+%Y-%m-%dT%H:%M:%SZ\" 2>/dev/null ||\n+ date -u \"+%Y-%m-%dT%H:%M:%SZ\" -D \"%s\" -d \"$(( `date +%s`+3600 ))\")\ncat <<EOF | kubectl apply -f -\napiVersion: v1\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
fix(bootstrap): Handle busybox date
350,432
18.05.2021 01:10:21
-7,200
3885934819d6499fc9bd5d96e10600da167f5b1a
Fix clippy warnings closes
[ { "change_type": "MODIFY", "old_path": "crates/krator-derive/src/admission.rs", "new_path": "crates/krator-derive/src/admission.rs", "diff": "@@ -25,7 +25,7 @@ where\n{\nlet input: proc_macro2::TokenStream = input.into();\nlet token_stream = match syn::parse2(input)\n- .and_then(|input| <T as CustomDerive>::parse(input))\n+ .and_then(<T as CustomDerive>::parse)\n.and_then(<T as CustomDerive>::emit)\n{\nOk(token_stream) => token_stream,\n@@ -71,7 +71,7 @@ impl Parse for Features {\n\"service\" => features.service = true,\n\"admission_webhook_config\" => features.admission_webhook_config = true,\n_ => {\n- panic!(format!(\"WebhookAdmission attribute {} can only contain one or more of the following values: service, secret, admission_webhook_config\", ATTRIBUTE_NAME))\n+ panic!(\"WebhookAdmission attribute {} can only contain one or more of the following values: service, secret, admission_webhook_config\", ATTRIBUTE_NAME)\n}\n};\n}\n@@ -81,19 +81,14 @@ impl Parse for Features {\n}\n}\n-fn get_features(attrs: &Vec<Attribute>) -> Features {\n- attrs\n- .into_iter()\n- .fold(Features::default(), |mut acc, ref attr| {\n- match parse_as_features_attr(attr) {\n- Some(features) => {\n+fn get_features(attrs: &[Attribute]) -> Features {\n+ attrs.iter().fold(Features::default(), |mut acc, ref attr| {\n+ if let Some(features) = parse_as_features_attr(attr) {\nacc.secret |= features.secret;\nacc.service |= features.service;\nacc.admission_webhook_config |= features.admission_webhook_config;\nacc.attributes_found |= features.attributes_found;\n}\n- None => {}\n- };\nacc\n})\n}\n@@ -130,7 +125,7 @@ impl CustomDerive for CustomResourceInfos {\n// Outputs\nlet mut cri = CustomResourceInfos {\nname: \"\".to_string(),\n- features: features,\n+ features,\n};\nlet mut name: Option<String> = None;\n@@ -153,23 +148,17 @@ impl CustomDerive for CustomResourceInfos {\n};\nfor meta in metas {\n- match &meta {\n- // key-value arguments\n- syn::NestedMeta::Meta(syn::Meta::NameValue(meta)) => {\n+ if let syn::NestedMeta::Meta(syn::Meta::NameValue(meta)) = &meta {\nif meta.path.is_ident(\"kind\") {\nif let syn::Lit::Str(lit) = &meta.lit {\nname = Some(lit.value());\nbreak;\n} else {\n- return Err(\n- r#\"#[kube(kind = \"...\")] expects a string literal value\"#,\n- )\n+ return Err(r#\"#[kube(kind = \"...\")] expects a string literal value\"#)\n.spanning(meta);\n}\n}\n- } // unknown arg\n- _ => (),\n- };\n+ }\n}\n}\ncri.name = name.expect(\"kube macro must have property name set\");\n@@ -380,6 +369,6 @@ impl CustomDerive for CustomResourceInfos {\n}\n};\n- Ok(token_stream.into())\n+ Ok(token_stream)\n}\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Fix clippy warnings (#604) closes #599
350,410
12.05.2021 14:39:28
-7,200
991132d319d9ca8fc7d990ed0706c59534a4eede
oci-distribution: add IMAGE_DOCKER_LAYER_GZIP_MEDIA_TYPE Needed to be able to download Docker images.
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/manifest.rs", "new_path": "crates/oci-distribution/src/manifest.rs", "diff": "@@ -15,6 +15,9 @@ pub const IMAGE_DOCKER_CONFIG_MEDIA_TYPE: &str = \"application/vnd.docker.contain\npub const IMAGE_LAYER_MEDIA_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar\";\n/// The mediatype for a layer that is gzipped.\npub const IMAGE_LAYER_GZIP_MEDIA_TYPE: &str = \"application/vnd.oci.image.layer.v1.tar+gzip\";\n+/// The mediatype that Docker uses for a layer that is gzipped.\n+pub const IMAGE_DOCKER_LAYER_GZIP_MEDIA_TYPE: &str =\n+ \"application/vnd.docker.image.rootfs.diff.tar.gzip\";\n/// The mediatype for a layer that is nondistributable.\npub const IMAGE_LAYER_NONDISTRIBUTABLE_MEDIA_TYPE: &str =\n\"application/vnd.oci.image.layer.nondistributable.v1.tar\";\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
oci-distribution: add IMAGE_DOCKER_LAYER_GZIP_MEDIA_TYPE Needed to be able to download Docker images.
350,430
18.05.2021 13:44:31
21,600
5111aaab7bef7c2e61e78a12bb860851e2255478
Expose pull_manifest publically on Registry Client.
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -184,7 +184,7 @@ impl Client {\nself.auth(image, auth, &RegistryOperation::Pull).await?;\n}\n- let (manifest, digest) = self.pull_manifest(image).await?;\n+ let (manifest, digest) = self._pull_manifest(image).await?;\nself.validate_layers(&manifest, accepted_media_types)\n.await?;\n@@ -402,11 +402,27 @@ impl Client {\nOk(())\n}\n+ /// Pull a manifest from the remote OCI Distribution service.\n+ ///\n+ /// The client will check if it's already been authenticated and if\n+ /// not will attempt to do.\n+ pub async fn pull_manifest(\n+ &mut self,\n+ image: &Reference,\n+ auth: &RegistryAuth,\n+ ) -> anyhow::Result<(OciManifest, String)> {\n+ if !self.tokens.contains_key(image.registry()) {\n+ self.auth(image, auth, &RegistryOperation::Pull).await?;\n+ }\n+\n+ self._pull_manifest(image).await\n+ }\n+\n/// Pull a manifest from the remote OCI Distribution service.\n///\n/// If the connection has already gone through authentication, this will\n/// use the bearer token. Otherwise, this will attempt an anonymous pull.\n- async fn pull_manifest(&self, image: &Reference) -> anyhow::Result<(OciManifest, String)> {\n+ async fn _pull_manifest(&self, image: &Reference) -> anyhow::Result<(OciManifest, String)> {\nlet url = self.to_v2_manifest_url(image);\ndebug!(\"Pulling image manifest from {}\", url);\nlet request = self.client.get(&url);\n@@ -1189,12 +1205,12 @@ mod test {\n}\n#[tokio::test]\n- async fn test_pull_manifest() {\n+ async fn test_pull_manifest_private() {\nfor &image in TEST_IMAGES {\nlet reference = Reference::try_from(image).expect(\"failed to parse reference\");\n// Currently, pull_manifest does not perform Authz, so this will fail.\nlet c = Client::default();\n- c.pull_manifest(&reference)\n+ c._pull_manifest(&reference)\n.await\n.expect_err(\"pull manifest should fail\");\n@@ -1208,7 +1224,23 @@ mod test {\n.await\n.expect(\"authenticated\");\nlet (manifest, _) = c\n- .pull_manifest(&reference)\n+ ._pull_manifest(&reference)\n+ .await\n+ .expect(\"pull manifest should not fail\");\n+\n+ // The test on the manifest checks all fields. This is just a brief sanity check.\n+ assert_eq!(manifest.schema_version, 2);\n+ assert!(!manifest.layers.is_empty());\n+ }\n+ }\n+\n+ #[tokio::test]\n+ async fn test_pull_manifest_public() {\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n+ let mut c = Client::default();\n+ let (manifest, _) = c\n+ .pull_manifest(&reference, &RegistryAuth::Anonymous)\n.await\n.expect(\"pull manifest should not fail\");\n@@ -1264,7 +1296,7 @@ mod test {\n.await\n.expect(\"authenticated\");\nlet (manifest, _) = c\n- .pull_manifest(&reference)\n+ ._pull_manifest(&reference)\n.await\n.expect(\"failed to pull manifest\");\n@@ -1485,7 +1517,7 @@ mod test {\n.expect(\"authenticated\");\nlet (manifest, _digest) = c\n- .pull_manifest(&image)\n+ ._pull_manifest(&image)\n.await\n.expect(\"failed to pull manifest\");\n@@ -1537,7 +1569,7 @@ mod test {\n.expect(\"failed to pull pushed image\");\nlet (pulled_manifest, _digest) = c\n- .pull_manifest(&push_image)\n+ ._pull_manifest(&push_image)\n.await\n.expect(\"failed to pull pushed image manifest\");\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Expose pull_manifest publically on Registry Client.
350,430
18.05.2021 15:44:09
21,600
0b533e0e454cc0bcc5e4b15cfca1ccea524d213d
Add pull_manifest_and_config
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/client.rs", "new_path": "crates/oci-distribution/src/client.rs", "diff": "@@ -437,6 +437,8 @@ impl Client {\nlet digest = digest_header_value(&res)?;\nlet text = res.text().await?;\n+ println!(\"Manifest Response: {}\", text);\n+\nself.validate_image_manifest(&text).await?;\ndebug!(\"Parsing response as OciManifest: {}\", text);\n@@ -483,6 +485,36 @@ impl Client {\nOk(())\n}\n+ /// Pull a manifest and its config from the remote OCI Distribution service.\n+ ///\n+ /// The client will check if it's already been authenticated and if\n+ /// not will attempt to do.\n+ pub async fn pull_manifest_and_config(\n+ &mut self,\n+ image: &Reference,\n+ auth: &RegistryAuth,\n+ ) -> anyhow::Result<(OciManifest, String, String)> {\n+ if !self.tokens.contains_key(image.registry()) {\n+ self.auth(image, auth, &RegistryOperation::Pull).await?;\n+ }\n+\n+ self._pull_manifest_and_config(image).await\n+ }\n+\n+ async fn _pull_manifest_and_config(\n+ &mut self,\n+ image: &Reference,\n+ ) -> anyhow::Result<(OciManifest, String, String)> {\n+ let (manifest, digest) = self._pull_manifest(image).await?;\n+\n+ let mut out: Vec<u8> = Vec::new();\n+ debug!(\"Pulling config layer\");\n+ self.pull_layer(image, &manifest.config.digest, &mut out)\n+ .await?;\n+\n+ Ok((manifest, digest, String::from_utf8(out)?))\n+ }\n+\n/// Pull a single layer from an OCI registry.\n///\n/// This pulls the layer for a particular image that is identified by\n@@ -1250,6 +1282,23 @@ mod test {\n}\n}\n+ #[tokio::test]\n+ async fn pull_manifest_and_config_public() {\n+ for &image in TEST_IMAGES {\n+ let reference = Reference::try_from(image).expect(\"failed to parse reference\");\n+ let mut c = Client::default();\n+ let (manifest, _, config) = c\n+ .pull_manifest_and_config(&reference, &RegistryAuth::Anonymous)\n+ .await\n+ .expect(\"pull manifest and config should not fail\");\n+\n+ // The test on the manifest checks all fields. This is just a brief sanity check.\n+ assert_eq!(manifest.schema_version, 2);\n+ assert!(!manifest.layers.is_empty());\n+ assert!(!config.is_empty());\n+ }\n+ }\n+\n#[tokio::test]\nasync fn test_fetch_digest() {\nlet mut c = Client::default();\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Add pull_manifest_and_config
350,430
22.05.2021 22:42:27
21,600
fa10ea1a927f85cc86c557711b719a43d4742e3d
Expose ParseError
[ { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/lib.rs", "new_path": "crates/oci-distribution/src/lib.rs", "diff": "@@ -11,7 +11,7 @@ pub mod secrets;\n#[doc(inline)]\npub use client::Client;\n#[doc(inline)]\n-pub use reference::Reference;\n+pub use reference::{ParseError, Reference};\n#[macro_use]\nextern crate lazy_static;\n" }, { "change_type": "MODIFY", "old_path": "crates/oci-distribution/src/reference.rs", "new_path": "crates/oci-distribution/src/reference.rs", "diff": "@@ -8,15 +8,24 @@ use crate::regexp;\n/// NAME_TOTAL_LENGTH_MAX is the maximum total number of characters in a repository name.\nconst NAME_TOTAL_LENGTH_MAX: usize = 255;\n+/// Reasons that parsing a string as a Reference can fail.\n#[derive(Debug, PartialEq, Eq)]\npub enum ParseError {\n+ /// Invalid checksum digest format\nDigestInvalidFormat,\n+ /// Invalid checksum digest length\nDigestInvalidLength,\n+ /// Unsupported digest algorithm\nDigestUnsupported,\n+ /// Repository name must be lowercase\nNameContainsUppercase,\n+ /// Repository name must have at least one component\nNameEmpty,\n+ /// Repository name must not be more than NAME_TOTAL_LENGTH_MAX characters\nNameTooLong,\n+ /// Invalid reference format\nReferenceInvalidFormat,\n+ /// Invalid tag format\nTagInvalidFormat,\n}\n" } ]
Rust
Apache License 2.0
krustlet/krustlet
Expose ParseError