{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# S1 lab notebook — inventory and teardown check\n",
    "\n",
    "This notebook is the machine-checkable half of the S1 evidence. It reads the four\n",
    "JSON files you saved during the lab, verifies the Droplet's identity and the\n",
    "firewall rules, proves the teardown left nothing behind, and records the run's\n",
    "cost against the $0.10 ceiling. It writes `inventory.json`.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "โน้ตบุ๊กนี้เป็นหลักฐานที่ตรวจสอบได้ด้วยเครื่องของแล็บ S1 อ่านไฟล์ JSON สี่ไฟล์ที่บันทึกระหว่างแล็บ ตรวจชื่อและคุณสมบัติของ Droplet กฎไฟร์วอลล์ ยืนยันว่าการรื้อทรัพยากรไม่เหลืออะไร และคำนวณค่าใช้จ่ายเทียบเพดาน 0.10 ดอลลาร์ จากนั้นเขียนไฟล์ inventory.json\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "这个 notebook 是 S1 实验室可用机器核验的证据。它读取你在实验期间保存的四个 JSON 文件，检查 Droplet 的名称和属性以及防火墙规则，确认资源拆除后没有留下任何东西，并把成本与 0.10 美元的上限比较，然后写出 inventory.json。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Setup\n",
    "\n",
    "The notebook uses the Python 3.14 standard library only. The two switches below\n",
    "are the only settings: `USE_EXAMPLE` loads the reference run that ships with the\n",
    "course instead of your own evidence, and `STUDENT_ID` is the id you used in\n",
    "the resource names. Export `USE_EXAMPLE=1` before starting Jupyter, or change\n",
    "the value to `True`, to check the shipped reference run on a fresh kit; leave\n",
    "it unset for your submission, whose student path fails until your own four\n",
    "JSON files exist in `data/`.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "โน้ตบุ๊กใช้ไลบรารีมาตรฐานของ Python 3.14 เท่านั้น สวิตช์สองตัวคือ USE_EXAMPLE สำหรับโหลดหลักฐานตัวอย่างที่มากับรายวิชา และ STUDENT_ID คือรหัสที่ใช้ตั้งชื่อทรัพยากร หากต้องการตรวจการติดตั้งบนคิทใหม่ให้กำหนด USE_EXAMPLE=1 ก่อนเริ่ม Jupyter หรือแก้ค่าเป็น True ในการส่งงานให้ปล่อยว่างไว้ เพราะเส้นทางของผู้เรียนจะไม่ผ่านจนกว่าจะมีไฟล์ JSON สี่ไฟล์ของตนเองอยู่ใน data/\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "notebook 只使用 Python 3.14 的标准库。两个开关是：USE_EXAMPLE，用于加载随课程提供的示例证据；以及 STUDENT_ID，即用于命名资源的 id。若要在新 kit 上检查安装，请在启动 Jupyter 前设置 USE_EXAMPLE=1，或把值改为 True；提交作业时则留空，因为在你自己的四个 JSON 文件出现在 data/ 之前，学习者路径不会通过。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import sys\n",
    "from datetime import datetime, timezone\n",
    "from pathlib import Path\n",
    "\n",
    "print(\"Python\", sys.version.split()[0])\n",
    "assert sys.version_info >= (3, 11), \"Use Python 3.14 for the course kit\"\n",
    "\n",
    "USE_EXAMPLE = os.environ.get(\"USE_EXAMPLE\", \"\").lower() in (\"1\", \"true\", \"yes\")\n                             # export USE_EXAMPLE=1 to check the reference run\n",
    "STUDENT_ID = \"verify\"        # the <id> you used in the resource names\n",
    "CEILING_USD = 0.10\n",
    "HOURLY_USD = 0.00893        # s-1vcpu-1gb in SGP1, checked 2026-11-13\n",
    "print(\"example data\", USE_EXAMPLE)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Load the evidence\n",
    "\n",
    "The lab saves two snapshots before teardown and two after it. `droplet-before.json`\n",
    "and `firewall-before.json` record what existed while the Droplet ran; the `after`\n",
    "files prove what remains. The resolver tries `data/` first, then a Kaggle input\n",
    "folder, then `COURSE_DATA`, so the same notebook works locally and on Kaggle.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "แล็บบันทึกสถานะสองครั้งก่อนรื้อและสองครั้งหลังรื้อ ไฟล์ before คือทรัพยากรที่อยู่ในขณะแล็บทำงาน ไฟล์ after คือสิ่งที่เหลืออยู่ ตัวแก้เส้นทางจะลองหาใน data/ ก่อน จากนั้นโฟลเดอร์ Kaggle และตัวแปร COURSE_DATA ทำให้โน้ตบุ๊กใช้ได้ทั้งบนเครื่องและบน Kaggle\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "实验在拆除前保存两次状态，在拆除后保存两次状态。before 文件是在实验运行期间存在的资源，after 文件是仍然剩下的东西。路径解析器先尝试 data/，然后是 Kaggle 文件夹，再是 COURSE_DATA 环境变量，因此同一个 notebook 既能在本机运行，也能在 Kaggle 上运行。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def data_dir() -> Path:\n",
    "    candidates = [\n",
    "        Path(\"data\"),\n",
    "        Path(\"/kaggle/input/cloud-course-s1\"),\n",
    "        Path(os.environ.get(\"COURSE_DATA\", \"data\")),\n",
    "    ]\n",
    "    for candidate in candidates:\n",
    "        if candidate.is_dir():\n",
    "            return candidate\n",
    "    raise FileNotFoundError(\"Put the four JSON files in data/ or set COURSE_DATA\")\n",
    "\n",
    "\n",
    "DATA = data_dir()\n",
    "SOURCE = DATA / \"example\" if USE_EXAMPLE else DATA\n",
    "print(\"source\", SOURCE)\n",
    "\n",
    "def load(name):\n",
    "    with open(SOURCE / name, encoding=\"utf-8\") as handle:\n",
    "        return json.load(handle)\n",
    "\n",
    "droplets_before = load(\"droplet-before.json\")\n",
    "firewalls_before = load(\"firewall-before.json\")\n",
    "droplets_after = load(\"droplet-after.json\")\n",
    "firewalls_after = load(\"firewall-after.json\")\n",
    "if isinstance(firewalls_before, dict):\n",
    "    firewalls_before = [firewalls_before]\n",
    "\n",
    "def tagged(items):\n",
    "    return [item for item in items if \"week:1\" in (item.get(\"tags\") or [])]\n",
    "\n",
    "print(\"droplets before/after\", len(droplets_before), len(droplets_after))\n",
    "print(\"firewalls before/after\", len(firewalls_before), len(firewalls_after))\n",
    "assert len(tagged(droplets_before)) == 1, \"save droplet-before.json before teardown\"\n",
    "assert len(tagged(firewalls_before)) == 1, \"save firewall-before.json before teardown\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Check the Droplet\n",
    "\n",
    "The Droplet must be the one the lab asked for: the SGP1 region, the\n",
    "`s-1vcpu-1gb` size, the Rocky Linux 10 image, active, and carrying all three\n",
    "tags. A missing tag is not cosmetic — the `week:1` tag is what attaches the\n",
    "firewall.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "Droplet ต้องเป็นตัวที่แล็บกำหนด คือภูมิภาค sgp1 ขนาด s-1vcpu-1gb อิมเมจ Rocky Linux 10 สถานะ active และมีแท็กครบสามตัว แท็ก week:1 สำคัญเพราะเป็นตัวเชื่อมไฟร์วอลล์เข้ากับ Droplet\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "Droplet 必须是实验指定的那一个：区域 sgp1、规格 s-1vcpu-1gb、镜像 Rocky Linux 10、状态 active，并且带有全部三个标签。week:1 标签很重要，因为它是把防火墙挂接到 Droplet 上的连接。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "droplet = tagged(droplets_before)[0]\n",
    "print(droplet[\"name\"], droplet[\"region\"][\"slug\"], droplet[\"size\"][\"slug\"],\n",
    "      droplet[\"image\"][\"slug\"], droplet[\"status\"], droplet[\"tags\"])\n",
    "\n",
    "assert droplet[\"name\"] == f\"course-{STUDENT_ID}-s1\", \"Droplet name does not match STUDENT_ID\"\n",
    "assert droplet[\"region\"][\"slug\"] == \"sgp1\", \"the Droplet is not in SGP1\"\n",
    "assert droplet[\"size\"][\"slug\"] == \"s-1vcpu-1gb\", \"wrong Droplet size\"\n",
    "assert droplet[\"image\"][\"slug\"] == \"rockylinux-10-x64\", \"wrong image\"\n",
    "assert droplet[\"status\"] == \"active\", \"the Droplet was not active when saved\"\n",
    "assert {\"course:42-05-0112\", \"week:1\"} <= set(droplet[\"tags\"]), \"missing course or week tag\"\n",
    "assert any(tag.startswith(\"student:\") for tag in droplet[\"tags\"]), \"missing student tag\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Check the firewall\n",
    "\n",
    "The firewall is the session's guardrail, so its shape matters more than its name.\n",
    "Exactly one inbound rule, TCP 22, from one `/32` address — never `0.0.0.0/0`.\n",
    "Three outbound rules, one each for TCP, UDP and ICMP. The `week:1` tag is the\n",
    "attachment that makes the rule apply to the Droplet.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "ไฟร์วอลล์คือแนวป้องกันหลักของเซสชัน รูปแบบจึงสำคัญกว่าชื่อ ต้องมีกฎขาเข้าเพียงข้อเดียว TCP 22 จากที่อยู่ /32 เดียว ห้ามเป็น 0.0.0.0/0 และมีกฎขาออกสามข้อสำหรับ TCP UDP และ ICMP โดยผูกกับแท็ก week:1\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "防火墙是这节课的主要防线，因此它的形态比名称更重要。必须只有一条入站规则：TCP 22，来自单个 /32 地址，绝不能是 0.0.0.0/0；并且有三条出站规则，分别对应 TCP、UDP 和 ICMP，绑定到 week:1 标签。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "firewall = tagged(firewalls_before)[0]\n",
    "inbound = firewall.get(\"inbound_rules\") or []\n",
    "outbound = firewall.get(\"outbound_rules\") or []\n",
    "print(firewall[\"name\"], firewall[\"tags\"], \"inbound\", len(inbound), \"outbound\", len(outbound))\n",
    "\n",
    "assert len(inbound) == 1, \"the firewall must have exactly one inbound rule\"\n",
    "rule = inbound[0]\n",
    "assert rule[\"protocol\"] == \"tcp\" and str(rule.get(\"ports\")) == \"22\", \"inbound rule is not TCP 22\"\n",
    "addresses = rule.get(\"sources\", {}).get(\"addresses\") or []\n",
    "assert len(addresses) == 1, \"SSH must come from exactly one address\"\n",
    "assert addresses[0].endswith(\"/32\"), \"the SSH source must be a single host (/32)\"\n",
    "assert addresses[0] != \"0.0.0.0/0\", \"SSH is open to the internet\"\n",
    "assert len(outbound) == 3, \"expected three outbound rules\"\n",
    "assert {r[\"protocol\"] for r in outbound} == {\"tcp\", \"udp\", \"icmp\"}, \"outbound protocols are wrong\"\n",
    "assert \"week:1\" in (firewall.get(\"tags\") or []), \"the firewall is not attached by tag week:1\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Prove the teardown\n",
    "\n",
    "The proof is not a screenshot of a delete dialog; it is a list that no longer\n",
    "contains the resource. On a fresh account both `after` files are empty arrays.\n",
    "On a shared account they may contain someone else's resources, so the check is\n",
    "narrow: no `week:1` Droplet and no `week:1` firewall remain.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "หลักฐานการรื้อไม่ใช่ภาพหน้าจอยืนยันการลบ แต่คือรายการทรัพยากรที่ไม่มีของเราอยู่แล้ว บนบัญชีใหม่ไฟล์ after จะเป็นอาร์เรย์ว่าง บนบัญชีที่ใช้ร่วมกันอาจมีของผู้อื่น จึงตรวจเฉพาะว่าไม่มี Droplet หรือไฟร์วอลล์ที่ติดแท็ก week:1 เหลืออยู่\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "拆除的证据不是确认删除的截图，而是一份不再包含我们资源的清单。在新账号上，after 文件会是空数组；在共享账号上，其中可能有别人的资源，因此只检查不再剩下带有 week:1 标签的 Droplet 或防火墙。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "remaining_droplets = tagged(droplets_after)\n",
    "remaining_firewalls = tagged(firewalls_after)\n",
    "print(\"week:1 droplets remaining\", len(remaining_droplets))\n",
    "print(\"week:1 firewalls remaining\", len(remaining_firewalls))\n",
    "assert not remaining_droplets, \"a week:1 Droplet is still billing\"\n",
    "assert not remaining_firewalls, \"a week:1 firewall is still attached\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Cost against the ceiling\n",
    "\n",
    "The Droplet bills for the hours it existed, not the hours it worked. Enter the\n",
    "start and end time of your lab; the reference run writes `run-meta.json`, which\n",
    "the notebook prefers when present. The assertion fails if the run exceeds three\n",
    "hours or costs more than $0.10 — both are signs that something was left running.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "Droplet คิดค่าบริการตามชั่วโมงที่มีอยู่ ไม่ใช่ชั่วโมงที่ทำงาน ให้กรอกเวลาเริ่มและสิ้นสุดของแล็บ หรือใช้ไฟล์ run-meta.json ที่การรันอ้างอิงสร้างไว้ ข้อความยืนยันจะไม่ผ่านถ้าเกินสามชั่วโมงหรือเกิน 0.10 ดอลลาร์ ซึ่งบ่งชี้ว่ามีทรัพยากรถูกทิ้งไว้\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "Droplet 按它存在的时数计费，而不是按它工作的时数。请填入实验的开始和结束时间，或使用参考运行生成的 run-meta.json 文件。如果超过三小时或超过 0.10 美元，断言就不会通过，这表明有资源被遗留了下来。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "meta_path = SOURCE / \"run-meta.json\"\n",
    "if meta_path.exists():\n",
    "    meta = json.loads(meta_path.read_text(encoding=\"utf-8\"))\n",
    "    started = datetime.fromisoformat(meta[\"started_utc\"].replace(\"Z\", \"+00:00\"))\n",
    "    finished = datetime.fromisoformat(meta[\"finished_utc\"].replace(\"Z\", \"+00:00\"))\n",
    "else:\n",
    "    # Replace these values with your lab window, or export LAB_START and\n",
    "    # LAB_FINISH as ISO-8601 timestamps before starting Jupyter.\n",
    "    started = datetime.fromisoformat(\n",
    "        os.environ.get(\"LAB_START\", \"2026-11-13T10:00:00+00:00\"))\n",
    "    finished = datetime.fromisoformat(\n",
    "        os.environ.get(\"LAB_FINISH\", \"2026-11-13T12:00:00+00:00\"))\n",
    "\n",
    "hours = (finished - started).total_seconds() / 3600\n",
    "amount = hours * HOURLY_USD\n",
    "print(f\"{hours:.2f} h at ${HOURLY_USD}/h = ${amount:.4f}\")\n",
    "assert 0 < hours <= 3, \"the lab window is longer than three hours; check for a stray Droplet\"\n",
    "assert amount < CEILING_USD, f\"${amount:.4f} reaches the ${CEILING_USD:.2f} ceiling\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Write the inventory artifact\n",
    "\n",
    "`inventory.json` is the companion the instructor checks against your screenshots.\n",
    "It records which evidence source was read, so an example run is never mistaken\n",
    "for a finished lab.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "ไฟล์ inventory.json เป็นหลักฐานประกอบที่อาจารย์ใช้เทียบกับภาพหน้าจอ โดยบันทึกว่าใช้ข้อมูลจากแหล่งใด เพื่อไม่ให้การรันตัวอย่างถูกเข้าใจผิดว่าเป็นแล็บที่ทำเสร็จแล้ว\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "inventory.json 文件是教师用来与截图对照的辅助证据，它记录了使用了哪个来源的数据，以免把示例运行误认为已经完成的实验。\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "inventory = {\n",
    "    \"student\": STUDENT_ID,\n",
    "    \"data_source\": \"example\" if USE_EXAMPLE else \"student\",\n",
    "    \"droplet\": {\n",
    "        \"name\": droplet[\"name\"],\n",
    "        \"region\": droplet[\"region\"][\"slug\"],\n",
    "        \"size\": droplet[\"size\"][\"slug\"],\n",
    "        \"image\": droplet[\"image\"][\"slug\"],\n",
    "        \"status\": droplet[\"status\"],\n",
    "        \"tags\": droplet[\"tags\"],\n",
    "    },\n",
    "    \"firewall\": {\n",
    "        \"name\": firewall[\"name\"],\n",
    "        \"inbound\": [{\"protocol\": rule[\"protocol\"], \"ports\": rule[\"ports\"],\n",
    "                     \"addresses\": addresses}],\n",
    "        \"outbound\": [{\"protocol\": r[\"protocol\"], \"ports\": r.get(\"ports\"),\n",
    "                       \"addresses\": r.get(\"destinations\", {}).get(\"addresses\", [])}\n",
    "                      for r in outbound],\n",
    "        \"tags\": firewall[\"tags\"],\n",
    "    },\n",
    "    \"teardown\": {\n",
    "        \"droplets_remaining\": len(remaining_droplets),\n",
    "        \"firewalls_remaining\": len(remaining_firewalls),\n",
    "    },\n",
    "    \"cost\": {\n",
    "        \"hours\": round(hours, 2),\n",
    "        \"hourly_usd\": HOURLY_USD,\n",
    "        \"amount_usd\": round(amount, 4),\n",
    "        \"ceiling_usd\": CEILING_USD,\n",
    "    },\n",
    "}\n",
    "out_path = Path(\"inventory.json\")\n",
    "out_path.write_text(json.dumps(inventory, indent=2) + \"\\n\", encoding=\"utf-8\")\n",
    "print(out_path.resolve())\n",
    "assert json.loads(out_path.read_text(encoding=\"utf-8\"))[\"teardown\"][\"droplets_remaining\"] == 0\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Submit\n",
    "\n",
    "Attach `inventory.json`, the ten evidence items and the 150–250 word *what this\n",
    "proves* note in Classroom. The notebook's assertions are the completion gate, not\n",
    "the submission itself.\n",
    "\n",
    "## Verification\n",
    "\n",
    "**Mac (M1 Max, Python 3.14):** the reference run's JSON is checked with\n",
    "`USE_EXAMPLE = True` (or `USE_EXAMPLE=1` in the environment); the cost cell\n",
    "recomputes the measured run window. The student path fails until the four JSON\n",
    "files exist, which is the intended gate.\n",
    "T4/RTX: not applicable to S1.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
