[
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  # Maintain dependencies for GitHub Actions\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"monthly\"\n"
  },
  {
    "path": ".github/workflows/call-docker-build-api.yaml",
    "content": "name: Build API\n# template source: https://github.com/dockersamples/.github/blob/main/templates/call-docker-build.yaml\n\non:\n  # we want pull requests so we can build(test) but not push to image registry\n  push:\n    branches:\n      - 'main'\n    # only build when important files change\n    paths:\n      - 'api/**'\n      - '.github/workflows/call-docker-build-api.yaml'\n  pull_request:\n    branches:\n      - 'main'\n    # only build when important files change\n    paths:\n      - 'api/**'\n      - '.github/workflows/call-docker-build-api.yaml'\n\njobs:\n  call-docker-build:\n\n    name: API Call Docker Build\n\n    uses: dockersamples/.github/.github/workflows/reusable-docker-build.yaml@main\n\n    permissions:\n      contents: read\n      packages: write # needed to push docker image to ghcr.io\n      pull-requests: write # needed to create and update comments in PRs\n    \n    secrets:\n\n      # Only needed if with:dockerhub-enable is true below\n      dockerhub-username: ${{ secrets.DOCKERHUB_USERNAME }}\n\n      # Only needed if with:dockerhub-enable is true below\n      dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }}\n\n    with:\n      \n      ### REQUIRED\n      ### ENABLE ONE OR BOTH REGISTRIES\n      ### tell docker where to push.\n      ### NOTE if Docker Hub is set to true, you must set secrets above and also add account/repo/tags below\n      dockerhub-enable: true\n      ghcr-enable: true\n\n      ### REQUIRED \n      ### A list of the account/repo names for docker build. List should match what's enabled above\n      ### defaults to:\n      image-names: |\n        ghcr.io/dockersamples/wordsmith-api\n        dockersamples/wordsmith-api\n        dockersamples/k8s-wordsmith-api\n      \n      ### REQUIRED set rules for tagging images, based on special action syntax:\n      ### https://github.com/docker/metadata-action#tags-input\n      ### defaults to:\n      tag-rules: |\n        type=raw,value=latest,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}\n        type=ref,event=pr\n      \n      ### path to where docker should copy files into image\n      ### defaults to root of repository (.)\n      context: api\n      \n      ### Dockerfile alternate name. Default is Dockerfile (relative to context path)\n      # file: Containerfile\n\n      ### build stage to target, defaults to empty, which builds to last stage in Dockerfile\n      # target:\n      \n      ### platforms to build for, defaults to linux/amd64\n      ### other options: linux/amd64,linux/arm64,linux/arm/v7\n      platforms: linux/amd64,linux/arm64\n      \n      ### Create a PR comment with image tags and labels\n      ### defaults to false\n      # comment-enable: false\n"
  },
  {
    "path": ".github/workflows/call-docker-build-web.yaml",
    "content": "name: Build Web\n# template source: https://github.com/dockersamples/.github/blob/main/templates/call-docker-build.yaml\n\non:\n  # we want pull requests so we can build(test) but not push to image registry\n  push:\n    branches:\n      - 'main'\n    # only build when important files change\n    paths:\n      - 'web/**'\n      - '.github/workflows/call-docker-build-web.yaml'\n  pull_request:\n    branches:\n      - 'main'\n    # only build when important files change\n    paths:\n      - 'web/**'\n      - '.github/workflows/call-docker-build-web.yaml'\n\njobs:\n  call-docker-build:\n\n    name: Web Call Docker Build\n\n    uses: dockersamples/.github/.github/workflows/reusable-docker-build.yaml@main\n\n    permissions:\n      contents: read\n      packages: write # needed to push docker image to ghcr.io\n      pull-requests: write # needed to create and update comments in PRs\n    \n    secrets:\n\n      # Only needed if with:dockerhub-enable is true below\n      dockerhub-username: ${{ secrets.DOCKERHUB_USERNAME }}\n\n      # Only needed if with:dockerhub-enable is true below\n      dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }}\n\n    with:\n      \n      ### REQUIRED\n      ### ENABLE ONE OR BOTH REGISTRIES\n      ### tell docker where to push.\n      ### NOTE if Docker Hub is set to true, you must set secrets above and also add account/repo/tags below\n      dockerhub-enable: true\n      ghcr-enable: true\n\n      ### REQUIRED \n      ### A list of the account/repo names for docker build. List should match what's enabled above\n      ### defaults to:\n      image-names: |\n        ghcr.io/dockersamples/wordsmith-web\n        dockersamples/wordsmith-web\n        dockersamples/k8s-wordsmith-web\n      \n      ### REQUIRED set rules for tagging images, based on special action syntax:\n      ### https://github.com/docker/metadata-action#tags-input\n      ### defaults to:\n      tag-rules: |\n        type=raw,value=latest,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }}\n        type=ref,event=pr\n      \n      ### path to where docker should copy files into image\n      ### defaults to root of repository (.)\n      context: web\n      \n      ### Dockerfile alternate name. Default is Dockerfile (relative to context path)\n      # file: Containerfile\n\n      ### build stage to target, defaults to empty, which builds to last stage in Dockerfile\n      # target:\n      \n      ### platforms to build for, defaults to linux/amd64\n      ### other options: linux/amd64,linux/arm64,linux/arm/v7\n      platforms: linux/amd64,linux/arm64,linux/arm/v7\n      \n      ### Create a PR comment with image tags and labels\n      ### defaults to false\n      # comment-enable: false\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Wordsmith App\n\nWordsmith is the demo project originally shown at DockerCon EU 2017 and 2018.\n\nThe demo app runs across three containers:\n\n- **[api](api/Dockerfile)** - a Java REST API which serves words read from the database\n- **[web](web/Dockerfile)** - a Go web application that calls the API and builds words into sentences\n- **db** - a Postgres database that stores words\n\n## Architecture\n\n![Architecture diagram](architecture.excalidraw.png)\n\n## Build and run in Docker Compose\n\nThe only requirement to build and run the app from source is Docker. Clone this repo and use Docker Compose to build all the images. You can use the new V2 Compose with `docker compose` or the classic `docker-compose` CLI:\n\n```shell\ndocker compose up --build\n```\n\nOr you can pull pre-built images from Docker Hub using `docker compose pull`.\n\n\n## Deploy using Kubernetes manifests\n\nYou can deploy the same app to Kubernetes using the [Kustomize configuration](./kustomization.yaml). It will define all of the necessary Deployment and Service objects and a ConfigMap to provide the database schema.\n\nApply the manifest using `kubectl` while at the root of the project:\n\n```shell\nkubectl apply -k .\n```\n\nOnce the pods are running, browse to http://localhost:8080 and you will see the site.\n\nDocker Desktop includes Kubernetes and the [kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) command line, so you can work directly with the cluster. Check the services are up, and you should see output like this:\n\n```text\nkubectl get svc\nNAME         TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE\ndb           ClusterIP      None             <none>        55555/TCP        2m\nkubernetes   ClusterIP      10.96.0.1        <none>        443/TCP          38d\nweb          LoadBalancer   10.107.215.211   <pending>     8080:30220/TCP   2m\nwords        ClusterIP      None             <none>        55555/TCP        2m\n```\n\nCheck the pods are running and you should see one pod each for the database and web components and five pods for the words API:\n\n```text\nkubectl get pods\nNAME                   READY     STATUS    RESTARTS   AGE\ndb-8678676c79-h2d99    1/1       Running   0          1m\nweb-5d6bfbbd8b-6zbl8   1/1       Running   0          1m\napi-858f6678-6c8kk     1/1       Running   0          1m\napi-858f6678-7bqbv     1/1       Running   0          1m\napi-858f6678-fjdws     1/1       Running   0          1m\napi-858f6678-rrr8c     1/1       Running   0          1m\napi-858f6678-x9zqh     1/1       Running   0          1m\n```\n"
  },
  {
    "path": "api/.dockerignore",
    "content": ".idea\ntarget\n*.iml\n"
  },
  {
    "path": "api/Dockerfile",
    "content": "# Build stage\nFROM --platform=${BUILDPLATFORM} maven:3-amazoncorretto-20 as build\nWORKDIR /usr/local/app\nCOPY pom.xml .\nRUN mvn verify -DskipTests --fail-never\nCOPY src ./src\nRUN mvn verify\n\n# Run stage\nFROM --platform=${TARGETPLATFORM} amazoncorretto:20\nWORKDIR /usr/local/app\nCOPY --from=build /usr/local/app/target .\nENTRYPOINT [\"java\", \"-Xmx8m\", \"-Xms8m\", \"-jar\", \"/usr/local/app/words.jar\"]\nEXPOSE 8080\n"
  },
  {
    "path": "api/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n\n    <groupId>codestory</groupId>\n    <artifactId>words</artifactId>\n    <version>1.0-SNAPSHOT</version>\n\n    <properties>\n        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n        <maven.compiler.source>17</maven.compiler.source>\n        <maven.compiler.target>17</maven.compiler.target>\n    </properties>\n\n    <build>\n        <finalName>words</finalName>\n\n        <pluginManagement>\n            <plugins>\n                <plugin>\n                    <artifactId>maven-clean-plugin</artifactId>\n                    <version>3.2.0</version>\n                </plugin>\n                <plugin>\n                    <artifactId>maven-compiler-plugin</artifactId>\n                    <version>3.10.1</version>\n                </plugin>\n                <plugin>\n                    <artifactId>maven-deploy-plugin</artifactId>\n                    <version>3.0.0</version>\n                </plugin>\n                <plugin>\n                    <artifactId>maven-install-plugin</artifactId>\n                    <version>3.1.0</version>\n                </plugin>\n                <plugin>\n                    <artifactId>maven-resources-plugin</artifactId>\n                    <version>3.3.0</version>\n                </plugin>\n                <plugin>\n                    <artifactId>maven-surefire-plugin</artifactId>\n                    <version>2.19.1</version>\n                </plugin>\n            </plugins>\n        </pluginManagement>\n\n        <plugins>\n            <plugin>\n                <artifactId>maven-dependency-plugin</artifactId>\n                <version>3.4.0</version>\n                <executions>\n                    <execution>\n                        <id>copy-dependencies</id>\n                        <phase>package</phase>\n                        <goals>\n                            <goal>copy-dependencies</goal>\n                        </goals>\n                    </execution>\n                </executions>\n            </plugin>\n            <plugin>\n                <artifactId>maven-jar-plugin</artifactId>\n                <version>3.3.0</version>\n                <configuration>\n                    <archive>\n                        <manifest>\n                            <addClasspath>true</addClasspath>\n                            <classpathPrefix>dependency</classpathPrefix>\n                            <mainClass>Main</mainClass>\n                        </manifest>\n                    </archive>\n                </configuration>\n            </plugin>\n        </plugins>\n    </build>\n\n    <dependencies>\n        <dependency>\n            <groupId>com.google.guava</groupId>\n            <artifactId>guava</artifactId>\n            <version>32.0.1-jre</version>\n        </dependency>\n        <dependency>\n            <groupId>org.postgresql</groupId>\n            <artifactId>postgresql</artifactId>\n            <version>42.7.2</version>\n        </dependency>\n    </dependencies>\n</project>\n"
  },
  {
    "path": "api/src/main/java/Main.java",
    "content": "import com.google.common.base.Charsets;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.sun.net.httpserver.HttpHandler;\nimport com.sun.net.httpserver.HttpServer;\n\nimport java.io.OutputStream;\nimport java.net.InetSocketAddress;\nimport java.sql.*;\nimport java.util.NoSuchElementException;\n\npublic class Main {\n    public static void main(String[] args) throws Exception {\n        Class.forName(\"org.postgresql.Driver\");\n\n        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);\n        server.createContext(\"/noun\", handler(() -> randomWord(\"nouns\")));\n        server.createContext(\"/verb\", handler(() -> randomWord(\"verbs\")));\n        server.createContext(\"/adjective\", handler(() -> randomWord(\"adjectives\")));\n        server.start();\n    }\n\n    private static String randomWord(String table) {\n        try (Connection connection = DriverManager.getConnection(\"jdbc:postgresql://db:5432/postgres\", \"postgres\", \"\")) {\n            try (Statement statement = connection.createStatement()) {\n                try (ResultSet set = statement.executeQuery(\"SELECT word FROM \" + table + \" ORDER BY random() LIMIT 1\")) {\n                    while (set.next()) {\n                        return set.getString(1);\n                    }\n                }\n            }\n        } catch (SQLException e) {\n            e.printStackTrace();\n        }\n\n        throw new NoSuchElementException(table);\n    }\n\n    private static HttpHandler handler(Supplier<String> word) {\n        return t -> {\n            String response = \"{\\\"word\\\":\\\"\" + word.get() + \"\\\"}\";\n            byte[] bytes = response.getBytes(Charsets.UTF_8);\n\n            System.out.println(response);\n            \n            t.getResponseHeaders().add(\"content-type\", \"application/json; charset=utf-8\");\n            t.getResponseHeaders().add(\"cache-control\", \"private, no-cache, no-store, must-revalidate, max-age=0\");\n            t.getResponseHeaders().add(\"pragma\", \"no-cache\");\n\n            t.sendResponseHeaders(200, bytes.length);\n\n            try (OutputStream os = t.getResponseBody()) {\n                os.write(bytes);\n            }\n        };\n    }\n}\n"
  },
  {
    "path": "db/words.sql",
    "content": "CREATE TABLE nouns (word TEXT NOT NULL);\nCREATE TABLE verbs (word TEXT NOT NULL);\nCREATE TABLE adjectives (word TEXT NOT NULL);\n\nINSERT INTO nouns(word) VALUES\n  ('cloud'),\n  ('elephant'),\n  ('gø language'),\n  ('laptøp'),\n  ('cøntainer'),\n  ('micrø-service'),\n  ('turtle'),\n  ('whale'),\n  ('gøpher'),\n  ('møby døck'),\n  ('server'),\n  ('bicycle'),\n  ('viking'),\n  ('mermaid'),\n  ('fjørd'),\n  ('legø'),\n  ('flødebolle'),\n  ('smørrebrød');\n\nINSERT INTO verbs(word) VALUES\n  ('will drink'),\n  ('smashes'),\n  ('smøkes'),\n  ('eats'),\n  ('walks tøwards'),\n  ('løves'),\n  ('helps'),\n  ('pushes'),\n  ('debugs'),\n  ('invites'),\n  ('hides'),\n  ('will ship');\n\nINSERT INTO adjectives(word) VALUES\n  ('the exquisite'),\n  ('a pink'),\n  ('the røtten'),\n  ('a red'),\n  ('the serverless'),\n  ('a brøken'),\n  ('a shiny'),\n  ('the pretty'),\n  ('the impressive'),\n  ('an awesøme'),\n  ('the famøus'),\n  ('a gigantic'),\n  ('the gløriøus'),\n  ('the nørdic'),\n  ('the welcøming'),\n  ('the deliciøus');\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '3.9'\n# we'll keep the version for now to work in Compose and Swarm\n\nservices:\n  db:\n    image: postgres:10.0-alpine\n    volumes:\n      - ./db:/docker-entrypoint-initdb.d/\n\n  api:\n    build: api\n    image: dockersamples/wordsmith-api\n    deploy:\n      replicas: 5\n\n  web:\n    build: web\n    image: dockersamples/wordsmith-web\n    ports:\n     - \"8080:80\""
  },
  {
    "path": "k8s-manifests/api.yaml",
    "content": "apiVersion: v1\nkind: Service\nmetadata:\n  name: api\n  labels:\n    app: api\nspec:\n  ports:\n    - port: 8080\n      targetPort: 8080\n      name: api\n  selector:\n    app: api\n  clusterIP: None\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: api\n  labels:\n    app: api\nspec:\n  replicas: 5\n  selector:\n    matchLabels:\n      app: api\n  template:\n    metadata:\n      labels:\n        app: api\n    spec:\n      containers:\n        - name: api\n          image: dockersamples/wordsmith-api\n          ports:\n            - containerPort: 8080\n              name: api"
  },
  {
    "path": "k8s-manifests/db.yaml",
    "content": "apiVersion: v1\nkind: Service\nmetadata:\n  name: db\n  labels:\n    app: db\nspec:\n  ports:\n    - port: 5432\n      targetPort: 5432\n      name: db\n  selector:\n    app: db\n  clusterIP: None\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: db\n  labels:\n    app: db\nspec:\n  selector:\n    matchLabels:\n      app: db\n  template:\n    metadata:\n      labels:\n        app: db\n    spec:\n      containers:\n        - name: db\n          image: postgres:10.0-alpine\n          ports:\n            - containerPort: 5432\n              name: db\n          volumeMounts:\n            - name: db-schema\n              mountPath: /docker-entrypoint-initdb.d\n      volumes:\n        - name: db-schema\n          configMap:\n            name: db-schema"
  },
  {
    "path": "k8s-manifests/web.yaml",
    "content": "apiVersion: v1\nkind: Service\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  ports:\n    - port: 8080\n      targetPort: 80\n      name: web\n  selector:\n    app: web\n  type: LoadBalancer\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: web\n  labels:\n    app: web\nspec:\n  selector:\n    matchLabels:\n      app: web\n  template:\n    metadata:\n      labels:\n        app: web\n    spec:\n      containers:\n        - name: web\n          image: dockersamples/wordsmith-web\n          ports:\n            - containerPort: 80\n              name: web\n"
  },
  {
    "path": "kustomization.yaml",
    "content": "resources:\n  - k8s-manifests/api.yaml\n  - k8s-manifests/db.yaml\n  - k8s-manifests/web.yaml\nconfigMapGenerator:\n  - name: db-schema\n    files:\n      - ./db/words.sql\ngeneratorOptions:\n  disableNameSuffixHash: true"
  },
  {
    "path": "web/Dockerfile",
    "content": "# BUILD\n# use the build platforms matching arch rather than target arch\nFROM --platform=$BUILDPLATFORM golang:alpine as builder\nWORKDIR /usr/local/app\nARG TARGETARCH\n\nCOPY dispatcher.go .\n\n# build for the target arch not the build platform host arch\nRUN GOOS=linux GOARCH=$TARGETARCH go build dispatcher.go\n\n# RUN\n# defaults to using the target arch image\nFROM alpine:latest\nWORKDIR /usr/local/app\n\nCOPY --from=builder /usr/local/app/dispatcher ./\nCOPY static ./static/\n\nEXPOSE 80\nCMD [\"/usr/local/app/dispatcher\"]\n"
  },
  {
    "path": "web/dispatcher.go",
    "content": "package main\n\nimport (\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"log\"\n\t\"math/rand\"\n\t\"net\"\n\t\"net/http\"\n\t\"time\"\n)\n\nfunc main() {\n\trand.Seed(time.Now().UnixNano())\n\n\tfwd := &forwarder{\"api\", 8080}\n\thttp.Handle(\"/words/\", http.StripPrefix(\"/words\", fwd))\n\thttp.Handle(\"/\", http.FileServer(http.Dir(\"static\")))\n\n\tfmt.Println(\"Listening on port 80\")\n\thttp.ListenAndServe(\":80\", nil)\n}\n\ntype forwarder struct {\n\thost string\n\tport int\n}\n\nfunc (f *forwarder) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\taddrs, err := net.LookupHost(f.host)\n\tif err != nil {\n\t\tlog.Println(\"Error\", err)\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tlog.Printf(\"%s %d available ips: %v\", r.URL.Path, len(addrs), addrs)\n\tip := addrs[rand.Intn(len(addrs))]\n\tlog.Printf(\"%s I choose %s\", r.URL.Path, ip)\n\n\turl := fmt.Sprintf(\"http://%s:%d%s\", ip, f.port, r.URL.Path)\n\tlog.Printf(\"%s Calling %s\", r.URL.Path, url)\n\n\tif err = copy(url, ip, w); err != nil {\n\t\tlog.Println(\"Error\", err)\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n}\n\nfunc copy(url, ip string, w http.ResponseWriter) error {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor header, values := range resp.Header {\n\t\tfor _, value := range values {\n\t\t\tw.Header().Add(header, value)\n\t\t}\n\t}\n\tw.Header().Set(\"source\", ip)\n\n\tbuf, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = w.Write(buf)\n\treturn err\n}\n"
  },
  {
    "path": "web/static/app.js",
    "content": "\"use strict\";\n\nvar lab = angular.module('lab', []);\n\nlab.controller('LabCtrl', function ($scope, $http, $timeout) {\n  $scope.noun1 = \"\";\n  $scope.noun2 = \"\";\n  $scope.adjective1 = \"\";\n  $scope.adjective2 = \"\";\n  $scope.verb = \"\";\n\n  getWord($http, $timeout, '/words/noun?n=1', function(resp1) {\n    $scope.noun1 = word(resp1);\n  });\n\n  getWord($http, $timeout, '/words/adjective?a=1', function(resp) {\n    var adj = word(resp);\n    adj.word = adj.word.charAt(0).toUpperCase() + adj.word.substr(1)\n    $scope.adjective1 = adj;\n  });\n\n  getWord($http, $timeout, '/words/verb', function(resp) {\n    $scope.verb = word(resp);\n  });\n\n  getWord($http, $timeout, '/words/noun?n=2', function(resp2) {\n    $scope.noun2 = word(resp2);\n  });\n\n  getWord($http, $timeout, '/words/adjective?n=2', function(resp) {\n    $scope.adjective2 = word(resp);\n  });\n});\n\nfunction getWord($http, $timeout, url, callback) {\n  $http.get(url).then(callback, function(resp) {\n    $timeout(function() {\n      console.log(\"Retry: \" + url);\n      getWord($http, $timeout, url, callback);\n    }, 500);\n  });\n}\n\nfunction word(resp) {\n  return {\n    word: resp.data.word,\n    hostname: resp.headers()[\"source\"]\n  };\n}\n"
  },
  {
    "path": "web/static/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" ng-app=\"lab\">\n<head>\n  <meta charset=\"utf-8\">\n  <title>dockercon EU 18</title>\n  <link rel=\"stylesheet\" href=\"style.css\">\n</head>\n\n<body>\n  <div class=\"logo\"><img src=\"images/logo.svg\" style=\"width:50%\"/></div>\n\n<div class=\"sentence\" ng-controller=\"LabCtrl\">\n  <div class=\"line line1 slide-in\">\n  <span class=\"result adjective slide-in\">\n    <span class=\"word slide-in\" ng-bind=\"adjective1.word\"></span>\n    <span class=\"hostname\" ng-bind=\"adjective1.hostname\"></span>\n  </span>\n  <span class=\"result noun slide-in\">\n    <span class=\"word\" ng-bind=\"noun1.word\"></span>\n    <span class=\"hostname\" ng-bind=\"noun1.hostname\"></span>\n  </span>\n  </div>\n  <div class=\"line line2 slide-in\">\n  <span class=\"result verb slide-in\">\n    <span class=\"word\" ng-bind=\"verb.word\"></span>\n    <span class=\"hostname\" ng-bind=\"verb.hostname\"></span>\n  </span>\n  </div>\n  <div class=\"line line3 slide-in\">\n  <span class=\"result adjective slide-in\">\n    <span class=\"word\" ng-bind=\"adjective2.word\"></span>\n    <span class=\"hostname\" ng-bind=\"adjective2.hostname\"></span>\n  </span>\n  <span class=\"result noun slide-in\">\n    <span class=\"word\" ng-bind=\"noun2.word\"></span>\n    <span class=\"hostname\" ng-bind=\"noun2.hostname\"></span>\n  </span>\n  </div>\n</div>\n\n<div class=\"footer\"><img src=\"images/homes.png\" /></div>\n</body>\n\n<script src=\"angular.min.js\"></script>\n<script src=\"app.js\"></script>\n</html>\n"
  },
  {
    "path": "web/static/style.css",
    "content": "/* latin-ext */\n@font-face {\n  font-family: 'Raleway';\n  font-style: normal;\n  font-weight: 400;\n  src: local('Raleway'), local('Raleway-Regular'), url('fonts/font1.woff2') format('woff2');\n  unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;\n}\n/* latin */\n@font-face {\n  font-family: 'Raleway';\n  font-style: normal;\n  font-weight: 400;\n  src: local('Raleway'), local('Raleway-Regular'), url('fonts/font2.woff2') format('woff2');\n  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;\n}\n\nbody {\n\ttext-align: center;\n\tmargin: 0;\n\tpadding: 0;\n\tbackground-color: #001f5b;\n}\n\n.logo {\n\tmargin-top: 30px;\n}\n\n.footer {\n\tposition: absolute;\n\tbottom: 0;\n\twidth: 100%;\n\tz-index: -1;\n\topacity: 0.5;\n}\n\n.footer img {\n\tmax-width: 100%;\n\tvertical-align: middle;\n}\n\n.sentence {\n\tmargin: 70px auto 0 auto;\n}\n\n.line {\n\tmargin-bottom: 30px;\n\ttransform: translateX(-100%) rotate(-20deg);\n}\n\n.slide-in {\n    animation: slide-in .5s forwards ease-in;\n}\n\n.line3.slide-in {\n    animation: slide-in 1s forwards ease-in;\n}\n\n.line2.slide-in {\n    animation: slide-in 1.2s forwards ease-in;\n}\n\n@keyframes slide-in {\n  100% {\n\t\ttransform: translateX(0%);\n\t}\n}\n\n.result {\n\tposition: relative;\n\tdisplay: inline-block;\n\tpadding: 0 20px;\n\tmargin: 0 10px;\n\tcolor: white;\n\theight: 175px;\n\twidth: 330px;\n}\n\n.result .word {\n\tdisplay: inline-block;\n\tfont-family: 'Raleway', sans-serif;\n\tfont-size: 45px;\n\tcolor: white;\n\tline-height: 155px;\n\theight: 175px;\n\tvertical-align: middle;\n\tmargin-top: 20px;\n}\n\n.result .hostname {\n\tposition: absolute;\n\twidth: 100%;\n\tleft: 0;\n\tbottom: 8px;\n\tfont-size: 0.8em;\n\theight: 14px;\n}\n\n.noun {\n\tbackground-image: url('images/lego_blue.png') !important;\n}\n\n.verb {\n\tbackground-image: url('images/lego_yellow.png') !important;\n}\n\n.adjective {\n\tbackground-image: url('images/lego_light_blue.png') !important;\n}\n"
  }
]