diff --git a/.changeset/config.json b/.changeset/config.json index 02236339b9..c7c4f11e57 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -34,7 +34,6 @@ "@backstage/plugin-gitops-profiles", "@backstage/plugin-graphiql", "@backstage/plugin-graphql-backend", - "@backstage/plugin-identity-backend", "@backstage/plugin-jenkins", "@backstage/plugin-lighthouse", "@backstage/plugin-newrelic", diff --git a/.changeset/create-app-url-reader-update.md b/.changeset/create-app-url-reader-update.md new file mode 100644 index 0000000000..eb2e538b77 --- /dev/null +++ b/.changeset/create-app-url-reader-update.md @@ -0,0 +1,6 @@ +--- +'example-backend': patch +'@backstage/create-app': patch +--- + +Bump @backstage/catalog-backend and pass the now required UrlReader interface to the plugin diff --git a/.changeset/metal-fishes-learn.md b/.changeset/metal-fishes-learn.md new file mode 100644 index 0000000000..d22af83ca0 --- /dev/null +++ b/.changeset/metal-fishes-learn.md @@ -0,0 +1,5 @@ +--- +'@backstage/create-app': minor +--- + +The default mount point for backend plugins have been changed to /api. These changes are done in the backend package itself, so it is recommended that you sync up existing backend packages with this new pattern. diff --git a/.changeset/new-url-reader.md b/.changeset/new-url-reader.md new file mode 100644 index 0000000000..94758c5bc1 --- /dev/null +++ b/.changeset/new-url-reader.md @@ -0,0 +1,12 @@ +--- +'@backstage/backend-common': patch +--- + +Added new UrlReader interface for reading opaque data from URLs with different providers. + +This new URL reading system is intended as a replacement for the various integrations towards +external systems in the catalog, scaffolder, and techdocs. It is configured via a new top-level +config section called 'integrations'. + +Along with the UrlReader interface is a new UrlReaders class, which exposes static factory +methods for instantiating readers that can read from many different integrations simultaneously. diff --git a/.changeset/url-reader-processor.md b/.changeset/url-reader-processor.md new file mode 100644 index 0000000000..40fef3c106 --- /dev/null +++ b/.changeset/url-reader-processor.md @@ -0,0 +1,5 @@ +--- +'@backstage/plugin-catalog-backend': minor +--- + +The catalog backend UrlReaderProcessor now uses a UrlReader from @backstage/backend-common, which must now be supplied to the constructor. diff --git a/.codecov.yml b/.codecov.yml index d03ad99836..1b8e770b59 100644 --- a/.codecov.yml +++ b/.codecov.yml @@ -13,6 +13,8 @@ flags: core: paths: - packages/core/ + carryforward: true core-api: paths: - packages/core-api/ + carryforward: true diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index de0655cdbc..3df1031034 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,6 +6,8 @@ * @spotify/backstage-core /docs/features/techdocs @spotify/techdocs-core +/plugins/cost-insights @spotify/silver-lining +/plugins/cloudbuild @trivago/ebarrios /plugins/techdocs @spotify/techdocs-core /plugins/techdocs-backend @spotify/techdocs-core /packages/techdocs-cli @spotify/techdocs-core diff --git a/.github/styles/vocab.txt b/.github/styles/vocab.txt new file mode 100644 index 0000000000..21045f04dd --- /dev/null +++ b/.github/styles/vocab.txt @@ -0,0 +1,203 @@ +abc +Apdex +api +Api +apis +args +asciidoc +async +Avro +backrub +Balachandran +Bigtable +Blackbox +bool +boolean +Chai +changeset +changesets +Changesets +changset +chanwit +Chanwit +cisphobia +cissexist +classname +cli +cncf +codeblocks +Codecov +codehilite +Codehilite +codeowners +config +Config +configs +const +cookiecutter +css +dariddler +deadnaming +destructured +dev +devs +discoverability +Discoverability +dls +docgen +Dockerfile +Dockerize +dockerode +Docusaurus +eg +Ek +env +Env +eslint +facto +failover +Figma +Firekube +Fredrik +github +Github +Gitlab +graphql +graphviz +Hackathons +haproxy +heroku +Hostname +http +https +img +incentivised +inlinehilite +interop +javascript +Javascript +jq +js +json +jsx +Kaewkasi +Knex +kubectl +kubernetes +learnings +lerna +Lerna +magiclink +mailto +Malus +md +microsite +middleware +minikube +Minikube +misgendering +mkdocs +Mkdocs +monorepo +Monorepo +monorepos +msw +namespace +Namespaces +neuro +newrelic +nginx +Niklas +nohoist +nonces +npm +nvm +oauth +Oauth +Okta +Oldsberg +onboarding +Onboarding +pagerduty +Patrik +Phoen +plantuml +Pomaceous +postgres +pre +prebaked +preconfigured +Preprarer +Prerequisities +productional +Protobuf +proxying +Proxying +pygments +pymdownx +Raghunandan +rankdir +readme +Readme +Redash +repo +Repo +repos +rerender +rollbar +Rollbar +Rollup +Rosaceae +rst +rsync +ruleset +sam +scaffolded +scaffolder +Scaffolder +semlas +Serverless +Sinon +smartsymobls +sparklines +Spotifiers +spotify +Spotify +squidfunk +src +subkey +superfences +Superfences +talkdesk +Talkdesk +tasklist +techdocs +templated +templater +Templater +templaters +Templaters +Thauer +theres +toc +tolerations +Tolerations +toolsets +touchpoints +ui +upvote +url +utils +validators +Voi +Wealthsimple +Weaveworks +xyz +yaml +Zalando +Zhou +Billett +cloudbuild +Grafana +Iain +Snyk diff --git a/.github/workflows/chromatic-storybook-test.yml b/.github/workflows/chromatic-storybook-test.yml index 0bcaf400d0..bb14e1c38b 100644 --- a/.github/workflows/chromatic-storybook-test.yml +++ b/.github/workflows/chromatic-storybook-test.yml @@ -26,7 +26,7 @@ jobs: uses: actions/cache@v2 with: path: '**/node_modules' - key: ${{ runner.os }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} + key: ${{ runner.os }}-v${{ matrix.node-version }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} - name: find location of global yarn cache id: yarn-cache if: steps.cache-modules.outputs.cache-hit != 'true' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c8c92c57ff..65e092676d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: - node-version: [12.x] + node-version: [12.x, 14.x] env: CI: true @@ -37,7 +37,7 @@ jobs: path: '**/node_modules' # We use both yarn.lock and package.json as cache keys to ensure that # changes to local monorepo packages bust the cache. - key: ${{ runner.os }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} + key: ${{ runner.os }}-v${{ matrix.node-version }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} # If we get a cache hit for node_modules, there's no need to bring in the global # yarn cache or run yarn install, as all dependencies will be installed already. diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000000..2fafd3756d --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,71 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +name: 'CodeQL' + +on: + push: + branches: [master] + pull_request: + # The branches below must be a subset of the branches above + branches: [master] + schedule: + - cron: '0 8 * * 6' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + # Override automatic language detection by changing the below list + # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] + language: ['javascript'] + # Learn more... + # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + # We must fetch at least the immediate parents so that if this is + # a pull request then we can checkout the head. + fetch-depth: 2 + + # If this run was triggered by a pull request event, then checkout + # the head of the pull request instead of the merge commit. + - run: git checkout HEAD^2 + if: ${{ github.event_name == 'pull_request' }} + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/docs-quality-checker.yml b/.github/workflows/docs-quality-checker.yml new file mode 100644 index 0000000000..45cf1dafe3 --- /dev/null +++ b/.github/workflows/docs-quality-checker.yml @@ -0,0 +1,18 @@ +name: Check Markdown files quality + +on: + pull_request: + branches: [master] + paths: + - '**.md' + +jobs: + check-all-files: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: documentation quality check + uses: errata-ai/vale-action@v1.3.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/e2e-win.yml b/.github/workflows/e2e-win.yml index 5bab1b1299..c48d779962 100644 --- a/.github/workflows/e2e-win.yml +++ b/.github/workflows/e2e-win.yml @@ -17,7 +17,7 @@ jobs: strategy: matrix: os: [windows-latest] - node-version: [12.x] + node-version: [12.x, 14.x] env: CI: true @@ -31,6 +31,8 @@ jobs: uses: actions/setup-node@v1 with: node-version: ${{ matrix.node-version }} + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.0.1 - name: yarn install run: yarn install --frozen-lockfile diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 69bd8393c8..e280bf59a3 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -26,7 +26,7 @@ jobs: strategy: matrix: os: [ubuntu-latest] - node-version: [12.x] + node-version: [12.x, 14.x] env: CI: true @@ -47,7 +47,7 @@ jobs: uses: actions/cache@v2 with: path: '**/node_modules' - key: ${{ runner.os }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} + key: ${{ runner.os }}-v${{ matrix.node-version }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} - name: find location of global yarn cache id: yarn-cache if: steps.cache-modules.outputs.cache-hit != 'true' diff --git a/.github/workflows/master-win.yml b/.github/workflows/master-win.yml index 3f65cf9aec..c103583052 100644 --- a/.github/workflows/master-win.yml +++ b/.github/workflows/master-win.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: - node-version: [12.x] + node-version: [12.x, 14.x] env: CI: true diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index bebca7c6f9..f5029bf836 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -10,7 +10,7 @@ jobs: strategy: matrix: - node-version: [12.x] + node-version: [12.x, 14.x] env: CI: true @@ -30,7 +30,7 @@ jobs: uses: actions/cache@v2 with: path: '**/node_modules' - key: ${{ runner.os }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} + key: ${{ runner.os }}-v${{ matrix.node-version }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} - name: find location of global yarn cache id: yarn-cache if: steps.cache-modules.outputs.cache-hit != 'true' @@ -69,12 +69,14 @@ jobs: # Publishes current version of packages that are not already present in the registry - name: publish + if: matrix.node-version == '12.x' run: yarn lerna -- publish from-package --yes env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} # Tags the commit with the version in the core package if the tag doesn't exist - uses: Klemensas/action-autotag@1.2.3 + if: matrix.node-version == '12.x' with: GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' package_root: 'packages/core' diff --git a/.github/workflows/microsite-build-check.yml b/.github/workflows/microsite-build-check.yml index ff290b71e4..8a2fa99ed2 100644 --- a/.github/workflows/microsite-build-check.yml +++ b/.github/workflows/microsite-build-check.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: - node-version: [12.x] + node-version: [12.x, 14.x] env: CI: true @@ -33,6 +33,10 @@ jobs: run: yarn install --frozen-lockfile working-directory: microsite + - name: prettier + run: yarn prettier:check + working-directory: microsite + - name: build microsite run: yarn build working-directory: microsite diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000000..335bd80109 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,77 @@ +name: Nightly Snapshot Release + +on: + schedule: + - cron: '0 2 * * *' # run at 2 AM UTC + +jobs: + build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [14.x] + + env: + CI: true + NODE_OPTIONS: --max-old-space-size=4096 + + steps: + - uses: actions/checkout@v2 + + # Beginning of yarn setup, keep in sync between all workflows, see ci.yml + - name: use node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + registry-url: https://registry.npmjs.org/ # Needed for auth + - name: cache all node_modules + id: cache-modules + uses: actions/cache@v2 + with: + path: '**/node_modules' + key: ${{ runner.os }}-v${{ matrix.node-version }}-node_modules-${{ hashFiles('yarn.lock', '**/package.json') }} + - name: find location of global yarn cache + id: yarn-cache + if: steps.cache-modules.outputs.cache-hit != 'true' + run: echo "::set-output name=dir::$(yarn cache dir)" + - name: cache global yarn cache + uses: actions/cache@v2 + if: steps.cache-modules.outputs.cache-hit != 'true' + with: + path: ${{ steps.yarn-cache.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: yarn install + run: yarn install --frozen-lockfile + # End of yarn setup + + # No verification done here, only build & publish. If the master branch + # is broken we will see that from those builds, but we still want to push nightly + # builds since upgrading to them is a manual process anyway. + + - name: tsc + run: yarn tsc + - name: build + run: yarn build + + # Prepares a nightly release version of any package with pending changesets + - name: prepare nightly release + run: yarn changeset version --snapshot nightly + + # Publishes the nightly release to NPM, by using tag we make sure the release is + # not flagged as the latest release, which means that people will not get this + # version of the package unless requested explicitly + - name: publish nightly release + run: yarn changeset publish --tag nightly + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Discord notification + if: ${{ failure() }} + uses: Ilshidur/action-discord@0.2.0 + env: + DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }} + with: + args: 'Nightly build failed https://github.com/{{GITHUB_REPOSITORY}}/actions/runs/{{GITHUB_RUN_ID}}' diff --git a/.github/workflows/scaffolder.yml b/.github/workflows/scaffolder.yml deleted file mode 100644 index bbfd52009d..0000000000 --- a/.github/workflows/scaffolder.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Scaffolder - -on: - pull_request: - paths: - - '.github/workflows/scaffolder.yml' - - './plugins/scaffolder-backend/scripts' - push: - branches: [master] -jobs: - build: - runs-on: ${{ matrix.os }} - - strategy: - matrix: - os: [ubuntu-latest] - python-version: [3.7] - - name: Build Container - steps: - - uses: actions/checkout@v2 - # Build Docker Image - - name: Build and push Docker images - uses: docker/build-push-action@v1.1.0 - with: - path: plugins/scaffolder-backend/scripts - dockerfile: plugins/scaffolder-backend/scripts/Cookiecutter.dockerfile - registry: docker.pkg.github.com - repository: ${{ github.repository }}/cookiecutter - username: ${{ github.actor }} - password: ${{ github.token }} - tag_with_ref: true - push: true diff --git a/.prettierignore b/.prettierignore index 9e75b74eee..4b1acbb594 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,6 +1,6 @@ .yarn dist -microsite/build +microsite coverage *.hbs templates diff --git a/.vale.ini b/.vale.ini new file mode 100644 index 0000000000..fd1ea53b0d --- /dev/null +++ b/.vale.ini @@ -0,0 +1,4 @@ +StylesPath = .github/styles + +[*.md] +BasedOnStyles = Vale diff --git a/CHANGELOG.md b/CHANGELOG.md index 25360f3e1e..bf2638cfe9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,30 @@ If you encounter issues while upgrading to a newer version, don't hesitate to re > Collect changes for the next release below +### Backend (example-backend, or backends created with @backstage/create-app) + +- The default mount point for backend plugins have been changed to `/api`. These changes are done in the backend package itself, so it is recommended that you sync up existing backend packages with this new pattern. [#2562](https://github.com/spotify/backstage/pull/2562) +- A service discovery mechanism for backend plugins has been added, and is now a requirement for several backend plugins. See [packages/backend/src/index.ts](./packages/backend/src/index.ts) for how to set it up using `SingleHostDiscovery` from `@backstage/backend-common`. Note that the default base path for plugins is set to `/api` to that change, but it can be set to use the old behavior via the `basePath` option. [#2600](https://github.com/spotify/backstage/pull/2600) + +### @backstage/auth-backend + +- The default mount path of backend plugins was changed to `/api/:pluginId`, and as part of that it was needed to enable configuration of the base path of the auth backend, so that it can construct redirect URLs correctly. Note that you will also need to reconfigure any allowed redirect URLs to include `/api` if you switch to the new recommended pattern. [#2562](https://github.com/spotify/backstage/pull/2562) +- The auth backend now requires an implementation of `PluginEndpointDiscovery` from `@backstage/backend-common` to be passed in as `discovery`. See the changes to `@backstage/backend`. + +### @backstage/proxy-backend + +- The proxy backend now requires an implementation of `PluginEndpointDiscovery` from `@backstage/backend-common` to be passed in as `discovery`. See the changes to `@backstage/backend`. + +### @backstage/techdocs-backend + +- The TechDocs backend now requires an implementation of `PluginEndpointDiscovery` from `@backstage/backend-common` to be passed in as `discovery`. See the changes to `@backstage/backend`. + +### @backstage/plugin-identity-backend + +- This plugin was removed, remove it from your backend if it's there. [#2616](https://github.com/spotify/backstage/pull/2616) + +## v0.1.1-alpha.23 + ### @backstage/core - Renamed `SessionStateApi` to `SessionApi` and `logout` to `signOut`. Custom implementations of the `SingInPage` app-component will need to rename their `logout` function. The different auth provider items for the `UserSettingsMenu` have been consolidated into a single `ProviderSettingsItem`, meaning you need to replace existing usages of `OAuthProviderSettings` and `OIDCProviderSettings`. [#2555](https://github.com/spotify/backstage/pull/2555). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a6f7e5e5e1..85834076d4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,10 +28,14 @@ What kind of plugins should/could be created? Some inspiration from the 120+ plu ## Suggesting a plugin -If you start developing a plugin that you aim to release as open source, we suggest that you create a new [new Issue](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). This helps the community know what plugins are in development. +If you start developing a plugin that you aim to release as open source, we suggest that you create a [new Issue](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). This helps the community know what plugins are in development. You can also use this process if you have an idea for a good plugin but you hope that someone else will pick up the work. +## Adding Non-code Contributions + +Since there is such a large landscape of possible development, build, and deployment environments, we welcome community contributions in these areas in the [`/contrib`](https://github.com/spotify/backstage/tree/master/contrib) folder of the project. This is an excellent place to put things that help out the community at large, but which may not fit within the scope of the core product to support natively. Here, you will find Helm charts, alternative Docker images, and much more. + ## Write Documentation The current documentation is very limited. Help us make the `/docs` folder come alive. @@ -72,6 +76,8 @@ If you're contributing to the backend or CLI tooling, be mindful of cross-platfo Also be sure to skim through our [ADRs](https://github.com/spotify/backstage/tree/master/docs/architecture-decisions) to see if they cover what you're working on. In particular [ADR006: Avoid React.FC and React.SFC](https://github.com/spotify/backstage/blob/master/docs/architecture-decisions/adr006-avoid-react-fc.md) is one to look out for. +If there are any updates in `markdown` file please make sure to run `yarn run lint:docs`. Though it is checked on `lint-staged`. It is required to install [vale](https://docs.errata.ai/vale/install) separately and make sure it is accessed by global command. + # Creating Changesets We use [changesets](https://github.com/atlassian/changesets) to help us prepare releases. It helps us make sure that every package affected by a change gets a proper version number and an entry in its `CHANGELOG.md`. To make the process of generating releases easy. it helps when contributors include changesets with their pull requests. diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index be77f0d4de..1aebbeb0eb 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -4,7 +4,7 @@ Deploying to heroku is relatively easy following these steps. -First, make sure you have the [heroku CLI installed](https://devcenter.heroku.com/articles/heroku-cli) and log into it as well as loging into Heroku's [container registry](https://devcenter.heroku.com/articles/container-registry-and-runtime). +First, make sure you have the [heroku CLI installed](https://devcenter.heroku.com/articles/heroku-cli) and log into it as well as login into Heroku's [container registry](https://devcenter.heroku.com/articles/container-registry-and-runtime). ```bash $ heroku login diff --git a/README.md b/README.md index 9ef09aee06..e05c1eb16e 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,8 @@ Out of the box, Backstage includes: For more information go to [backstage.io](https://backstage.io) or join our [Discord chatroom](https://discord.gg/EBHEGzX). +🎉 Backstage is a CNCF Sandbox project. Read the announcement [here](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox). + ## Project roadmap A detailed project roadmap, including already delivered milestones, is available [here](https://backstage.io/docs/overview/roadmap). @@ -51,11 +53,9 @@ Check out [the documentation](https://backstage.io/docs/getting-started) on how - [Code of Conduct](CODE_OF_CONDUCT.md) - This is how we roll - [Adopters](ADOPTERS.md) - Companies already using Backstage - [Blog](https://backstage.io/blog/) - Announcements and updates -- [Newsletter](https://mailchi.mp/spotify/backstage-community) +- [Newsletter](https://mailchi.mp/spotify/backstage-community) - Subscribe to our email newsletter - Give us a star â­ī¸ - If you are using Backstage or think it is an interesting project, we would love a star â¤ī¸ -Or, if you are an open source developer and are interested in joining our team, please reach out to [foss-opportunities@spotify.com ](mailto:foss-opportunities@spotify.com) - ## License Copyright 2020 Spotify AB. diff --git a/app-config.development.yaml b/app-config.development.yaml index da274ba1a8..817847c6d6 100644 --- a/app-config.development.yaml +++ b/app-config.development.yaml @@ -9,3 +9,5 @@ backend: origin: http://localhost:3000 methods: [GET, POST, PUT, DELETE] credentials: true + csp: + connect-src: ["'self'", 'http:', 'https:'] diff --git a/app-config.yaml b/app-config.yaml index 60ecb813f7..ac327f04a9 100644 --- a/app-config.yaml +++ b/app-config.yaml @@ -9,14 +9,13 @@ backend: database: client: sqlite3 connection: ':memory:' + csp: + connect-src: ["'self'", 'https:'] # See README.md in the proxy-backend plugin for information on the configuration format proxy: '/circleci/api': target: https://circleci.com/api/v1.1 - changeOrigin: true - pathRewrite: - '^/proxy/circleci/api/': '/' headers: Circle-Token: $secret: @@ -29,12 +28,21 @@ proxy: $secret: env: JENKINS_BASIC_AUTH_HEADER + '/travisci/api': + target: https://api.travis-ci.com + changeOrigin: true + headers: + Authorization: + $secret: + env: TRAVISCI_AUTH_TOKEN + travis-api-version: 3 + organization: name: Spotify techdocs: - storageUrl: http://localhost:7000/techdocs/static/docs - requestUrl: http://localhost:7000/techdocs/docs + storageUrl: http://localhost:7000/api/techdocs/static/docs + requestUrl: http://localhost:7000/api/techdocs generators: techdocs: 'docker' @@ -55,11 +63,53 @@ newrelic: lighthouse: baseUrl: http://localhost:3003 +kubernetes: + clusterLocatorMethod: 'configMultiTenant' + clusters: [] + +integrations: + github: + - host: github.com + token: + $secret: + env: GITHUB_PRIVATE_TOKEN + ### Example for how to add your GitHub Enterprise instance using the API: + # - host: ghe.example.net + # apiBaseUrl: https://ghe.example.net/api/v3 + # token: + # $secret: + # env: GHE_PRIVATE_TOKEN + ### Example for how to add your GitHub Enterprise instance using raw HTTP fetches (token is optional): + # - host: ghe.example.net + # rawBaseUrl: https://ghe.example.net/raw + # token: + # $secret: + # env: GHE_PRIVATE_TOKEN + gitlab: + - host: gitlab.com + token: + $secret: + env: GITLAB_PRIVATE_TOKEN + bitbucket: + - host: bitbucket.org + username: + $secret: + env: BITBUCKET_USERNAME + appPassword: + $secret: + env: BITBUCKET_APP_PASSWORD + azure: + - host: dev.azure.com + token: + $secret: + env: AZURE_PRIVATE_TOKEN + catalog: rules: - - allow: [Component, API, Group, Template, Location] + - allow: [Component, API, Group, User, Template, Location] + processors: - github: + githubOrg: providers: - target: https://github.com token: @@ -71,47 +121,22 @@ catalog: # token: # $secret: # env: GHE_PRIVATE_TOKEN - #### Example for how to add your GitHub Enterprise instance using raw HTTP fetches (token is optional): - # - target: https://ghe.example.net - # rawBaseUrl: https://ghe.example.net/raw - # token: - # $secret: - # env: GHE_PRIVATE_TOKEN - bitbucketApi: - username: - $secret: - env: BITBUCKET_USERNAME - appPassword: - $secret: - env: BITBUCKET_APP_PASSWORD - gitlabApi: - privateToken: - $secret: - env: GITLAB_PRIVATE_TOKEN - azureApi: - privateToken: - $secret: - env: AZURE_PRIVATE_TOKEN locations: # Backstage example components - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/all-components.yaml - # Example component for github-actions - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/plugins/github-actions/examples/sample.yaml - # Example component for techdocs - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/plugins/techdocs-backend/examples/documented-component/documented-component.yaml - # Backstage example APIs - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/all-apis.yaml - # Backstage example templates - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/sample-templates/all-templates.yaml scaffolder: @@ -126,6 +151,12 @@ scaffolder: token: $secret: env: GITLAB_ACCESS_TOKEN + azure: + baseUrl: https://dev.azure.com/{your-organization} + api: + token: + $secret: + env: AZURE_PRIVATE_TOKEN auth: providers: @@ -209,3 +240,33 @@ auth: tenantId: $secret: env: AUTH_MICROSOFT_TENANT_ID +costInsights: + engineerCost: 200000 + products: + computeEngine: + name: Compute Engine + icon: compute + cloudDataflow: + name: Cloud Dataflow + icon: data + cloudStorage: + name: Cloud Storage + icon: storage + bigQuery: + name: Big Query + icon: search + metrics: + dailyCost: + name: Your Company's Daily Cost + DAU: + name: Cost Per DAU +homepage: + clocks: + - label: UTC + timzone: UTC + - label: NYC + timezone: 'America/New_York' + - label: STO + timezone: 'Europe/Stockholm' + - label: TYO + timezone: 'Asia/Tokyo' diff --git a/contrib/docker/multi-stage-frontend/Dockerfile b/contrib/docker/multi-stage-frontend/Dockerfile index 0c492478d1..3190687c52 100644 --- a/contrib/docker/multi-stage-frontend/Dockerfile +++ b/contrib/docker/multi-stage-frontend/Dockerfile @@ -1,4 +1,4 @@ -FROM node:12 AS build +FROM node:12-buster AS build RUN mkdir /app COPY . /app diff --git a/docs/FAQ.md b/docs/FAQ.md index b4c4970ff8..355cf97880 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -86,7 +86,7 @@ well-known tech and a large flora of components. ### What technology does Backstage use? -The code base is a large-scale React application that uses TypeScript. For +The codebase is a large-scale React application that uses TypeScript. For [Phase 2](https://github.com/spotify/backstage#project-roadmap), we plan to use Node.js and GraphQL. @@ -132,20 +132,19 @@ to see if it already exists or is in the works. If no one's thought of it yet, great! Open a new issue as [a plugin suggestion](https://github.com/spotify/backstage/issues/new/choose) and describe what your plugin will do. This will help coordinate our -contributors' efforts and avoid duplicating existing functionality. In the -future, we will create -[a plugin gallery](https://github.com/spotify/backstage/issues/260) where people -can browse and search for all available plugins. +contributors' efforts and avoid duplicating existing functionality. + +You can browse and search for all available plugins in the +[Plugin Marketplace](https://backstage.io/plugins). ### Which plugin is used the most at Spotify? By far, our most-used plugin is our TechDocs plugin, which we use for creating technical documentation. Our philosophy at Spotify is to treat "docs like code", where you write documentation using the same workflow as you write your code. -This makes it easier to create, find, and update documentation. We hope to -release -[the open source version](https://github.com/spotify/backstage/issues/687) in -the future. (See also: +This makes it easier to create, find, and update documentation. +[TechDocs is now open source.](https://backstage.io/docs/features/techdocs/techdocs-overview) +(See also: "[Will Spotify's internal plugins be open sourced, too?](#will-spotifys-internal-plugins-be-open-sourced-too)" above) @@ -205,7 +204,7 @@ Please report sensitive security issues via Spotify's ### Does Backstage collect any information that is shared with Spotify? No. Backstage does not collect any telemetry from any third party using the -platform. Spotify, and the open source community, does have access to +platform. Spotify, and the open source community, do have access to [GitHub Insights](https://github.com/features/insights), which contains information such as contributors, commits, traffic, and dependencies. Backstage is an open platform, but you are in control of your own data. You control who diff --git a/docs/api/utility-apis.md b/docs/api/utility-apis.md index d192cbd6ee..1ebf2ae88b 100644 --- a/docs/api/utility-apis.md +++ b/docs/api/utility-apis.md @@ -97,7 +97,7 @@ app, and the app itself. ### Core APIs -Starting with the Backstage core library, it provides implementation for all of +Starting with the Backstage core library, it provides implementations for all of the core APIs. The core APIs are the ones exported by `@backstage/core`, such as the `errorApiRef` and `configApiRef`. You can find a full list of them [here](../reference/utility-apis/README.md). @@ -113,7 +113,7 @@ While doing so they should usually also provide default implementations of their own APIs, for example, the `catalog` plugin exports `catalogApiRef`, and also supplies a default `ApiFactory` of that API using the `CatalogClient`. There is one restriction to plugin-provided API Factories: plugins may not supply -factories for core APIs, trying to do so will cause the app to crash. +factories for core APIs, trying to do so will cause the app to refuse to start. Plugins supply their APIs through the `apis` option of `createPlugin`, for example: @@ -248,8 +248,8 @@ directly tied to React. The indirection provided by Utility APIs also makes it straightforward to test components that depend on APIs, and to provide a standard common development environment for plugins. A proper test wrapper with mocked API implementations -is not yet ready, but it will provided as a part of `@backstage/test-utils`. It -will provide mocked variants of APIs, with additional methods for asserting a +is not yet ready, but it will be provided as a part of `@backstage/test-utils`. +It will provide mocked variants of APIs, with additional methods for asserting a component's interaction with the API. The common development environment for plugins is included in diff --git a/docs/architecture-decisions/adr002-default-catalog-file-format.md b/docs/architecture-decisions/adr002-default-catalog-file-format.md index f4fd3a1158..d831581d5b 100644 --- a/docs/architecture-decisions/adr002-default-catalog-file-format.md +++ b/docs/architecture-decisions/adr002-default-catalog-file-format.md @@ -22,7 +22,7 @@ This ADR describes the default format of these descriptor files. ### Inspiration -Internally at Spotify, a home grown software catalog system is used heavily and +Internally at Spotify, a homegrown software catalog system is used heavily and forms a core part of Backstage and other important pieces of the infrastructure. The user experience, learnings and certain pieces of metadata from that catalog are being carried over to the open source effort. @@ -40,7 +40,7 @@ triggers from the version control system, etc. Each file describes one or more entities in accordance with the [Backstage System Model](https://github.com/spotify/backstage/issues/390). All -of these entities have a common stucture and nomenclature, and they are stored +of these entities have a common structure and nomenclature, and they are stored in the software catalog from which they then can be queried. Entities have distinct names, and they may reference each other by those names. diff --git a/docs/architecture-decisions/adr003-avoid-default-exports.md b/docs/architecture-decisions/adr003-avoid-default-exports.md index 8634a19632..d08bc6a882 100644 --- a/docs/architecture-decisions/adr003-avoid-default-exports.md +++ b/docs/architecture-decisions/adr003-avoid-default-exports.md @@ -44,7 +44,7 @@ A summary: name each. Using named exports helps prevent needing to rename symbols, which has myriad -benefts. A few are: +benefits. A few are: - IDE tools like "Find All References" and "Go To Definition" function - Manual codebase searching ("grep", etc) is easier with a unique symbol diff --git a/docs/architecture-decisions/adr004-module-export-structure.md b/docs/architecture-decisions/adr004-module-export-structure.md index 12408abac1..14c94c4ed1 100644 --- a/docs/architecture-decisions/adr004-module-export-structure.md +++ b/docs/architecture-decisions/adr004-module-export-structure.md @@ -22,8 +22,8 @@ or We currently do not use any pattern for how to structure exports. There is a mix of package-level re-exports deep into the directory tree, shallow re-exports for each directory, exports using `*` and explicit lists of each symbol, etc. The -mix and lack of predictability makes it difficult to reason about the boundaries -of a module, and for example knowing whether is is safe to export a symbol in a +mix and lack of predictability make it difficult to reason about the boundaries +of a module, and for example knowing whether it is safe to export a symbol in a given file. ## Decision diff --git a/docs/architecture-decisions/adr006-avoid-react-fc.md b/docs/architecture-decisions/adr006-avoid-react-fc.md index bea36712d7..96f594daf7 100644 --- a/docs/architecture-decisions/adr006-avoid-react-fc.md +++ b/docs/architecture-decisions/adr006-avoid-react-fc.md @@ -13,7 +13,7 @@ with next to no benefits in combination with a few downsides. The main reasons were: - **children props** were implicitly added -- **Generic Type** were not supported on children +- **Generic Type** was not supported on children Read more about the removal in [this PR](https://github.com/facebook/create-react-app/pull/8177). @@ -25,7 +25,7 @@ should be avoided in our codebase when adding new code. Here is an example: -```ts +```typescript /* Avoid this: */ type BadProps = { text: string }; const BadComponent: FC = ({ text, children }) => ( diff --git a/docs/architecture-decisions/adr007-use-msw-to-mock-service-requests.md b/docs/architecture-decisions/adr007-use-msw-to-mock-service-requests.md index 6b18f67d40..045588f505 100644 --- a/docs/architecture-decisions/adr007-use-msw-to-mock-service-requests.md +++ b/docs/architecture-decisions/adr007-use-msw-to-mock-service-requests.md @@ -11,7 +11,7 @@ tests, unit tests to e2e tests always have their own implementation of mocking these requests. There's been traction in the outer community towards using this library to mock network requests by using an express style declaration for routes. react-testing-library suggests using this library instead of mocking -fetch directly wether this be in a browser or in node. +fetch directly whether this be in a browser or in node. https://github.com/mswjs/msw diff --git a/docs/architecture-decisions/adr008-default-catalog-file-name.md b/docs/architecture-decisions/adr008-default-catalog-file-name.md index c57d10c0b1..d4716318bc 100644 --- a/docs/architecture-decisions/adr008-default-catalog-file-name.md +++ b/docs/architecture-decisions/adr008-default-catalog-file-name.md @@ -7,7 +7,7 @@ description: Architecture Decision Record (ADR) log on Default Catalog File Name ## Background While the spec for the catalog file format is well described in -[ADR002](./adr002-default-catalog-file-format.md), guidance was note provided as +[ADR002](./adr002-default-catalog-file-format.md), guidance was not provided as to the name of the catalog file. Following discussion in @@ -23,4 +23,4 @@ catalog-info.yaml ``` This name is a default, **not a requirement**. The catalog file will work with -Backstage irregardless of its name. +Backstage regardless of its name. diff --git a/docs/architecture-decisions/adr009-entity-references.md b/docs/architecture-decisions/adr009-entity-references.md new file mode 100644 index 0000000000..8b7984ea49 --- /dev/null +++ b/docs/architecture-decisions/adr009-entity-references.md @@ -0,0 +1,69 @@ +--- +id: adrs-adr009 +title: ADR009: Entity References +description: Architecture Decision Record (ADR) log on Entity References +--- + +## Background + +While the spec for the catalog file format is well described in +[ADR002](./adr002-default-catalog-file-format.md), guidance was not provided as +to how one is expected to express references to other entities in the catalog. +There was also some confusion on how to reference entities in URLs in the +Backstage frontend. + +Following discussion in +[Issue 1947](https://github.com/spotify/backstage/issues/1947), a decision was +made. + +## Entity References in YAML files + +The textual format, as written by humans, to reference entities by name is on +the following form, where square brackets denote optionality: + +``` +[:][/] +``` + +That is, it is composed of between one and three parts in this specific order, +without any additional encoding, with those exact separator characters. +Optionality of `kind` and `namespace` are contextual, and they may or may not +have default contextual fallback values. + +When that format is insufficient or when machine made interchange formats wish +to express such relations in a more expressive form, a nested structure on the +following form can be used: + +```yaml +kind: +namespace: +name: +``` + +Of these, only `name` is always required. Optionality of `kind` and `namespace` +are contextual, and they may or may not have default contextual fallback values. +All other possible key values in this structure are reserved for future use. + +A system or user wanting to express a full entity name that is always valid, +shall supply the entire triplet whether using the string form or the compound +form. + +A full description of the format can be found +[in the documentation](https://backstage.io/docs/features/software-catalog/references). + +## Entity References in URLs + +Where entities are referenced by name in the Backstage frontend, the URL +containing the reference shall take the following form: + +``` +:namespace/:kind/:name +``` + +All three parts are required under all circumstances. The default value for the +`namespace` in the catalog is the string `"default"`, if the entity does not +specify one explicitly in `metadata.namespace`. + +This means that we do not encourage the string form of entity references to be +used as a single URL segment, due to the use of URL-unsafe characters leading to +possible risk, confusion, and uglier URLs. diff --git a/docs/auth/add-auth-provider.md b/docs/auth/add-auth-provider.md index c5f7645a49..56586cbfc6 100644 --- a/docs/auth/add-auth-provider.md +++ b/docs/auth/add-auth-provider.md @@ -229,9 +229,10 @@ name. ### Test the new provider -You can `curl -i localhost:7000/auth/providerA/start` and which should provide a -`302` redirect with a `Location` header. Paste the url from that header into a -web browser and you should be able to trigger the authorization flow. +You can `curl -i localhost:7000/api/auth/providerA/start` and which should +provide a `302` redirect with a `Location` header. Paste the url from that +header into a web browser and you should be able to trigger the authorization +flow. --- diff --git a/docs/auth/index.md b/docs/auth/index.md index aed3a580b0..d7fb5d8c59 100644 --- a/docs/auth/index.md +++ b/docs/auth/index.md @@ -6,7 +6,7 @@ description: Documentation on User Authentication and Authorization in Backstage ## Summary -The purpose of the Auth APIs in Backstage are to identify the user, and to +The purpose of the Auth APIs in Backstage is to identify the user, and to provide a way for plugins to request access to 3rd party services on behalf of the user (OAuth). This documentation focuses on the implementation of that solution and how to extend it. For documentation on how to consume the Auth APIs diff --git a/docs/auth/oauth.md b/docs/auth/oauth.md index e90b7b665a..178b99b153 100644 --- a/docs/auth/oauth.md +++ b/docs/auth/oauth.md @@ -52,7 +52,7 @@ in a new popup window that is opened by the app. By using a popup-based flow it is possible to request authentication at any point in the app, without requiring a redirect. Because of this there is no need to ask for all scopes upfront, or interrupt the app with a redirect and forcing plugin authors to take care in -restoring state after a redirect has been make. All in all it makes it much +restoring state after a redirect has been made. All in all it makes it much easier to make authenticated requests inside a plugin. ## OAuth Flow @@ -67,7 +67,7 @@ Component and APIs can request Access or ID Tokens from any available Auth provider. If there already exists a cached fresh token that covers (at least) the requested scopes, it will be returned immediately. If the OAuth provider implements token refreshes, this check will also trigger a token refresh attempt -if no session is a available. +if no session is available. If new scopes are requested, or the user is not yet logged in with that provider, a dialog is shown informing the user that they need to log in with the diff --git a/docs/features/software-catalog/configuration.md b/docs/features/software-catalog/configuration.md index c98bd73ca3..ba5e36ab5d 100644 --- a/docs/features/software-catalog/configuration.md +++ b/docs/features/software-catalog/configuration.md @@ -11,36 +11,56 @@ tasks, such as reading raw entity data from a remote source, parsing it, transforming it, and validating it. These processors are configured under the `catalog.processors` key. -### Processor: github +### Processor: url -The `github` processor is responsible for fetching entity data from files on -GitHub or GitHub Enterprise. The configuration for this processor lives under -`catalog.processors.github`. Example: +The `url` processor is responsible for fetching entity data from files in any +external provider like GitHub, GitLab, Bitbucket, etc. The configuration of this +processor lives under the top-level `integrations` key, as it is used by other +parts of Backstage too. ```yaml -catalog: - processors: - github: - providers: - - target: https://github.com - token: - $secret: - env: GITHUB_PRIVATE_TOKEN - - target: https://ghe.example.net - apiBaseUrl: https://ghe.example.net/api/v3 - rawBaseUrl: https://ghe.example.net/raw - token: - $secret: - env: GHE_PRIVATE_TOKEN +integrations: + github: + - host: github.com + token: + $secret: + env: GITHUB_TOKEN + - host: ghe.example.net + apiBaseUrl: https://ghe.example.net/api/v3 + rawBaseUrl: https://ghe.example.net/raw + token: + $secret: + env: GHE_TOKEN + gitlab: + - host: gitlab.com + token: + $secret: + env: GITLAB_TOKEN + bitbucket: + - host: bitbucket.org + username: + $secret: + env: BITBUCKET_USERNAME + appPassword: + $secret: + env: BITBUCKET_APP_PASSWORD + azure: + - host: dev.azure.com + token: + $secret: + env: AZURE_TOKEN ``` -The main subkey is `providers`, where you can list the various GitHub compatible -providers you want to be able to fetch data from. Each entry is a structure with -up to four elements: +Each key under `integrations` is a separate configuration for each external +provider. The providers each have their own configuration, so let's look at the +GitHub section as an example. -- `target` (required): The string prefix of the location target that you want to - match on, with no trailing slash. For GitHub, it should be exactly - `https://github.com`. +Directly under the `github` key is a list of provider configurations, where you +can list the various GitHub compatible providers you want to be able to fetch +data from. Each entry is a structure with up to four elements: + +- `host` (optional): The host of the location target that you want to match on. + The default host is `github.com`. - `token` (optional): An authentication token as expected by GitHub. If supplied, it will be passed along with all calls to this provider, both API and raw. If it is not supplied, anonymous access will be used. @@ -74,7 +94,7 @@ the catalog under the `catalog.locations` key, for example: ```yaml catalog: locations: - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/artist-lookup-component.yaml ``` @@ -97,7 +117,7 @@ catalog: - allow: [Component, API, Location, Template] locations: - - type: github + - type: url target: https://github.com/org/example/blob/master/org-data.yaml rules: - allow: [Group] diff --git a/docs/features/software-catalog/descriptor-format.md b/docs/features/software-catalog/descriptor-format.md index 301d80630c..0c50e3669a 100644 --- a/docs/features/software-catalog/descriptor-format.md +++ b/docs/features/software-catalog/descriptor-format.md @@ -22,6 +22,8 @@ humans. However, the structure and semantics is the same in both cases. - [Kind: Component](#kind-component) - [Kind: Template](#kind-template) - [Kind: API](#kind-api) +- [Kind: Group](#kind-group) +- [Kind: User](#kind-user) ## Overall Shape Of An Entity @@ -571,3 +573,167 @@ group of people in an organizational structure. The definition of the API, based on the format defined by `spec.type`. This field is required. + +## Kind: Group + +Describes the following entity kind: + +| Field | Value | +| ------------ | ----------------------- | +| `apiVersion` | `backstage.io/v1alpha1` | +| `kind` | `Group` | + +A group describes an organizational entity, such as for example a team, a +business unit, or a loose collection of people in an interest group. Members of +these groups are modeled in the catalog as kind [`User`](#kind-user). + +Descriptor files for this kind may look as follows. + +```yaml +apiVersion: backstage.io/v1alpha1 +kind: Group +metadata: + name: infrastructure + description: The infra business unit +spec: + type: business-unit + parent: ops + ancestors: [ops, global-synergies, acme-corp] + children: [backstage, other] + descendants: [backstage, other, team-a, team-b, team-c, team-d] +``` + +In addition to the [common envelope metadata](#common-to-all-kinds-the-metadata) +shape, this kind has the following structure. + +### `apiVersion` and `kind` [required] + +Exactly equal to `backstage.io/v1alpha1` and `Group`, respectively. + +### `spec.type` [required] + +The type of group as a string, e.g. `team`. There is currently no enforced set +of values for this field, so it is left up to the adopting organization to +choose a nomenclature that matches their org hierarchy. + +Some common values for this field could be: + +- `team` +- `business-unit` +- `product-area` +- `root` - as a common virtual root of the hierarchy, if desired + +### `spec.parent` [optional] + +The immediate parent group in the hierarchy, if any. Not all groups must have a +parent; the catalog supports multi-root hierarchies. Groups may however not have +more than one parent. + +This field is an +[entity reference](https://backstage.io/docs/features/software-catalog/references), +with the default kind `Group` and the default namespace equal to the same +namespace as the user. Only `Group` entities may be referenced. Most commonly, +this field points to a group in the same namespace, so in those cases it is +sufficient to enter only the `metadata.name` field of that group. + +### `spec.ancestors` [required] + +The recursive list of parents up the hierarchy, by stepping through parents one +by one. The list must be present, but may be empty if `parent` is not present. +The first entry in the list is equal to `parent`, and then the following ones +are progressively farther up the hierarchy. + +The entries of this array are +[entity references](https://backstage.io/docs/features/software-catalog/references), +with the default kind `Group` and the default namespace equal to the same +namespace as the user. Only `Group` entities may be referenced. Most commonly, +these entries point to groups in the same namespace, so in those cases it is +sufficient to enter only the `metadata.name` field of those groups. + +### `spec.children` [required] + +The immediate child groups of this group in the hierarchy (whose `parent` field +points to this group). The list must be present, but may be empty if there are +no child groups. The items are not guaranteed to be ordered in any particular +way. + +The entries of this array are +[entity references](https://backstage.io/docs/features/software-catalog/references), +with the default kind `Group` and the default namespace equal to the same +namespace as the user. Only `Group` entities may be referenced. Most commonly, +these entries point to groups in the same namespace, so in those cases it is +sufficient to enter only the `metadata.name` field of those groups. + +### `spec.descendants` [required] + +The immediate and recursive child groups of this group in the hierarchy +(children, and children's children, etc.). The list must be present, but may be +empty if there are no child groups. The items are not guaranteed to be ordered +in any particular way. + +The entries of this array are +[entity references](https://backstage.io/docs/features/software-catalog/references), +with the default kind `Group` and the default namespace equal to the same +namespace as the user. Only `Group` entities may be referenced. Most commonly, +these entries point to groups in the same namespace, so in those cases it is +sufficient to enter only the `metadata.name` field of those groups. + +## Kind: User + +Describes the following entity kind: + +| Field | Value | +| ------------ | ----------------------- | +| `apiVersion` | `backstage.io/v1alpha1` | +| `kind` | `User` | + +A user describes a person, such as an employee, a contractor, or similar. Users +belong to [`Group`](#kind-group) entities in the catalog. + +These catalog user entries are connected to the way that authentication within +the Backstage ecosystem works. See the [auth](https://backstage.io/docs/auth) +section of the docs for a discussion of these concepts. + +Descriptor files for this kind may look as follows. + +```yaml +apiVersion: backstage.io/v1alpha1 +kind: User +metadata: + name: jdoe +spec: + profile: + displayName: Jenny Doe + email: jenny-doe@example.com + picture: https://example.com/staff/jenny-with-party-hat.jpeg + memberOf: [team-b, employees] +``` + +In addition to the [common envelope metadata](#common-to-all-kinds-the-metadata) +shape, this kind has the following structure. + +### `apiVersion` and `kind` [required] + +Exactly equal to `backstage.io/v1alpha1` and `User`, respectively. + +### `spec.profile` [optional] + +Optional profile information about the user, mainly for display purposes. All +fields of this structure are also optional. The email would be a primary email +of some form, that the user may wish to be used for contacting them. The picture +is expected to be a URL pointing to an image that's representative of the user, +and that a browser could fetch and render on a profile page or similar. + +### `spec.memberOf` [required] + +The list of groups that the user is a direct member of (i.e., no transitive +memberships are listed here). The list must be present, but may be empty if the +user is not member of any groups. The items are not guaranteed to be ordered in +any particular way. + +The entries of this array are +[entity references](https://backstage.io/docs/features/software-catalog/references), +with the default kind `Group` and the default namespace equal to the same +namespace as the user. Only `Group` entities may be referenced. Most commonly, +these entries point to groups in the same namespace, so in those cases it is +sufficient to enter only the `metadata.name` field of those groups. diff --git a/docs/features/software-catalog/extending-the-model.md b/docs/features/software-catalog/extending-the-model.md index 4e8a357ea7..b045660202 100644 --- a/docs/features/software-catalog/extending-the-model.md +++ b/docs/features/software-catalog/extending-the-model.md @@ -16,11 +16,9 @@ Backstage natively supports tracking of the following component ![](../../assets/software-catalog/bsc-extend.png) Since these types are likely not the only kind of software you will want to -track in Backstage, it is possible to - -It is possible to add your own software types that fits your organization's data -model. Inside Spotify our model has grown significantly over the years, and now -includes ML models, Apps, data pipelines and many more. +track in Backstage, it is possible to add your own software types that fit your +organization's data model. Inside Spotify our model has grown significantly over +the years, and now includes ML models, Apps, data pipelines and many more. ## Adding a new type @@ -30,7 +28,7 @@ catalog. ## The Other type It might be tempting to put software that doesn't fit into any of the existing -types into Other. There are a few reasons why we advice against this; firstly, +types into Other. There are a few reasons why we advise against this; firstly, we have found that it is preferred to match the conceptual model that your engineers have when describing your software. Secondly, Backstage helps your engineers manage their software by integrating the infrastructure tooling diff --git a/docs/features/software-catalog/index.md b/docs/features/software-catalog/index.md index 49a490d78b..4ba83146db 100644 --- a/docs/features/software-catalog/index.md +++ b/docs/features/software-catalog/index.md @@ -84,13 +84,13 @@ registered in the catalog. ### Static catalog configuration In addition to manually registering components, it is also possible to register -components though [static configuration](../../conf/index.md). For example, the +components through [static configuration](../../conf/index.md). For example, the above example can be added using the following configuration: ```yaml catalog: locations: - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/artist-lookup-component.yaml ``` diff --git a/docs/features/software-catalog/installation.md b/docs/features/software-catalog/installation.md index a825020eb6..26990033aa 100644 --- a/docs/features/software-catalog/installation.md +++ b/docs/features/software-catalog/installation.md @@ -166,21 +166,21 @@ our example templates through static configuration. Add the following to the catalog: locations: # Backstage Example Component - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/artist-lookup-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/playback-order-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/podcast-api-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/queue-proxy-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/searcher-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/playback-lib-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/www-artist-component.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/shuffle-api-component.yaml ``` diff --git a/docs/features/software-catalog/references.md b/docs/features/software-catalog/references.md new file mode 100644 index 0000000000..e438ddc977 --- /dev/null +++ b/docs/features/software-catalog/references.md @@ -0,0 +1,104 @@ +--- +id: references +title: Entity References +description: How to express references between entities +--- + +Entities commonly have a need to reference other entities. For example, a +[Component](descriptor-format.md#kind-component) entity may want to declare who +its owner is by mentioning a Group or User entity, and a User entity may want to +declare what Group entities it is a member of. This article describes how to +write those references in your yaml entity declaration files. + +Each entity in the catalog is uniquely identified by the triplet of its +[kind](descriptor-format.md#apiversion-and-kind-required), +[namespace](descriptor-format.md#namespace-optional), and +[name](descriptor-format.md#name-required). But that's a lot to type out +manually, and in a lot of circumstances, both the kind and the namespace are +fixed, or possible to deduce, or could have sane default values. So in order to +help the writer, the catalog has a few tricks up its sleeve. + +Each reference can be expressed in one of two ways: as a compact string, or as a +compound reference structure. + +## String References + +This is the most common alternative, that should be used in almost all +circumstances. + +The string is on the form `[:][/]`, that is, it is +composed of between one and three parts in this specific order, without any +additional encoding: + +- Optionally, the kind, followed by a colon +- Optionally, the namespace, followed by a forward slash +- The name + +The name is always required. Depending on the context, you may be able to leave +out the kind and/or namespace. If you do, it is contextual what values will be +used, and the relevant documentation should specify which rule applies where. +All strings are case insensitive. + +```yaml +# Example: +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: petstore + namespace: external-systems + description: Petstore +spec: + type: service + lifecycle: experimental + owner: group:pet-managers + implementsApis: + - petstore + - internal/streetlights + - hello-world +``` + +The field `spec.owner` is a reference. In this case, the string +`group:pet-managers` was given by the user. That means that the kind is `Group`, +the namespace is left out, and the name is `pet-managers`. In this context, the +namespace was chosen to fall back to the value `default` by the code that parsed +the reference, so the end result is that we expect to find another entity in the +catalog that is of kind `Group`, namespace `default` (which, actually, also can +be left out in its own yaml file because that's the default value there too), +and name `pet-managers`. + +The entries in `implementsApis` are also references. In this case, none of them +needs to specify a kind since we know from the context that that's the only kind +that's supported here. The second entry specifies a namespace but the other ones +don't, and in this context, the default is to refer to the same namespace as the +originating entity (`external-systems` here). So the three references +essentially expand to `api:external-systems/petstore`, +`api:internal/streetlights`, and `api:external-systems/hello-world`. We expect +there to exist three API kind entities in the catalog matching those references. + +## Compound References + +This is a more verbose version of a reference, where each part of the +kind-namespace-name triplet is expressed as a field in a structure. This format +can be used where necessary, such as if either of the three elements contains +colons or forward slashes. Avoid using it where possible, since it is harder to +read and write for humans. + +```yaml +# Example: +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: petstore + description: Petstore +spec: + type: service + lifecycle: experimental + owner: + kind: Group + name: aegis-imports/pet-managers +``` + +In this example, the `spec.owner` has been broken apart since the name was +complex. The kind happened to be written with an uppercase letter G, which also +works. The namespace was left out just like in the string version above, which +is handled identically. diff --git a/docs/features/software-catalog/well-known-annotations.md b/docs/features/software-catalog/well-known-annotations.md index ba5b491e07..1bd5528f22 100644 --- a/docs/features/software-catalog/well-known-annotations.md +++ b/docs/features/software-catalog/well-known-annotations.md @@ -41,6 +41,27 @@ expecting a two-item array out of it. The format of the target part is type-dependent and could conceivably even be an empty string, but the separator colon is always present. +### backstage.io/definition-at-location + +```yaml +# Example +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: petstore + annotations: + backstage.io/definition-at-location: 'url:https://petstore.swagger.io/v2/swagger.json' +spec: + type: openapi +``` + +This annotation allows to fetch an API definition from another location, instead +of wrapping the API definition inside the definition field. This allows to +easily consume existing API definition. The definition is fetched during +ingestion by a processor and included in the entity. It is updated on every +refresh. The annotation contains a location reference string that contains the +location processor type and the target. + ### backstage.io/techdocs-ref ```yaml @@ -79,13 +100,50 @@ metadata: ``` The value of this annotation is the so-called slug that identifies a project on -[GitHub](https://github.com) that is related to this entity. It is on the format +[GitHub](https://github.com) (either the public one, or a private GitHub +Enterprise installation) that is related to this entity. It is on the format `/`, and is the same as can be seen in the URL location bar of the browser when viewing that project. Specifying this annotation will enable GitHub related features in Backstage for that entity. +### github.com/team-slug + +```yaml +# Example: +metadata: + annotations: + github.com/team-slug: spotify/backstage-core +``` + +The value of this annotation is the so-called slug that identifies a team on +[GitHub](https://github.com) (either the public one, or a private GitHub +Enterprise installation) that is related to this entity. It is on the format +`/`, and is the same as can be seen in the URL location bar +of the browser when viewing that team. + +This annotation can be used on a [Group entity](descriptor-format.md#kind-group) +to note that it originated from that team on GitHub. + +### github.com/user-login + +```yaml +# Example: +metadata: + annotations: + github.com/user-login: freben +``` + +The value of this annotation is the so-called login that identifies a user on +[GitHub](https://github.com) (either the public one, or a private GitHub +Enterprise installation) that is related to this entity. It is on the format +``, and is the same as can be seen in the URL location bar of the +browser when viewing that user. + +This annotation can be used on a [User entity](descriptor-format.md#kind-user) +to note that it originated from that user on GitHub. + ### sentry.io/project-slug ```yaml diff --git a/docs/features/software-templates/adding-templates.md b/docs/features/software-templates/adding-templates.md index fad5c68e41..5a4e0049ab 100644 --- a/docs/features/software-templates/adding-templates.md +++ b/docs/features/software-templates/adding-templates.md @@ -5,7 +5,7 @@ description: Documentation on Adding your own Templates --- Templates are stored in the **Service Catalog** under a kind `Template`. The -minimum that the a template skeleton needs is a `template.yaml` but it would be +minimum that the template skeleton needs is a `template.yaml` but it would be good to also have some files in there that can be templated in. A simple `template.yaml` definition might look something like this: @@ -30,7 +30,7 @@ spec: templater: cookiecutter # what does this template create type: website - # if the template is not in the current directory where this definition is kept then specfiy + # if the template is not in the current directory where this definition is kept then specify path: './template' # the schema for the form which is displayed in the frontend. # should follow JSON schema for forms: https://jsonforms.io/ @@ -66,7 +66,7 @@ for example ```yaml catalog: locations: - - type: github + - type: url target: https://github.com/spotify/cookiecutter-golang/blob/master/template.yaml rules: - allow: [Template] @@ -88,7 +88,7 @@ running: ```sh curl \ --location \ - --request POST 'localhost:7000/catalog/locations' \ + --request POST 'localhost:7000/api/catalog/locations' \ --header 'Content-Type: application/json' \ --data-raw "{\"type\": \"file\", \"target\": \"${YOUR PATH HERE}/template.yaml\"}" ``` @@ -98,7 +98,7 @@ If loading from a Git location, you can run the following ```sh curl \ --location \ - --request POST 'localhost:7000/catalog/locations' \ + --request POST 'localhost:7000/api/catalog/locations' \ --header 'Content-Type: application/json' \ --data-raw "{\"type\": \"github\", \"target\": \"https://${YOUR GITHUB REPO}blob/master/${PATH TO FOLDER}/template.yaml\"}" ``` @@ -107,7 +107,7 @@ This should then have added the catalog, and also should now be listed under the create page at http://localhost:3000/create. The `type` field which is chosen in the request to add the `template.yaml` to -the Service Catalog here, will be come the `PreparerKey` which will be used to +the Service Catalog here, will become the `PreparerKey` which will be used to select the `Preparer` when creating a job. ### Adding form values in the Scaffolder Wizard diff --git a/docs/features/software-templates/extending/create-your-own-preparer.md b/docs/features/software-templates/extending/create-your-own-preparer.md index 14c75b0ffb..80287c6ce1 100644 --- a/docs/features/software-templates/extending/create-your-own-preparer.md +++ b/docs/features/software-templates/extending/create-your-own-preparer.md @@ -17,7 +17,7 @@ location protocols: These two are added to the `PreparersBuilder` and then passed into the `createRouter` function of the `@spotify/plugin-scaffolder-backend` -An full example backend can be found +A full example backend can be found [here](https://github.com/spotify/backstage/blob/d91c10f654475a60829fa33a5c81018e517a319a/packages/backend/src/plugins/scaffolder.ts), but it looks something like the following @@ -88,7 +88,7 @@ Some good examples exist here: - https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/src/scaffolder/stages/prepare/file.ts - https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/src/scaffolder/stages/prepare/github.ts -### Registerinng your own Preparer +### Registering your own Preparer You can register the preparer that you have created with the `PreparerBuilder` by using the `PreparerKey` from the Catalog, for example like this: @@ -98,4 +98,4 @@ const preparers = new Preparers(); preparers.register('gcs', new GoogleCloudStoragePreparer()); ``` -And then pass this in to the `createRouter` function. +And then pass this into the `createRouter` function. diff --git a/docs/features/software-templates/extending/create-your-own-publisher.md b/docs/features/software-templates/extending/create-your-own-publisher.md index 25d7bcf676..ecb097f9d9 100644 --- a/docs/features/software-templates/extending/create-your-own-publisher.md +++ b/docs/features/software-templates/extending/create-your-own-publisher.md @@ -8,10 +8,10 @@ Publishers are responsible for pushing and storing the templated skeleton after the values have been templated by the `Templater`. See [Create your own templater](./create-your-own-templater.md) for more info. -They receive a directory or location where the templater has sucessfully run and -is now ready to store somewhere. They also are given some other options which -are sent from the frontend, such as the `storePath` which is a string of where -the frontend thinks we should save this templated folder. +They receive a directory or location where the templater has successfully run +and is now ready to store somewhere. They also are given some other options +which are sent from the frontend, such as the `storePath` which is a string of +where the frontend thinks we should save this templated folder. Currently we provide the following `publishers`: diff --git a/docs/features/software-templates/extending/create-your-own-templater.md b/docs/features/software-templates/extending/create-your-own-templater.md index 36c362b9c3..d4a6eef5d2 100644 --- a/docs/features/software-templates/extending/create-your-own-templater.md +++ b/docs/features/software-templates/extending/create-your-own-templater.md @@ -147,4 +147,4 @@ const templaters = new Templaters(); templaters.register('handlebars', new HandlebarsTemplater()); ``` -And then pass this in to the `createRouter` function. +And then pass this into the `createRouter` function. diff --git a/docs/features/software-templates/extending/index.md b/docs/features/software-templates/extending/index.md index 02d27a5725..944bf0e3ca 100644 --- a/docs/features/software-templates/extending/index.md +++ b/docs/features/software-templates/extending/index.md @@ -11,13 +11,13 @@ You're at the right place. This guide is going to take you through how the Scaffolder in Backstage works. We'll dive into some jargon and run through what's going on in the backend to be able to create these templates. There's also more guides that you might find -useful at the bottom of this document. At it's core, theres 3 simple stages. +useful at the bottom of this document. At its core, there are 3 simple stages. 1. Pick a skeleton 2. Template some variables into the skeleton 3. Send the templated skeleton somewhere -These three steps are translated to the folllowing stages under the hood in the +These three steps are translated to the following stages under the hood in the scaffolder that you will need to know: 1. Prepare @@ -38,7 +38,7 @@ the router to pick the correct `Preparer` to run for the `Template` entity. **Templater** - The templater is responsible for actually running the chosen templater on top of the previously returned temporary directory from the -**Preprarer**. We advise making these Docker containers as it can keep all +**Preparer**. We advise making these Docker containers as it can keep all dependencies--for example Cookiecutter--self contained and not a dependency on the host machine. @@ -82,7 +82,7 @@ Once that has been posted, a job will be setup with different stages, and the job processor will complete each stage before moving onto the next stage, whilst collecting logs and mutating the running job. -Here's some futher reading that you might find useful: +Here's some further reading that you might find useful: - [Adding your own Template](../adding-templates.md) - [Creating your own Templater](./create-your-own-templater.md) diff --git a/docs/features/software-templates/installation.md b/docs/features/software-templates/installation.md index 90d25cab81..08f1882425 100644 --- a/docs/features/software-templates/installation.md +++ b/docs/features/software-templates/installation.md @@ -191,13 +191,13 @@ our example templates through static configuration. Add the following to the catalog: locations: # Backstage Example Templates - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/sample-templates/react-ssr-template/template.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/sample-templates/springboot-grpc-template/template.yaml - - type: github + - type: url target: https://github.com/spotify/backstage/blob/master/plugins/scaffolder-backend/sample-templates/create-react-app/template.yaml - - type: github + - type: url target: https://github.com/spotify/cookiecutter-golang/blob/master/template.yaml ``` @@ -217,6 +217,11 @@ The Github access token is retrieved from environment variables via the config. The config file needs to specify what environment variable the token is retrieved from. Your config should have the following objects. +You can configure who can see the new repositories that the scaffolder creates +by specifying `visibility` option. Valid options are `public`, `private` and +`internal`. `internal` options is for GitHub Enterprise clients, which means +public within the organization. + #### Gitlab For Gitlab, we currently support the configuration of the GitLab publisher and @@ -238,10 +243,23 @@ scaffolder: env: SCAFFOLDER_GITLAB_PRIVATE_TOKEN ``` -You can configure who can see the new repositories that the scaffolder creates -by specifying `visibility` option. Valid options are `public`, `private` and -`internal`. `internal` options is for GitHub Enterprise clients, which means -public within the organization. +#### Azure DevOps + +For Azure DevOps we support both the preparer and publisher stage with the +configuration of a private access token (PAT). For the publisher it's also +required to define the base URL for the client to connect to the service. This +will hopefully support on-prem installations as well but that has not been +verified. + +```yaml +scaffolder: + azure: + baseUrl: https://dev.azure.com/{your-organization} + api: + token: + $secret: + env: AZURE_PRIVATE_TOKEN +``` ### Running the Backend diff --git a/docs/features/techdocs/FAQ.md b/docs/features/techdocs/FAQ.md index 5d6c9136d9..e81e9d82c7 100644 --- a/docs/features/techdocs/FAQ.md +++ b/docs/features/techdocs/FAQ.md @@ -11,14 +11,15 @@ This page answers frequently asked questions about [TechDocs](README.md). - [What static site generator is TechDocs using?](#what-static-site-generator-is-techdocs-using) - [What is the mkdocs-techdocs-core plugin?](#what-is-the-mkdocs-techdocs-core-plugin) -- [Does TechDocs support file formats other than Markdown (e.g. rst, asciidoc)?](#does-techdocs-support-file-formats-other-than-markdown-eg-rst-asciidoc-) +- [Does TechDocs support file formats other than Markdown (e.g. RST, AsciiDoc)?](#does-techdocs-support-file-formats-other-than-markdown-eg-rst-asciidoc-) #### What static site generator is TechDocs using? TechDocs is using [MkDocs](https://www.mkdocs.org/) to build project documentation under the hood. Documentation built with the [techdocs-container](https://github.com/spotify/backstage/blob/master/packages/techdocs-container/README.md) -is using the MkDocs Material Theme. +is using the MkDocs +[Material Theme](https://github.com/squidfunk/mkdocs-material). #### What is the mkdocs-techdocs-core plugin? @@ -29,9 +30,9 @@ plugins (e.g. [MkDocs Monorepo Plugin](https://github.com/spotify/mkdocs-monorepo-plugin)) as well as a selection of Python Markdown extensions that TechDocs supports. -#### Does TechDocs support file formats other than Markdown (e.g. rst, asciidoc) ? +#### Does TechDocs support file formats other than Markdown (e.g. RST, AsciiDoc) ? Not right now. We are currently using MkDocs to generate the documentation from -source. So, they have to be in Markdown format. However, in future we want to -support other alternatives to MkDocs. That will make it possible to use other -file formats. +source, so the files have to be in Markdown format. However, in the future we +want to support other static site generators which will make it possible to use +other file formats. diff --git a/docs/features/techdocs/README.md b/docs/features/techdocs/README.md index aa97506edb..cec5b63cc7 100644 --- a/docs/features/techdocs/README.md +++ b/docs/features/techdocs/README.md @@ -33,16 +33,17 @@ about TechDocs and the philosophy in its ## Project roadmap -| Version | Description | -| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| [TechDocs V.0 ✅][v0] | Read docs in Backstage - Enable anyone to get a reader experience working in Backstage. [See V.0 Use Cases.](#techdocs-v0) | -| [TechDocs V.1 ✅][v1] | TechDocs end to end (alpha) - Alpha of TechDocs that you can use end to end - and contribute to. [See V.1 Use Cases.](#techdocs-v1) | -| [TechDocs V.2 🔮⌛][v2] | Platform stability and compatibility improvements. [See V.2 Use Cases.](#techdocs-v2) | -| TechDocs V.3 🔮⌛ | Widget Architecture - TechDocs widget architecture available, so the community can create their own customized features. | +| Version | Description | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [TechDocs V.0 ✅][v0] | Read docs in Backstage - Enable anyone to get a reader experience working in Backstage. [See V.0 Use Cases.](#techdocs-v0) | +| [TechDocs V.1 ✅][v1] | TechDocs end to end (alpha) - Alpha of TechDocs that you can use end to end - and contribute to. [See V.1 Use Cases.](#techdocs-v1) | +| [TechDocs V.2 🔮⌛][v2] | Easy adoption of TechDocs (whatever environment you have) [See V.2 Use Cases.](#techdocs-v2) | +| [TechDocs V.3 🔮⌛][v3] | Build a widget (plugin) framework so that contributors can easily contribute features to TechDocs - that others can use. [See V.3 Use Cases.](#techdocs-v3) | [v0]: https://github.com/spotify/backstage/milestone/15 [v1]: https://github.com/spotify/backstage/milestone/16 -[v2]: https://github.com/spotify/backstage/milestone/17 +[v2]: https://github.com/spotify/backstage/milestone/22 +[v3]: https://github.com/spotify/backstage/milestone/17 @@ -59,26 +60,39 @@ about TechDocs and the philosophy in its - As a user I can run TechDocs locally and read documentation. - As a user I can create a docs folder in my entity project and add a reference in the entity configuration file (of the owning entity) to my documentation. - - Backstage will automatically build my documentation and serve it in - TechDocs. - - Documentation will be displayed under the docs tab in the service catalog. +- Backstage will automatically build my documentation and serve it in TechDocs. +- Documentation will be displayed under the docs tab in the service catalog. - As a user I can create a docs only repository that will be standalone from any other service. - As a user I can choose my own storage solution for the documentation (as example GCS/AWS/Azure etc) - As a user I can define my own API to interface my own documentation solution. -#### TechDocs V.2 - -Platform stability and compatibility improvements +Extra platform stability and compatibility improvements: - As a user I can define the metadata generated for my documentation. - As a user I will be able to browse metadata from within my documentation in Backstage. +#### TechDocs V.2 + +We have a TechDocs that works end-to-end. The next step is to make it super easy +for companies to adopt. This involves (something like) the following work items. + +- “Solidify” work and “Mkdocs stabilization” work that has come out of our Q3 + end-to-end work. +- Improve/simplify the get up and running process. +- Introduce doc template Software Templates. +- Enable companies to choose their own storage (S3 for example). +- Enable companies to choose their own source code hosting provider (GitHub, + GitLab, and so). +- Share how to plug in TechDocs to your own CI. + #### TechDocs V.3 -more to come... +Build a widget (plugin) framework so that contributors can easily contribute +features to TechDocs - that others can use. And, also, so that we can easily +migrate Spotify's existing TechDocs features to open source. ## Structure diff --git a/docs/features/techdocs/concepts.md b/docs/features/techdocs/concepts.md index f13f9933f5..13144f8df0 100644 --- a/docs/features/techdocs/concepts.md +++ b/docs/features/techdocs/concepts.md @@ -25,7 +25,14 @@ MkDocs. [TechDocs Container](https://github.com/spotify/backstage/blob/master/packages/techdocs-container/README.md) -### TechDocs publisher (coming soon) +### TechDocs publisher + +The `techdocs-backend` plugin currently comes with one publisher - +`LocalPublish`. + +[TechDocs Backend](https://github.com/spotify/backstage/tree/master/plugins/techdocs-backend) + +More standalone publishers will come in the near future... ### TechDocs CLI diff --git a/docs/features/techdocs/getting-started.md b/docs/features/techdocs/getting-started.md index b9d215fd8a..2e5c8d000d 100644 --- a/docs/features/techdocs/getting-started.md +++ b/docs/features/techdocs/getting-started.md @@ -13,7 +13,7 @@ If you haven't setup Backstage already, start ## Installing TechDocs TechDocs is provided with the Backstage application by default. If you want to -set up TechDocs manually, keep follow the instructions below. +set up TechDocs manually, keep following the instructions below. ### Adding the package @@ -57,8 +57,8 @@ The default storage and request URLs: ```yaml techdocs: - storageUrl: http://localhost:7000/techdocs/static/docs - requestUrl: http://localhost:7000/techdocs/docs + storageUrl: http://localhost:7000/api/techdocs/static/docs + requestUrl: http://localhost:7000/api/techdocs/docs ``` If you want `techdocs-backend` to manage building and publishing, you want diff --git a/docs/features/techdocs/troubleshooting.md b/docs/features/techdocs/troubleshooting.md new file mode 100644 index 0000000000..3a9b2fcfd0 --- /dev/null +++ b/docs/features/techdocs/troubleshooting.md @@ -0,0 +1,10 @@ +--- +id: troubleshooting +title: Troubleshooting TechDocs +sidebar_label: Troubleshooting +description: Troubleshooting for TechDocs +--- + +- TechDocs will fail to clone your docs if you have a git config which overrides + the `https` protocol with `ssh` or something else. Make sure to remove your + git config locally when you try TechDocs. diff --git a/docs/getting-started/create-an-app.md b/docs/getting-started/create-an-app.md index 452e90add5..831e8af145 100644 --- a/docs/getting-started/create-an-app.md +++ b/docs/getting-started/create-an-app.md @@ -38,6 +38,34 @@ app-folder is the name that was provided when prompted. Inside that directory, it will generate all the files and folder structure needed for you to run your app. +### Troubleshooting + +The create app command doesn't always work as expected, this is a collection of +some of the commonly encountered issues and solutions. + +#### Couldn't find any versions for "file-saver" + +You may encounter the following error message: + +```text +Couldn't find any versions for "file-saver" that matches "eligrey-FileSaver.js-1.3.8.tar.gz-art-external" +``` + +This is likely because you have a globally configured NPM proxy, which breaks +the installation of the `material-table` dependency. This is a known issue and +being worked on in `material-table`, but for now you can work around it using +the following: + +```bash +NPM_CONFIG_REGISTRY=https://registry.npmjs.org npx @backstage/create-app +``` + +#### Can't find Python executable "python" + +The install process may also fail if no Python installation is available. Python +is commonly available in most systems already, but if it isn't you can head for +example [here](https://www.python.org/downloads/) to install it. + ### General folder structure Below is a simplified layout of the files and folders generated when creating an diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index a9ac770f90..4ca2f431a7 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -24,9 +24,11 @@ Requests towards this repo. Backstage provides the `@backstage/create-app` package to scaffold standalone instances of Backstage. You will need to have [NodeJS](https://nodejs.org/en/download/) Active LTS Release installed -(currently v12), and [yarn](https://classic.yarnpkg.com/en/docs/install). You -will also need to have [Docker](https://docs.docker.com/engine/install/) -installed to use some features like Software Templates and TechDocs. +(currently v12), [yarn](https://classic.yarnpkg.com/en/docs/install) and +[Python](https://www.python.org/downloads/) (although you likely have it +already). You will also need to have +[Docker](https://docs.docker.com/engine/install/) installed to use some features +like Software Templates and TechDocs. Using `npx` you can then run the following to create an app in a chosen subdirectory of your current working directory: diff --git a/docs/getting-started/running-backstage-locally.md b/docs/getting-started/running-backstage-locally.md index a0cf10998e..6e6c8b2733 100644 --- a/docs/getting-started/running-backstage-locally.md +++ b/docs/getting-started/running-backstage-locally.md @@ -42,7 +42,7 @@ of GitHub and run an initial build. ```bash # Start from your local development folder -git clone git@github.com:spotify/backstage.git +git clone --depth 1 git@github.com:spotify/backstage.git cd backstage # Fetch our dependencies and run an initial build diff --git a/docs/openapi/definitions/auth.yaml b/docs/openapi/definitions/auth.yaml index eb96d434c2..cb736fd2a9 100644 --- a/docs/openapi/definitions/auth.yaml +++ b/docs/openapi/definitions/auth.yaml @@ -6,10 +6,10 @@ info: **Provided by `@backstage/auth-backend`.** - The purpose of the Auth APIs in Backstage are to identify the user, and to provide a way for plugins + The purpose of the Auth APIs in Backstage are to identify the user, and to provide a way for plugins to request access to 3rd party services on behalf of that user. - The API is supplied with a list of providers - such as `Google` or `Github` - and will add the endpoints + The API is supplied with a list of providers - such as `Google` or `Github` - and will add the endpoints described below to each of those providers. Read more about [User Authentication and Authorization in Backstage](https://github.com/spotify/backstage/blob/master/docs/auth/overview.md). @@ -21,7 +21,7 @@ externalDocs: description: Backstage official documentation url: https://github.com/spotify/backstage/blob/master/docs/README.md servers: - - url: http://localhost:7000/auth/ + - url: http://localhost:7000/api/auth/ tags: - name: provider description: List of endpoints per provider diff --git a/docs/overview/architecture-overview.md b/docs/overview/architecture-overview.md index f2c6dad61f..8edf3e9e4c 100644 --- a/docs/overview/architecture-overview.md +++ b/docs/overview/architecture-overview.md @@ -4,6 +4,23 @@ title: Architecture overview description: Documentation on Architecture overview --- +## Terminology + +Backstage is constructed out of three parts. We separate Backstage in this way +because we see three groups of contributors that work with Backstage in three +different ways. + +- Core - Base functionality built by core developers in the open source project. +- App - The app is an instance of a Backstage app that is deployed and tweaked. + The app ties together core functionality with additional plugins. The app is + built and maintained by app developers, usually a productivity team within a + company. +- Plugins - Additional functionality to make your Backstage app useful for your + company. Plugins can be specific to a company or open sourced and reusable. At + Spotify we have over 100 plugins built by over 50 different teams. It has been + very powerful to get contributions from various infrastructure teams added + into a single unified developer experience. + ## Overview The following diagram shows how Backstage might look when deployed inside a diff --git a/docs/overview/architecture-terminology.md b/docs/overview/architecture-terminology.md deleted file mode 100644 index 092ca7fb01..0000000000 --- a/docs/overview/architecture-terminology.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -id: architecture-terminology -title: Architecture terminology -description: Documentation on Architecture terminology ---- - -Backstage is constructed out of three parts. We separate Backstage in this way -because we see three groups of contributors that work with Backstage in three -different ways. - -- Core - Base functionality built by core devs in the open source project. -- App - The app is an instance of a Backstage app that is deployed and tweaked. - The app ties together core functionality with additional plugins. The app is - built and maintained by app developers, usually a productivity team within a - company. -- Plugins - Additional functionality to make your Backstage app useful for your - company. Plugins can be specific to a company or open sourced and reusable. At - Spotify we have over 100 plugins built by over 50 different teams. It has been - very powerful to get contributions from various infrastructure teams added - into a single unified developer experience. diff --git a/docs/overview/background.md b/docs/overview/background.md index 486260bac3..aca46614c2 100644 --- a/docs/overview/background.md +++ b/docs/overview/background.md @@ -1,7 +1,8 @@ --- id: background title: The Spotify Story -description: Documentation on Background and Story behind making of Backstage +description: Backstage was born out of necessity at Spotify. We found that as we grew, our +infrastructure was becoming more fragmented, our engineers less productive. --- Backstage was born out of necessity at Spotify. We found that as we grew, our @@ -29,3 +30,9 @@ building a new microservice using an automated template in Backstage. Create, maintain, and find the documentation for all that software in Backstage. One place for everything. Accessible to everyone. + +Backstage was originally built by Spotify and then donated to the CNCF. +Backstage is currently in the Sandbox phase. Read the announcement +[here](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox). + + diff --git a/docs/overview/roadmap.md b/docs/overview/roadmap.md index d6c1d2d641..1c90916fb5 100644 --- a/docs/overview/roadmap.md +++ b/docs/overview/roadmap.md @@ -27,10 +27,11 @@ We have divided the project into three high-level _phases_: With a single catalog, Backstage makes it easy for a team to manage ten services — and makes it possible for your company to manage thousands of them. -- 🐇 **Phase 3:** Ecosystem (later) - Everyone's infrastructure stack is - different. By fostering a vibrant community of contributors we hope to provide - an ecosystem of Open Source plugins/integrations that allows you to pick the - tools that match your stack. +- 🐇 **Phase 3:** Ecosystem (ongoing, see + [Plugin Marketplace](https://backstage.io/plugins)) - Everyone's + infrastructure stack is different. By fostering a vibrant community of + contributors we hope to provide an ecosystem of Open Source + plugins/integrations that allows you to pick the tools that match your stack. ## Detailed roadmap @@ -53,31 +54,24 @@ guidelines to get started. it much easier to see how a plugin can be built that integrates with the Backstage Service Catalog. +- **[Kubernetes support](https://github.com/spotify/backstage/milestone/20)** - + Native support for Kubernetes, making it easier for developers to see and + manage their services running in k8s. + +- **[Helm charts](https://github.com/spotify/backstage/issues/2540)** - Provide + Helm charts for easy deployments of Backstage and its subsystems on + Kubernetes. + +- **[Backstage platform is stable](https://github.com/spotify/backstage/milestone/19)** - + The platform APIs and features are stable and can be depended on for + production use. After this plugins will require little to no maintenance. + - **Backstage Design System** - By providing design guidelines for common plugin layouts together, rich set of reusable UI components ([Storybook](https://backstage.io/storybook)) and Figma design resources. The Design System will make it easy to design and build plugins that are consistent across the platform -- supporting both developers and designers. -- **[TechDocs v1](https://github.com/spotify/backstage/milestone/16)** - Our - docs-like-code feature TechDocs working end to end. - -- **[Initial GraphQL API](https://github.com/spotify/backstage/milestone/13)** - - A GraphQL API will open up the rich metadata provided by Backstage in a single - query. Plugins can easily query this API as well as extend the model where - needed. - -- **Production deployments** - Provide instructions and default configurations - (e.g. through Helm charts) for easy deployments of Backstage and its - subsystems on Kubernetes. - -- **Cloud Cost Insights plugin (from Spotify)** - Spotify teams are fully - responsible for their own software, including the cost of the cloud resources - they use. By making our internal cost insights plugin available as open source - you will also be able to treat cost as an engineering problem, and make it - easy for your engineers to see their spend and where there's opportunity to - reduce waste. - - Further improvements to platform documentation ### Plugins @@ -96,10 +90,6 @@ Chances are that someone will jump in and help build it. ### Future work 🔮 -- **[Backstage platform is stable](https://github.com/spotify/backstage/milestone/19)** - - The platform APIs and features are stable and can be depended on for - production use. After this plugins will require little to no maintenance. - - **Deploy a product demo at `demo.backstage.io`** - Deploy a typical Backstage deployment available publicly so that people can click around and get a feel for the product without having to install anything. @@ -118,8 +108,16 @@ Chances are that someone will jump in and help build it. [AWS](https://github.com/spotify/backstage/issues/290), [Azure](https://github.com/spotify/backstage/issues/348) and others. +- **[Initial GraphQL API](https://github.com/spotify/backstage/milestone/13)** - + A GraphQL API will open up the rich metadata provided by Backstage in a single + query. Plugins can easily query this API as well as extend the model where + needed. + ### Completed milestones ✅ +- [Cost Insights plugin 💸](https://engineering.atspotify.com/2020/09/29/managing-clouds-from-the-ground-up-cost-engineering-at-spotify/) +- [Donate Backstage to the CNCF 🎉](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox) +- [TechDocs v1](https://backstage.io/blog/2020/09/08/announcing-tech-docs) - [Plugin marketplace](https://backstage.io/plugins) - [Improved and move documentation to backstage.io](https://backstage.io/docs/overview/what-is-backstage) - [Backstage Service Catalog (alpha)](https://backstage.io/blog/2020/06/22/backstage-service-catalog-alpha) diff --git a/docs/overview/support.md b/docs/overview/support.md index 6e00c17fab..12bc7cfaf9 100644 --- a/docs/overview/support.md +++ b/docs/overview/support.md @@ -13,10 +13,7 @@ description: Support and Community Details and Links - [FAQ](../FAQ.md) - Frequently Asked Questions - [Code of Conduct](../../CODE_OF_CONDUCT.md) - This is how we roll - [Blog](https://backstage.io/blog/) - Announcements and updates -- [Newsletter](https://mailchi.mp/spotify/backstage-community) +- [Newsletter](https://mailchi.mp/spotify/backstage-community) - Subscribe to + our email newsletter - Give us a star â­ī¸ - If you are using Backstage or think it is an interesting project, we would love a star â¤ī¸ - -Or, if you are an open source developer and are interested in joining our team, -please reach out to -[foss-opportunities@spotify.com ](mailto:foss-opportunities@spotify.com) diff --git a/docs/overview/what-is-backstage.md b/docs/overview/what-is-backstage.md index 0d16943c9b..3d41c714ee 100644 --- a/docs/overview/what-is-backstage.md +++ b/docs/overview/what-is-backstage.md @@ -1,7 +1,7 @@ --- id: what-is-backstage title: What is Backstage? -description: Backsatge is an open platform for building developer portals. +description: Backstage is an open platform for building developer portals. Powered by a centralized service catalog, Backstage restores order to your microservices and infrastructure --- @@ -33,7 +33,14 @@ Out of the box, Backstage includes: [open source plugins](https://github.com/spotify/backstage/tree/master/plugins) that further expand Backstage’s customizability and functionality -### Benefits +## Backstage and the CNCF + +Backstage is a CNCF Sandbox project. Read the announcement +[here](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox). + + + +## Benefits - For _engineering managers_, it allows you to maintain standards and best practices across the organization, and can help you manage your whole tech diff --git a/docs/plugins/existing-plugins.md b/docs/plugins/existing-plugins.md index c1fbda379a..3c1ccb6438 100644 --- a/docs/plugins/existing-plugins.md +++ b/docs/plugins/existing-plugins.md @@ -4,12 +4,15 @@ title: Existing plugins description: Lists of existing open source plugins --- -## Open source plugins +## The Plugin Marketplace -The full list of open source plugins can be found -[here](https://github.com/spotify/backstage/tree/master/plugins). +Open source plugins that you can add to your Backstage deployment can be found +at: -## Plugin gallery +https://backstage.io/plugins -TODO: In the future we would like to have something similar to -https://grafana.com/grafana/plugins +![](https://backstage.io/blog/assets/marketplace.png) + +## Links + +- [[blog] The Plugin Marketplace is open](https://backstage.io/blog/2020/09/30/plugin-marketplace) diff --git a/docs/plugins/index.md b/docs/plugins/index.md index 8a61aeee80..8836c1cd42 100644 --- a/docs/plugins/index.md +++ b/docs/plugins/index.md @@ -9,7 +9,7 @@ Backstage is a single-page application composed of a set of plugins. Our goal for the plugin ecosystem is that the definition of a plugin is flexible enough to allow you to expose pretty much any kind of infrastructure or software development tool as a plugin in Backstage. By following strong -[design guidelines](../dls/design.md) we ensure the the overall user experience +[design guidelines](../dls/design.md) we ensure the overall user experience stays consistent between plugins. ![plugin](../assets/my-plugin_screenshot.png) @@ -21,7 +21,7 @@ To create a plugin, follow the steps outlined [here](create-a-plugin.md). ## Suggesting a plugin If you start developing a plugin that you aim to release as open source, we -suggest that you create a new +suggest that you create a [new Issue](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). This helps the community know what plugins are in development. diff --git a/docs/plugins/proxying.md b/docs/plugins/proxying.md index 2f809ffd10..a691c7f0bc 100644 --- a/docs/plugins/proxying.md +++ b/docs/plugins/proxying.md @@ -23,7 +23,7 @@ const proxyEnv = useHotMemoize(module, () => createEnv('proxy')); const service = createServiceBuilder(module) .loadConfig(configReader) /** ... other routers ... */ - .addRouter('/proxy', await proxy(proxyEnv, '/proxy')); + .addRouter('/proxy', await proxy(proxyEnv)); ``` ## Configuration @@ -49,7 +49,7 @@ Each key under the proxy configuration entry is a route to match, below the prefix that the proxy plugin is mounted on. It must start with a slash. For example, if the backend mounts the proxy plugin as `/proxy`, the above configuration will lead to the proxy acting on backend requests to -`/proxy/simple-example/...` and `/proxy/larger-example/v1/...`. +`/api/proxy/simple-example/...` and `/api/proxy/larger-example/v1/...`. The value inside each route is either a simple URL string, or an object on the format accepted by @@ -74,6 +74,6 @@ except with the following caveats for convenience: commonly useful value. - If `pathRewrite` is not specified, it is set to a single rewrite that removes the entire prefix and route. In the above example, a rewrite of - `'^/proxy/larger-example/v1/': '/'` is added. That means that a request to - `/proxy/larger-example/v1/some/path` will be translated to a request to + `'^/api/proxy/larger-example/v1/': '/'` is added. That means that a request to + `/api/proxy/larger-example/v1/some/path` will be translated to a request to `http://larger.example.com:8080/svc.v1/some/path`. diff --git a/docs/plugins/publishing.md b/docs/plugins/publishing.md index 0ed85e8cdc..fbeab6340c 100644 --- a/docs/plugins/publishing.md +++ b/docs/plugins/publishing.md @@ -21,6 +21,9 @@ out a new branch that you will use for the release, e.g. $ git checkout -b new-release ``` +First bump the `CHANGELOG.md` in the root of the repo and commit. You bump it by +adding a header for the new version just below the `## Next Release` one. + Then, from the root of the repo, run ```sh diff --git a/docs/plugins/structure-of-a-plugin.md b/docs/plugins/structure-of-a-plugin.md index f061d2f4a8..ee0a27cde2 100644 --- a/docs/plugins/structure-of-a-plugin.md +++ b/docs/plugins/structure-of-a-plugin.md @@ -84,7 +84,7 @@ structure our plugins. There are usually one or multiple page components and next to them you can split up the UI in as many components as you feel like. We have the `ExamplePage` to show an example Backstage page component. The -`ExampleFetchComponent` show cases the common task of making an async request to +`ExampleFetchComponent` showcases the common task of making an async request to a public API and plot the response data in a table using Material-UI components. You may tweak these components, rename them and/or replace them completely. diff --git a/docs/plugins/testing.md b/docs/plugins/testing.md index 696f8b1368..c6e1599786 100644 --- a/docs/plugins/testing.md +++ b/docs/plugins/testing.md @@ -32,7 +32,7 @@ working on. ## Naming Test Files -Tests should be name `[filename].test.js`. +Tests should be named `[filename].test.js`. For example, the tests for **`Link.js`** exist in the file **`Link.test.js`**. @@ -54,7 +54,7 @@ TODO. # Writing Unit Tests -The following principles are good guides to determining if you are writing high +The following principles are good guides for determining if you are writing high quality frontend unit tests. ## Bad Unit Test Principle @@ -166,11 +166,11 @@ because it fulfills all the principles above: ✓ **Fulfills Input/Output Principle**: Verifies the output changes when the input changes -✓ **Fufills Blackbox Principle**: Does not verify _how_ the `` +✓ **Fulfills Blackbox Principle**: Does not verify _how_ the `` component is mounted, just that it is mounted in response to the input. ✓ **Fulfills Scalability Principle**: If we decide to refactor the entire way -the loading indicator is displayed the test still works without touching it. +the loading indicator has displayed the test still works without touching it. ✓ **Fulfills Broken Functionality Principle**: this test verifies the functionality (displaying an indicator) is working, rather than how it is diff --git a/docs/reference/utility-apis/AlertApi.md b/docs/reference/utility-apis/AlertApi.md index d096276c3b..6219f520f5 100644 --- a/docs/reference/utility-apis/AlertApi.md +++ b/docs/reference/utility-apis/AlertApi.md @@ -73,7 +73,7 @@ Referenced by: [alert\$](#alert). ### Observer -This file contains non-react related core types used throught Backstage. +This file contains non-react related core types used through Backstage. Observer interface for consuming an Observer, see TC39. diff --git a/docs/reference/utility-apis/AppThemeApi.md b/docs/reference/utility-apis/AppThemeApi.md index d37282adea..eb35eb38ef 100644 --- a/docs/reference/utility-apis/AppThemeApi.md +++ b/docs/reference/utility-apis/AppThemeApi.md @@ -135,7 +135,7 @@ Referenced by: [activeThemeId\$](#activethemeid). ### Observer -This file contains non-react related core types used throught Backstage. +This file contains non-react related core types used through Backstage. Observer interface for consuming an Observer, see TC39. diff --git a/docs/reference/utility-apis/ErrorApi.md b/docs/reference/utility-apis/ErrorApi.md index 4de58b34a1..762d2016d5 100644 --- a/docs/reference/utility-apis/ErrorApi.md +++ b/docs/reference/utility-apis/ErrorApi.md @@ -93,7 +93,7 @@ Referenced by: [error\$](#error). ### Observer -This file contains non-react related core types used throught Backstage. +This file contains non-react related core types used through Backstage. Observer interface for consuming an Observer, see TC39. diff --git a/docs/reference/utility-apis/OAuthRequestApi.md b/docs/reference/utility-apis/OAuthRequestApi.md index ac11764682..1328aabeec 100644 --- a/docs/reference/utility-apis/OAuthRequestApi.md +++ b/docs/reference/utility-apis/OAuthRequestApi.md @@ -11,7 +11,8 @@ The following Utility API implements this type: ### createAuthRequester() A utility for showing login popups or similar things, and merging together -multiple requests for different scopes into one request that inclues all scopes. +multiple requests for different scopes into one request that includes all +scopes. The passed in options provide information about the login provider, and how to handle auth requests. @@ -30,7 +31,7 @@ createAuthRequester<AuthResponse>( ### authRequest\$() -Observers panding auth requests. The returned observable will emit all current +Observers pending auth requests. The returned observable will emit all current active auth request, at most one for each created auth requester. Each request has its own info about the login provider, forwarded from the auth @@ -156,7 +157,7 @@ Referenced by: [authRequest\$](#authrequest). ### Observer -This file contains non-react related core types used throught Backstage. +This file contains non-react related core types used through Backstage. Observer interface for consuming an Observer, see TC39. diff --git a/docs/reference/utility-apis/SessionApi.md b/docs/reference/utility-apis/SessionApi.md index 5e40b3317b..e7a9e58c59 100644 --- a/docs/reference/utility-apis/SessionApi.md +++ b/docs/reference/utility-apis/SessionApi.md @@ -81,7 +81,7 @@ Referenced by: [sessionState\$](#sessionstate). ### Observer -This file contains non-react related core types used throught Backstage. +This file contains non-react related core types used through Backstage. Observer interface for consuming an Observer, see TC39. diff --git a/docs/reference/utility-apis/SessionStateApi.md b/docs/reference/utility-apis/SessionStateApi.md index c1821f2381..81f25aa349 100644 --- a/docs/reference/utility-apis/SessionStateApi.md +++ b/docs/reference/utility-apis/SessionStateApi.md @@ -62,7 +62,7 @@ Referenced by: [sessionState\$](#sessionstate). ### Observer -This file contains non-react related core types used throught Backstage. +This file contains non-react related core types used through Backstage. Observer interface for consuming an Observer, see TC39. diff --git a/docs/reference/utility-apis/StorageApi.md b/docs/reference/utility-apis/StorageApi.md index 3fd75a42d6..e7d5131ff9 100644 --- a/docs/reference/utility-apis/StorageApi.md +++ b/docs/reference/utility-apis/StorageApi.md @@ -35,7 +35,7 @@ remove(key: string): Promise<void> ### set() -Save persistant data, and emit messages to anyone that is using observe\$ for +Save persistent data, and emit messages to anyone that is using observe\$ for this key
@@ -85,7 +85,7 @@ Referenced by: [observe\$](#observe), [StorageApi](#storageapi).
 
 ### Observer
 
-This file contains non-react related core types used throught Backstage.
+This file contains non-react related core types used through Backstage.
 
 Observer interface for consuming an Observer, see TC39.
 
@@ -129,7 +129,7 @@ export interface StorageApi {
   remove(key: string): Promise<void>;
 
   /**
-   * Save persistant data, and emit messages to anyone that is using observe$ for this key
+   * Save persistent data, and emit messages to anyone that is using observe$ for this key
    *
    * @param {String} key Unique key associated with the data.
    */
diff --git a/docs/tutorials/journey.md b/docs/tutorials/journey.md
index 24765e8531..908d7fc61b 100644
--- a/docs/tutorials/journey.md
+++ b/docs/tutorials/journey.md
@@ -134,7 +134,7 @@ work.
 # 5. The First User
 
 At this point the only things that anyone that wants to use Sam's plugin needs
-to do is to add
+to do are to add
 https://raw.githubusercontent.com/sam/backstage-spotify-theme/master/annotation.json#/sam.wise/spotify-track-id
 to their catalog schema, import and add the `PlayerWidget` on the desired entity
 template pages, and make sure they're providing Spotify auth.
@@ -145,7 +145,7 @@ select a theme tune when creating a new component. Sam jumps on the idea and
 adds a new creation hook that is exported by the plugin. The hook can be
 installed either in a single, all, or component templates that match a label. It
 adds a field as a part of the component creation process with a nice search box
-that allow users to search for a track that they want to use as the theme tune.
+that allows users to search for a track that they want to use as the theme tune.
 
 # 6. Return to the Repo
 
@@ -203,7 +203,7 @@ backend plugin also extends the common GraphQL schema with a mutation that
 updates the track ID in the database.
 
 On the frontend the Pull Request doesn't change much. It defines the save action
-the was previously using the `RepoApi` in it's own API.
+the was previously using the `RepoApi` in its own API.
 
 ```ts
 type ThemeTuneStorageApi = {
@@ -247,7 +247,7 @@ once an internal concern of the plugin is now becoming a standard in the
 community.
 
 In order to standardize the annotation in Backstage, Sam submits a Pull Request
-to the Backstage Core repo. The request suggest a new well-known metadata
+to the Backstage Core repo. The request suggests a new well-known metadata
 annotation called `spotify.com/track-id`, with the same schema definition as
 Sam's label, and refers to Sam's own plugin and the `spotify-album-art` plugin
 as existing usages. The Backstage maintainers merge the Pull Request, after
diff --git a/docs/tutorials/quickstart-app-auth.md b/docs/tutorials/quickstart-app-auth.md
index 82f9cab537..7403f2c2dd 100644
--- a/docs/tutorials/quickstart-app-auth.md
+++ b/docs/tutorials/quickstart-app-auth.md
@@ -11,10 +11,11 @@ title: Monorepo App Setup With Authentication
 > own environment. It starts with a skeleton install and verifying of the
 > monorepo's functionality. Next, GitHub authentication is added and tested.
 >
-> This document assumes you have NodeJS 12 active along with Yarn. Please note,
-> that at the time of this writing, the current version is 0.1.1-alpha.21. This
-> guide can still be used with future versions, just, verify as you go. If you
-> run into issues, you can compare your setup with mine here >
+> This document assumes you have NodeJS 12 active along with Yarn and Python.
+> Please note, that at the time of this writing, the current version is
+> 0.1.1-alpha.21. This guide can still be used with future versions, just,
+> verify as you go. If you run into issues, you can compare your setup with mine
+> here >
 > [simple-backstage-app](https://github.com/johnson-jesse/simple-backstage-app).
 
 # The Skeleton Application
@@ -115,7 +116,7 @@ export AUTH_GITHUB_CLIENT_SECRET=xxx
 > Log into http://github.com
 > Navigate to (Settings > Developer Settings > OAuth Apps > New OAuth App)[https://github.com/settings/applications/new]
 > Set Homepage URL = http://localhost:3000
-> Set Callback URL = http://localhost:7000/auth/github
+> Set Callback URL = http://localhost:7000/api/auth/github
 > Click [Register application]
 > On the next page, copy and paste your new Client ID and Client Secret to the environment variables above, `AUTH_GITHUB_CLIENT_ID` & `AUTH_GITHUB_CLIENT_SECRET`
 > Don't forget to `source` that profile file again if necessary.
@@ -155,39 +156,7 @@ const app = createApp({
 });
 ```
 
-6. Open and change _root > packages > app > src >_ `apis.ts` as follows
-
-```ts
-// Add the following imports to the existing list from core
-import { githubAuthApiRef, GithubAuth } from '@backstage/core';
-```
-
-7. In the same file, change the builder block for oauthRequestApiRef as follows
-
-_from:_
-
-```ts
-builder.add(oauthRequestApiRef, new OAuthRequestManager());
-```
-
-_to:_
-
-```ts
-const oauthRequestApi = builder.add(
-  oauthRequestApiRef,
-  new OAuthRequestManager(),
-);
-
-builder.add(
-  githubAuthApiRef,
-  GithubAuth.create({
-    discoveryApi,
-    oauthRequestApi,
-  }),
-);
-```
-
-8. Start the backend and frontend as before
+7. Start the backend and frontend as before
 
 When the browser loads, you should be presented with a login page for GitHub.
 Login as usual with your GitHub account. If this is your first time, you will be
diff --git a/docs/tutorials/quickstart-app-plugin.md b/docs/tutorials/quickstart-app-plugin.md
index 51a7f8ded6..9f571b0c9a 100644
--- a/docs/tutorials/quickstart-app-plugin.md
+++ b/docs/tutorials/quickstart-app-plugin.md
@@ -20,10 +20,11 @@ title: Adding Custom Plugin to Existing Monorepo App
 > functionality, extend the Sidebar to make our life easy. Finally, we add
 > custom code to display GitHub repository information.
 >
-> This document assumes you have NodeJS 12 active along with Yarn. Please note,
-> that at the time of this writing, the current version is 0.1.1-alpha.21. This
-> guide can still be used with future versions, just, verify as you go. If you
-> run into issues, you can compare your setup with mine here >
+> This document assumes you have NodeJS 12 active along with Yarn and Python.
+> Please note, that at the time of this writing, the current version is
+> 0.1.1-alpha.21. This guide can still be used with future versions, just,
+> verify as you go. If you run into issues, you can compare your setup with mine
+> here >
 > [simple-backstage-app-plugin](https://github.com/johnson-jesse/simple-backstage-app-plugin).
 
 # The Skeleton Plugin
@@ -210,7 +211,7 @@ type Viewer = {
 };
 ```
 
-# The Tabel Model
+# The Table Model
 
 Using Backstage's own component library, let's define a custom table. This
 component will get used if we have data to display.
@@ -312,6 +313,6 @@ return (
 > Break apart ExampleFetchComponent into smaller logical parts contained in
 > their own files. Rename your components to something other than ExampleXxx.
 >
-> You might be real proud of a plugin you develop. Follow this next tutorial for
-> an in-depth look at publishing and including that for the entire Backstage
+> You might be really proud of a plugin you develop. Follow this next tutorial
+> for an in-depth look at publishing and including that for the entire Backstage
 > community. [TODO](#).
diff --git a/microsite/.prettierignore b/microsite/.prettierignore
new file mode 100644
index 0000000000..378eac25d3
--- /dev/null
+++ b/microsite/.prettierignore
@@ -0,0 +1 @@
+build
diff --git a/microsite/blog/2020-09-30-backstage-design-system.md b/microsite/blog/2020-09-30-backstage-design-system.md
new file mode 100644
index 0000000000..4faea98782
--- /dev/null
+++ b/microsite/blog/2020-09-30-backstage-design-system.md
@@ -0,0 +1,107 @@
+---
+title: How to design for Backstage (even if you’re not a designer)
+author: Kat Zhou
+authorURL: http://twitter.com/katherinemzhou
+---
+
+![img](assets/backstage-DS-header.png)
+
+We are excited to launch the Backstage Design System, which includes a [Figma UI kit](https://www.figma.com/community/file/850673348101741100), a rich set of [reusable code components](http://backstage.io/storybook) on Storybook, and [Guidelines](https://backstage.io/docs/dls/design) for designers and developers as they build plugins for Backstage.
+
+
+
+## Not just the way it looks
+
+We see great design as one of the secret weapons of Backstage. Design should never be an afterthought — we believe an elegant, cohesive UX is vital to what makes Backstage such a productive, end-to-end development environment.
+
+Backstage keeps engineers from getting lost inside the complexity of your infrastructure by bringing order to your software ecosystem (through the [service catalog](https://backstage.io/blog/2020/06/22/backstage-service-catalog-alpha)) and providing an abstraction layer on top of it. How that abstraction layer works is essential to how Backstage works. So we’ve spent time figuring out how to make great design in Backstage easier to achieve for both designers and non-designers alike.
+
+Since making Backstage open source, we’ve been able to host design studios and user interviews with teams outside Spotify to get feedback and collaborate on a design system, together. (And we’re always keen on collaborating with more organizations.)
+
+![img](assets/Backstage-mural-DS.png)
+_Screenshot of our design studio for Backstage Search, which included stakeholders inside and outside of Spotify._
+
+As Backstage has gained traction, we’ve seen the importance of creating a scalable and coherent design system. It’s through the shared guidelines of our design system that we are able to maintain a unified ecosystem of plugins for our users, globally. Let’s get started by taking a closer look at the different design components of a plugin.
+
+## Anatomy of a plugin
+
+![](https://backstage.io/img/cards-plugins.png)
+
+Plugins are what provide the feature functionality in Backstage, allowing you to customize it to fit your infrastructure. They are integrated into Backstage's frontend, so that no matter what tool or service is being accessed, users are guaranteed a seamless experience.
+
+As you begin to [build your own plugins](https://backstage.io/docs/plugins/), we encourage you to explore the [open source plugins](https://backstage.io/plugins) we have available in Backstage, as reference. The anatomy of a plugin is simple. In the example below, we’ve highlighted a few of the standard components you should consider when designing your plugin.
+
+![img](assets/backstage-guide-DS.png)
+
+1. **Tabs.** Want to include multiple pages in your plugin? Use our tab component so users can easily navigate through your plugin.
+2. **Title.** Plugin pages should always have a title. Subheads are optional. Typically, the ‘star’ icon is included in the overview tab, which allows the user to favorite the plugin, adding it to the side navigation.
+3. **Cards.** Use the card components to display different kinds of content and functionality. You can follow our 12-column, responsive grid system to arrange the cards.
+4. **Support.** There should always be a support button (tertiary style, with icon). There can also be a primary action button as well as a secondary one.
+5. **Header.** Use the Backstage header to allow for users to easily understand what they’re looking at. You can include an optional subhead as well as other information. The color varies depending on the type of plugin you’ve built (stand-alone tool, service, app, website, etc.).
+
+Now that we’ve familiarized ourselves with the basic parts of a plugin, let’s take a look at some of the tools and resources that make designing plugins even easier.
+
+## Tools and resources
+
+The quickest way to start is by duplicating our [Figma UI kit](https://www.figma.com/community/file/850673348101741100), then clicking on the Create a Plugin page on the left-hand side to grab some templates. Feel free to experiment and play around! Figma is a fantastic, multiplayer tool that allows for designers and developers to co-create components and share specs with ease. We’re excited to see what you design and develop.
+
+As you’re designing and building your plugins, make sure to take advantage of these helpful resources.
+
+![img](assets/backstage-figma1-DS.png)
+![img](assets/backstage-figma2-ds.png)
+
+### [Figma Community](https://www.figma.com/@backstage)
+
+We are thrilled to be using [Figma Community](https://www.figma.com/@backstage) to share our design assets. You can duplicate our UI kit and design your own plugin for Backstage. Figma Community is currently in beta, so this is a neat opportunity to be testing out a new way of working. At the moment, it doesn’t support auto-updating of duplicated files, so we’ll be announcing new versions of our UI kit on Discord in the #design channel.
+
+![img](assets/backstage-storybook-ds.png)
+
+### [Storybook](https://backstage.io/storybook/)
+
+You can view (and grab) our [reusable components on Storybook](https://backstage.io/storybook/). If you’d like to help build up our design system, you can also help us add components that we’ve designed to Storybook as well. We post newly designed components and patterns to GitHub as issues, where contributors can pick them up and add them to our Storybook so they’re available for the rest of the Backstage community.
+
+![img](assets/backstage-guidelines-ds.png)
+
+### [Guidelines](https://backstage.io/docs/dls/design)
+
+To keep up with our latest design guidelines, go to [Designing for Backstage](https://backstage.io/docs/dls/design). You’ll find more how-to’s and you can also learn more about our design philosophy and practices there. Down the line, we plan on including more in-depth component rules in this section (i.e., dos/don’ts, use cases, etc.).
+
+![img](assets/backstage-github-ds.png)
+
+### [GitHub](https://github.com/spotify/backstage)
+
+Join in on the action [at spotify/backstage on GitHub](https://github.com/spotify/backstage) by submitting issues and opening pull requests for all things related to components and patterns in Backstage.
+
+![img](assets/backstage-discord-DS.png)
+
+### [Discord](https://discord.com/invite/MUpMjP2)
+
+All design questions should be directed to the [#design](https://discord.com/channels/687207715902193673/696709358544879716) channel in [Discord](https://discord.com/invite/MUpMjP2).
+
+## What's next for Backstage design
+
+There are a lot of exciting things that we’re envisioning for Backstage and open source design at Spotify. These include:
+
+- Expanding our Backstage Design System by building on the UI kit and component library in Figma and Storybook
+
+* Collaborating with more of our amazing contributors to ensure our Backstage Design System works for everyone
+
+* Featuring rad plugins that folks have created, using our design system, in our Figma Community space
+
+* Building up our Guidelines by continuing to creating robust design documentation
+
+* Ensuring that we maintain accessible practices throughout our experience
+
+![img](assets/backstage-world-DS.png)
+
+## Get involved
+
+Designing in the open needs to be democratic and participatory, which is why we invite you to join in on the fun! There are a couple things you can do to get involved, such as:
+
+- **Build with us!** Are there components/plugins that you’d like to see in Backstage? Feel free to create an example/prototype of what you’re envisioning and create a UX component issue in our GitHub repo.
+
+- **Chat with us!** If you have questions, ideas, or puppy GIFs, feel free to reach out to us on Discord in the #design channel.
+
+- **Share with us!** One of our priorities is making Backstage more accessible, and we need your help. If you’ve got A11Y insights and ideas on how we can improve our product, please let us know!
+
+- **Work with us!** We are hiring for product designers to work on Backstage. We strongly stand for breaking traditional pipelines and elevating our caliber by hiring the best folks who are underrepresented minorities in tech today. Keen on joining? Know someone who has a knack for open source design and design systems? Send a direct message to @katz on Discord!
diff --git a/microsite/blog/2020-09-30-plugin-marketplace.md b/microsite/blog/2020-09-30-plugin-marketplace.md
new file mode 100644
index 0000000000..b7a799097f
--- /dev/null
+++ b/microsite/blog/2020-09-30-plugin-marketplace.md
@@ -0,0 +1,43 @@
+---
+title: The Plugin Marketplace is open
+author: Stefan Ålund
+authorURL: https://twitter.com/stalund
+---
+
+Backstage has an ambitious goal: to provide engineers with the best possible developer experience.
+
+A great developer experience leads to happy, creative, and productive engineers. Our belief is that engineers should not have to be experts in various infrastructure tools or disciplines (e.g., machine learning or backend) to be productive. Infrastructure should be abstracted away, so that developers can spend more cycles building and testing, quickly and safely. Backstage unifies all your infrastructure tooling, services, and documentation to create a streamlined development environment from end to end.
+
+Now you may be thinking, “Yeah, sure, that sounds nice and all, but how does Backstage actually abstract away infrastructure?” The short answer: [plugins](https://backstage.io/plugins).
+
+![plugins](https://backstage.io/img/cards-plugins.png)
+
+
+
+Think of plugins as a mini version of an infrastructure tool or service — just the parts you need, made quick and easy. The advantage of using a Backstage plugin instead of a tool’s dedicated UI is that all your infrastructure is packaged into a “single pane of glass” instead of being spread out like independently built “islands”. Once you grow your infrastructure portfolio, the complexity really starts to add up. The Backstage plugin model allows you to add more tools without increasing the cognitive load for your users.
+
+Our goal for the plugin ecosystem is that anything can be a plugin. The definition of a plugin is flexible enough to allow you to expose pretty much any kind of infrastructure or software development tool as a plugin in Backstage. By following clear [design guidelines](https://backstage.io/blog/2020/09/30/backstage-design-system) we ensure the overall user experience stays consistent between plugins. If we all do our job well, the end user of Backstage does not see the boundaries between plugins. They are interacting with one consistent product — with many features.
+
+## Building an ecosystem
+
+Imagine a not-so-distant future where you walk up to Backstage, install it in your environment, and then choose from a gallery of existing, open source plugins that serve and match whatever infrastructure and software development needs you have inside your company. That means you can get started with Backstage and see the gains of improved productivity within days, not months. That is our vision for the Backstage plugin ecosystem.
+
+Running services on Kubernetes? There’s a plugin for that. Using Snyk for security scanning? There’s a plugin for that. Grafana, DataDog, or Rollbar for monitoring? There’s a plugin for that. Using Jenkins, CircleCI, GitHub Actions, or Travis CI? Pick the CI plugin of your choice. You get the picture. Regardless of your stack, there’s a plugin that you can use.
+
+Like this vision? So do we! But we can’t do it alone. We’ll need your help. For this vision to come true, we need to foster a community where many companies and individual developers build and contribute their plugins. Having been [accepted into the CNCF Sandbox](https://backstage.io/blog/2020/09/23/backstage-cncf-sandbox) provides us with the groundwork and guidance to broaden the community even faster.
+
+This grand vision is actually not that far off. Already today there is a growing ecosystem of Backstage plugins. To highlight all the amazing work that has been done by the community, and make it easier for Backstage adopters to see what plugins are available, we now have a Plugin Marketplace: [https://backstage.io/plugins](https://backstage.io/plugins)
+
+![marketplace](assets/marketplace.png)
+
+## Creating and suggesting new plugins
+
+Not all plugins you need will be open source. Every company has their own homegrown tooling. Building internal plugins lets you tailor your version of Backstage to be a perfect fit for your infrastructure and software development needs. If you end up [building plugins](https://backstage.io/docs/plugins/create-a-plugin) that could be useful for other companies, please consider releasing them as open source and [add them to the Marketplace](https://backstage.io/docs/plugins/add-to-marketplace).
+
+If you start developing a plugin that you aim to release as open source, we suggest that you create a [new plugin Issue](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME). This helps the community know what plugins are in development and opens up opportunities for collaboration. You can also use this process if you have an idea for a good plugin, but you need help building it.
+
+We are really excited to see all the amazing plugins that have already been built, and look forward to seeing even more ideas and collaboration as the Backstage community continues to grow.
+
+What plugins would you like to see in the Plugin Marketplace? [Tell us](https://github.com/spotify/backstage/issues/new?labels=plugin&template=plugin_template.md&title=%5BPlugin%5D+THE+PLUGIN+NAME)!
+
+_Special shout-out to community member [Iain Billett](https://github.com/iain-b) from Roadie for helping build and contribute the [Plugin Marketplace page](https://backstage.io/plugins) (as his first PR no less!)._
diff --git a/microsite/blog/assets/Backstage-mural-DS.png b/microsite/blog/assets/Backstage-mural-DS.png
new file mode 100644
index 0000000000..2944874706
Binary files /dev/null and b/microsite/blog/assets/Backstage-mural-DS.png differ
diff --git a/microsite/blog/assets/backstage-DS-header.png b/microsite/blog/assets/backstage-DS-header.png
new file mode 100644
index 0000000000..2160ef3229
Binary files /dev/null and b/microsite/blog/assets/backstage-DS-header.png differ
diff --git a/microsite/blog/assets/backstage-discord-DS.png b/microsite/blog/assets/backstage-discord-DS.png
new file mode 100644
index 0000000000..a0e513d7d8
Binary files /dev/null and b/microsite/blog/assets/backstage-discord-DS.png differ
diff --git a/microsite/blog/assets/backstage-figma1-DS.png b/microsite/blog/assets/backstage-figma1-DS.png
new file mode 100644
index 0000000000..00268eac2a
Binary files /dev/null and b/microsite/blog/assets/backstage-figma1-DS.png differ
diff --git a/microsite/blog/assets/backstage-figma2-ds.png b/microsite/blog/assets/backstage-figma2-ds.png
new file mode 100644
index 0000000000..d5e4fa7d9d
Binary files /dev/null and b/microsite/blog/assets/backstage-figma2-ds.png differ
diff --git a/microsite/blog/assets/backstage-github-ds.png b/microsite/blog/assets/backstage-github-ds.png
new file mode 100644
index 0000000000..6bd6bd976e
Binary files /dev/null and b/microsite/blog/assets/backstage-github-ds.png differ
diff --git a/microsite/blog/assets/backstage-guide-DS.png b/microsite/blog/assets/backstage-guide-DS.png
new file mode 100644
index 0000000000..8c0c7e7c2e
Binary files /dev/null and b/microsite/blog/assets/backstage-guide-DS.png differ
diff --git a/microsite/blog/assets/backstage-guidelines-ds.png b/microsite/blog/assets/backstage-guidelines-ds.png
new file mode 100644
index 0000000000..be5e9ff16f
Binary files /dev/null and b/microsite/blog/assets/backstage-guidelines-ds.png differ
diff --git a/microsite/blog/assets/backstage-storybook-ds.png b/microsite/blog/assets/backstage-storybook-ds.png
new file mode 100644
index 0000000000..aeff6650eb
Binary files /dev/null and b/microsite/blog/assets/backstage-storybook-ds.png differ
diff --git a/microsite/blog/assets/backstage-world-DS.png b/microsite/blog/assets/backstage-world-DS.png
new file mode 100644
index 0000000000..18e0da1425
Binary files /dev/null and b/microsite/blog/assets/backstage-world-DS.png differ
diff --git a/microsite/blog/assets/marketplace.png b/microsite/blog/assets/marketplace.png
new file mode 100644
index 0000000000..7681b436c7
Binary files /dev/null and b/microsite/blog/assets/marketplace.png differ
diff --git a/microsite/core/Footer.js b/microsite/core/Footer.js
index 761862c1fc..8e3c4c086d 100644
--- a/microsite/core/Footer.js
+++ b/microsite/core/Footer.js
@@ -51,6 +51,7 @@ class Footer extends React.Component {
             
               Subscribe to our newsletter
             
+            CNCF Sandbox
           
           
More
diff --git a/microsite/data/plugins/cloud-build.yaml b/microsite/data/plugins/cloud-build.yaml new file mode 100644 index 0000000000..cbd3a3cb6c --- /dev/null +++ b/microsite/data/plugins/cloud-build.yaml @@ -0,0 +1,13 @@ +--- +title: Google Cloud Build +author: Trivago +authorUrl: https://www.trivago.com +category: CI +description: Build, test, and deploy on Google's serverless CI/CD platform. +documentation: https://github.com/spotify/backstage/tree/master/plugins/cloudbuild +iconUrl: https://avatars2.githubusercontent.com/u/38220399?s=400&v=4 +npmPackageName: '@backstage/plugin-cloudbuild' +tags: + - ci + - cd + - test diff --git a/microsite/data/plugins/cost-insights.yaml b/microsite/data/plugins/cost-insights.yaml new file mode 100644 index 0000000000..7950879833 --- /dev/null +++ b/microsite/data/plugins/cost-insights.yaml @@ -0,0 +1,11 @@ +--- +title: Cost Insights +author: Spotify +authorUrl: https://github.com/spotify +category: Discovery +description: Visualize, understand and optimize your team's cloud costs. +documentation: https://github.com/spotify/backstage/tree/master/plugins/cost-insights +iconUrl: https://www.materialui.co/materialIcons/editor/monetization_on_white_192x192.png +npmPackageName: '@backstage/plugin-cost-insights' +tags: + - web diff --git a/microsite/data/plugins/firebase-functions.yaml b/microsite/data/plugins/firebase-functions.yaml new file mode 100644 index 0000000000..097ef00e50 --- /dev/null +++ b/microsite/data/plugins/firebase-functions.yaml @@ -0,0 +1,9 @@ +--- +title: Firebase Functions +author: roadie.io +authorUrl: https://roadie.io/ +category: Monitoring +description: View Firebase Functions details for your service in Backstage. +documentation: https://roadie.io/backstage/plugins/firebase-functions +iconUrl: https://roadie.io/static/49fb23200ad0eaa6703b4ddf75c78cf1/45f2b/logo-vertical.png +npmPackageName: '@roadiehq/backstage-plugin-firebase-functions' diff --git a/microsite/data/plugins/gcp-projects.yaml b/microsite/data/plugins/gcp-projects.yaml new file mode 100644 index 0000000000..7eff42af98 --- /dev/null +++ b/microsite/data/plugins/gcp-projects.yaml @@ -0,0 +1,13 @@ +--- +title: GCP Project Creator +author: Trivago +authorUrl: https://www.trivago.com +category: Cloud +description: Create, list and manage your Google Cloud Projects. +documentation: https://github.com/spotify/backstage/tree/master/plugins/gcp-projects +iconUrl: https://avatars1.githubusercontent.com/u/2810941?s=280&v=4 +npmPackageName: '@backstage/plugin-gcp-projects' +tags: + - cloud + - project + - resources diff --git a/microsite/package.json b/microsite/package.json index 734f1e4d49..335ada7212 100644 --- a/microsite/package.json +++ b/microsite/package.json @@ -7,13 +7,17 @@ "examples": "docusaurus-examples", "start": "docusaurus-start", "build": "docusaurus-build", + "prettier:check": "prettier --check .", "publish-gh-pages": "docusaurus-publish", "write-translations": "docusaurus-write-translations", "version": "docusaurus-version", "rename-version": "docusaurus-rename-version" }, "devDependencies": { - "docusaurus": "^2.0.0-alpha.64", - "js-yaml": "^3.14.0" - } + "@spotify/prettier-config": "^8.0.0", + "docusaurus": "^2.0.0-alpha.65", + "js-yaml": "^3.14.0", + "prettier": "^2.0.5" + }, + "prettier": "@spotify/prettier-config" } diff --git a/microsite/pages/en/demos.js b/microsite/pages/en/demos.js index d891e05613..c6657c6a31 100644 --- a/microsite/pages/en/demos.js +++ b/microsite/pages/en/demos.js @@ -216,7 +216,7 @@ const Background = props => { - + Manage data pipelines diff --git a/microsite/pages/en/plugins.js b/microsite/pages/en/plugins.js index 0ef8791970..a8255bcd0d 100644 --- a/microsite/pages/en/plugins.js +++ b/microsite/pages/en/plugins.js @@ -29,7 +29,7 @@ const Plugins = () => (
-

Plugin marketplace

+

Plugin Marketplace

Open source plugins that you can add to your Backstage deployment. Learn how to build a plugin. @@ -39,7 +39,7 @@ const Plugins = () => ( className="PluginAddNewButton ButtonFilled" href={addPluginDocsLink} > - Add to marketplace + Add to Marketplace

@@ -93,7 +93,7 @@ const Plugins = () => ( }} > - Add to marketplace + Add to Marketplace

diff --git a/microsite/sidebars.json b/microsite/sidebars.json index 8fa4935a38..7081e2bb1c 100644 --- a/microsite/sidebars.json +++ b/microsite/sidebars.json @@ -3,7 +3,6 @@ "Overview": [ "overview/what-is-backstage", "overview/architecture-overview", - "overview/architecture-terminology", "overview/roadmap", "overview/vision", "overview/background", @@ -43,6 +42,7 @@ "features/software-catalog/configuration", "features/software-catalog/system-model", "features/software-catalog/descriptor-format", + "features/software-catalog/references", "features/software-catalog/well-known-annotations", "features/software-catalog/extending-the-model", "features/software-catalog/external-integrations", @@ -71,6 +71,7 @@ "features/techdocs/concepts", "features/techdocs/architecture", "features/techdocs/creating-and-publishing", + "features/techdocs/troubleshooting", "features/techdocs/faqs" ] } @@ -158,7 +159,8 @@ "architecture-decisions/adrs-adr005", "architecture-decisions/adrs-adr006", "architecture-decisions/adrs-adr007", - "architecture-decisions/adrs-adr008" + "architecture-decisions/adrs-adr008", + "architecture-decisions/adrs-adr009" ], "Contribute": ["../CONTRIBUTING"], "Support": ["overview/support"], diff --git a/microsite/siteConfig.js b/microsite/siteConfig.js index d7a3bd67d0..d034321d6c 100644 --- a/microsite/siteConfig.js +++ b/microsite/siteConfig.js @@ -25,7 +25,7 @@ const siteConfig = { fossWebsite: 'https://spotify.github.io/', // Google Analytics - gaTrackingId: 'UA-48912878-10', + gaTrackingId: 'UA-163836834-5', // For no header links in the top nav bar -> headerLinks: [], headerLinks: [ diff --git a/microsite/static/css/custom.css b/microsite/static/css/custom.css index 79b8fd9de4..738478724f 100644 --- a/microsite/static/css/custom.css +++ b/microsite/static/css/custom.css @@ -844,6 +844,7 @@ code { width: 700px; margin: 20px auto; max-width: calc(100vw - 80px); + padding-bottom: 80px; } @media only screen and (max-width: 485px) { diff --git a/microsite/static/css/plugins.css b/microsite/static/css/plugins.css index a753e16047..9a8bbafa46 100644 --- a/microsite/static/css/plugins.css +++ b/microsite/static/css/plugins.css @@ -1,5 +1,5 @@ .PluginCard { - background-color: #272822; + background-color: #282828; height: 100%; padding: 16px; display: flex; @@ -53,13 +53,12 @@ .ButtonFilled { padding: 4px 8px; border-radius: 4px; - background-color: #36baa2; - color: white; + color: #69ddc7; margin-top: 36px; } .ButtonFilled:hover { - border: 1px solid #36baa2; + border: 1px solid #69ddc7; background-color: transparent; } @@ -67,8 +66,8 @@ font-size: small; border-radius: 16px; padding: 2px 8px; - border: 1px solid #36baa2; - color: #36baa2; + border: 1px solid #69ddc7; + color: #69ddc7; } .PluginCardLink { @@ -112,5 +111,5 @@ } #add-plugin-card { - border: 1px solid #36baa2; + border: 1px solid #69ddc7; } diff --git a/microsite/yarn.lock b/microsite/yarn.lock index 84b5d50d60..40e46c3545 100644 --- a/microsite/yarn.lock +++ b/microsite/yarn.lock @@ -959,6 +959,11 @@ resolved "https://registry.npmjs.org/@sindresorhus/is/-/is-0.7.0.tgz#9a06f4f137ee84d7df0460c1fdb1135ffa6c50fd" integrity sha512-ONhaKPIufzzrlNbqtWFFd+jlnemX6lJAgq9ZeiZtS7I1PIf/la7CW4m83rTXRnVnsMbW2k56pGYu7AUFJD9Pow== +"@spotify/prettier-config@^8.0.0": + version "8.0.0" + resolved "https://registry.npmjs.org/@spotify/prettier-config/-/prettier-config-8.0.0.tgz#8b6c2bd579ddc54887155a0721fe04e96c89f7f2" + integrity sha512-so8w32ZV42CHWxOEXcBtbNO/hLXFrQNXVmhfzhUI6dVB9cq2xjRaiqu8GjFj8LvKbWpPj+S+KwTIS4aDVWqrFQ== + "@types/cheerio@^0.22.8": version "0.22.21" resolved "https://registry.npmjs.org/@types/cheerio/-/cheerio-0.22.21.tgz#5e37887de309ba11b2e19a6e14cad7874b31a8a3" @@ -2228,10 +2233,10 @@ dir-glob@2.0.0: arrify "^1.0.1" path-type "^3.0.0" -docusaurus@^2.0.0-alpha.64: - version "2.0.0-alpha.64" - resolved "https://registry.yarnpkg.com/docusaurus/-/docusaurus-2.0.0-alpha.64.tgz#7833960e9d338403894a27b79058aa4076a676d3" - integrity sha512-ARCx0GwAvc5qx7AHvRVZidZuoDTfaaGXzgmkU23NahU6jzO/aK2Q1bH8IKNEQ5C2JuDerQ/hHDh80N20ijk82g== +docusaurus@^2.0.0-alpha.65: + version "2.0.0-alpha.65" + resolved "https://registry.yarnpkg.com/docusaurus/-/docusaurus-2.0.0-alpha.65.tgz#e2b84985529deb79797aff52aa39ffbe03cd8a20" + integrity sha512-OEnKbXLPy3EpbQA/Dj0kakB6fg/Qni1LORTIero+5Q5G0QT5OH4FAbBQOy3L1qQH0S5Bv18zESxX9Nvclg20ag== dependencies: "@babel/core" "^7.9.0" "@babel/plugin-proposal-class-properties" "^7.8.3" @@ -5199,6 +5204,11 @@ prepend-http@^2.0.0: resolved "https://registry.npmjs.org/prepend-http/-/prepend-http-2.0.0.tgz#e92434bfa5ea8c19f41cdfd401d741a3c819d897" integrity sha1-6SQ0v6XqjBn0HN/UAddBo8gZ2Jc= +prettier@^2.0.5: + version "2.1.2" + resolved "https://registry.npmjs.org/prettier/-/prettier-2.1.2.tgz#3050700dae2e4c8b67c4c3f666cdb8af405e1ce5" + integrity sha512-16c7K+x4qVlJg9rEbXl7HEGmQyZlG4R9AgP+oHKRMsMsuk8s+ATStlf1NpDqyBI1HpVyfjLOeMhH2LvuNvV5Vg== + prismjs@^1.17.1: version "1.21.0" resolved "https://registry.npmjs.org/prismjs/-/prismjs-1.21.0.tgz#36c086ec36b45319ec4218ee164c110f9fc015a3" diff --git a/mkdocs.yml b/mkdocs.yml index ba607f8a6e..4fbec4650d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -5,7 +5,6 @@ nav: - Overview: - What is Backstage?: 'overview/what-is-backstage.md' - Backstage architecture: 'overview/architecture-overview.md' - - Architecture and terminology: 'overview/architecture-terminology.md' - Roadmap: 'overview/roadmap.md' - Vision: 'overview/vision.md' - The Spotify story: 'overview/background.md' @@ -32,6 +31,7 @@ nav: - Configuration: 'features/software-catalog/configuration.md' - System model: 'features/software-catalog/system-model.md' - YAML File Format: 'features/software-catalog/descriptor-format.md' + - Entity References: 'features/software-catalog/references.md' - Well-known Annotations: 'features/software-catalog/well-known-annotations.md' - Extending the model: 'features/software-catalog/extending-the-model.md' - External integrations: 'features/software-catalog/external-integrations.md' @@ -51,6 +51,7 @@ nav: - Concepts: 'features/techdocs/concepts.md' - TechDocs Architecture: 'features/techdocs/architecture.md' - Creating and Publishing Documentation: 'features/techdocs/creating-and-publishing.md' + - Troubleshooting: 'features/techdocs/troubleshooting.md' - FAQ: 'features/techdocs/FAQ.md' - Plugins: - Overview: 'plugins/index.md' @@ -104,6 +105,7 @@ nav: - ADR006 - Avoid React.FC and React.SFC: 'architecture-decisions/adr006-avoid-react-fc.md' - ADR007 - Use MSW for Network Request Mocking: 'architecture-decisions/adr007-use-msw-to-mock-service-requests.md' - ADR008 - Default Catalog File Name: 'architecture-decisions/adr008-default-catalog-file-name.md' + - ADR009 - Entity References: 'architecture-decisions/adr009-entity-references.md' - Contribute: '../CONTRIBUTING.md' - Support: 'overview/support.md' - FAQ: FAQ.md diff --git a/package.json b/package.json index 3a77fe6880..b9c84a4d90 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "root", "private": true, "engines": { - "node": "12" + "node": "12 || 14" }, "scripts": { "dev": "concurrently \"yarn start\" \"yarn start-backend\"", @@ -16,6 +16,7 @@ "test": "lerna run test --since origin/master -- --coverage", "test:all": "lerna run test -- --coverage", "lint": "lerna run lint --since origin/master --", + "lint:docs": "node ./scripts/check-docs-quality", "lint:all": "lerna run lint --", "lint:type-deps": "node scripts/check-type-dependencies.js", "docgen": "lerna run docgen", @@ -46,7 +47,8 @@ "lerna": "^3.20.2", "lint-staged": "^10.1.0", "prettier": "^2.0.5", - "recursive-readdir": "^2.2.2" + "recursive-readdir": "^2.2.2", + "shx": "^0.3.2" }, "husky": { "hooks": { @@ -61,6 +63,9 @@ ], "*.{json,md}": [ "prettier --write" + ], + "*.md": [ + "vale" ] }, "jest": { diff --git a/packages/app/package.json b/packages/app/package.json index 77b1882b47..2373887cc6 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -10,6 +10,8 @@ "@backstage/plugin-api-docs": "^0.1.1-alpha.23", "@backstage/plugin-catalog": "^0.1.1-alpha.23", "@backstage/plugin-circleci": "^0.1.1-alpha.23", + "@backstage/plugin-cloudbuild": "^0.1.1-alpha.23", + "@backstage/plugin-cost-insights": "^0.1.1-alpha.23", "@backstage/plugin-explore": "^0.1.1-alpha.23", "@backstage/plugin-gcp-projects": "^0.1.1-alpha.23", "@backstage/plugin-github-actions": "^0.1.1-alpha.23", @@ -32,7 +34,7 @@ "@material-ui/icons": "^4.9.1", "@octokit/rest": "^18.0.0", "@roadiehq/backstage-plugin-github-pull-requests": "0.3.0", - "@roadiehq/backstage-plugin-travis-ci": "^0.1.4", + "@roadiehq/backstage-plugin-travis-ci": "^0.2.3", "history": "^5.0.0", "prop-types": "^15.7.2", "react": "^16.12.0", diff --git a/packages/app/src/App.test.tsx b/packages/app/src/App.test.tsx index cddd093855..40c49416bf 100644 --- a/packages/app/src/App.test.tsx +++ b/packages/app/src/App.test.tsx @@ -31,7 +31,7 @@ describe('App', () => { baseUrl: 'http://localhost:3003', }, techdocs: { - storageUrl: 'http://localhost:7000/techdocs/static/docs', + storageUrl: 'http://localhost:7000/api/techdocs/static/docs', }, }, context: 'test', diff --git a/packages/app/src/apis.ts b/packages/app/src/apis.ts index 7f57f6f970..c129bebfa2 100644 --- a/packages/app/src/apis.ts +++ b/packages/app/src/apis.ts @@ -16,11 +16,8 @@ import { errorApiRef, - discoveryApiRef, - UrlPatternDiscovery, githubAuthApiRef, createApiFactory, - configApiRef, } from '@backstage/core'; import { @@ -32,21 +29,16 @@ import { TravisCIApi, travisCIApiRef, } from '@roadiehq/backstage-plugin-travis-ci'; + import { GithubPullRequestsClient, githubPullRequestsApiRef, } from '@roadiehq/backstage-plugin-github-pull-requests'; +import { costInsightsApiRef } from '@backstage/plugin-cost-insights'; +import { ExampleCostInsightsClient } from './plugins/cost-insights'; + export const apis = [ - // TODO(Rugvip): migrate to use /api - createApiFactory({ - api: discoveryApiRef, - deps: { configApi: configApiRef }, - factory: ({ configApi }) => - UrlPatternDiscovery.compile( - `${configApi.getString('backend.baseUrl')}/{{ pluginId }}`, - ), - }), createApiFactory({ api: graphQlBrowseApiRef, deps: { errorApi: errorApiRef, githubAuthApi: githubAuthApiRef }, @@ -66,6 +58,8 @@ export const apis = [ ]), }), + createApiFactory(costInsightsApiRef, new ExampleCostInsightsClient()), + // TODO: move to plugins createApiFactory(travisCIApiRef, new TravisCIApi()), createApiFactory(githubPullRequestsApiRef, new GithubPullRequestsClient()), diff --git a/packages/app/src/components/Root/Root.tsx b/packages/app/src/components/Root/Root.tsx index 03e24cf4ae..45ffca7801 100644 --- a/packages/app/src/components/Root/Root.tsx +++ b/packages/app/src/components/Root/Root.tsx @@ -23,6 +23,7 @@ import RuleIcon from '@material-ui/icons/AssignmentTurnedIn'; import MapIcon from '@material-ui/icons/MyLocation'; import LibraryBooks from '@material-ui/icons/LibraryBooks'; import CreateComponentIcon from '@material-ui/icons/AddCircleOutline'; +import MoneyIcon from '@material-ui/icons/MonetizationOn'; import LogoFull from './LogoFull'; import LogoIcon from './LogoIcon'; import { @@ -94,6 +95,7 @@ const Root: FC<{}> = ({ children }) => ( + { // This component is just an example of how you can implement your company's logic in entity page. @@ -50,26 +60,61 @@ const CICDSwitcher = ({ entity }: { entity: Entity }) => { return ; case isCircleCIAvailable(entity): return ; + case isCloudbuildAvailable(entity): + return ; + case isTravisCIAvailable(entity): + return ; default: return ( - - No CI/CD is available for this entity. Check corresponding - annotations! - + + Read more + + } + /> ); } }; +const RecentCICDRunsSwitcher = ({ entity }: { entity: Entity }) => { + let content: ReactNode; + switch (true) { + case isJenkinsAvailable(entity): + content = ; + break; + case isGitHubActionsAvailable(entity): + content = ; + break; + case isTravisCIAvailable(entity): + content = ; + break; + default: + content = null; + } + if (!content) { + return null; + } + return ( + + {content} + + ); +}; + const OverviewContent = ({ entity }: { entity: Entity }) => ( - + - {isJenkinsAvailable(entity) && ( - - - - )} + ); diff --git a/packages/app/src/identityProviders.ts b/packages/app/src/identityProviders.ts index fab0e92577..388bc8d8b6 100644 --- a/packages/app/src/identityProviders.ts +++ b/packages/app/src/identityProviders.ts @@ -19,6 +19,7 @@ import { gitlabAuthApiRef, oktaAuthApiRef, githubAuthApiRef, + samlAuthApiRef, microsoftAuthApiRef, } from '@backstage/core'; @@ -53,4 +54,10 @@ export const providers = [ message: 'Sign In using Okta', apiRef: oktaAuthApiRef, }, + { + id: 'saml-auth-provider', + title: 'SAML', + message: 'Sign In using SAML', + apiRef: samlAuthApiRef, + }, ]; diff --git a/packages/app/src/plugins.ts b/packages/app/src/plugins.ts index aa68bc5fad..85c4977d67 100644 --- a/packages/app/src/plugins.ts +++ b/packages/app/src/plugins.ts @@ -34,3 +34,5 @@ export { plugin as ApiDocs } from '@backstage/plugin-api-docs'; export { plugin as GithubPullRequests } from '@roadiehq/backstage-plugin-github-pull-requests'; export { plugin as GcpProjects } from '@backstage/plugin-gcp-projects'; export { plugin as Kubernetes } from '@backstage/plugin-kubernetes'; +export { plugin as Cloudbuild } from '@backstage/plugin-cloudbuild'; +export { plugin as CostInsights } from '@backstage/plugin-cost-insights'; diff --git a/packages/app/src/plugins/cost-insights/ExampleCostInsightsClient.ts b/packages/app/src/plugins/cost-insights/ExampleCostInsightsClient.ts new file mode 100644 index 0000000000..c01092dc51 --- /dev/null +++ b/packages/app/src/plugins/cost-insights/ExampleCostInsightsClient.ts @@ -0,0 +1,209 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* eslint-disable no-restricted-imports */ + +import { + CostInsightsApi, + Alert, + Cost, + Duration, + Project, + ProductCost, + Group, +} from '@backstage/plugin-cost-insights'; + +export class ExampleCostInsightsClient implements CostInsightsApi { + private request(_: any, res: any): Promise { + return new Promise(resolve => setTimeout(resolve, 0, res)); + } + + async getUserGroups(userId: string): Promise { + const groups: Group[] = await this.request({ userId }, [ + { id: 'pied-piper' }, + ]); + + return groups; + } + + async getGroupProjects(group: string): Promise { + const projects: Project[] = await this.request({ group }, [ + { id: 'project-a' }, + { id: 'project-b' }, + { id: 'project-c' }, + ]); + + return projects; + } + + async getGroupDailyCost( + group: string, + metric: string | null, + intervals: string, + ): Promise { + const groupDailyCost: Cost = await this.request( + { group, metric, intervals }, + { + id: metric, // costs with null ids will appear as "All Projects" in Cost Overview panel + aggregation: [ + { date: '2020-08-01', amount: 75_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-02', amount: 120_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-03', amount: 110_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-04', amount: 90_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-05', amount: 80_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-06', amount: 85_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-07', amount: 82_500 / (metric ? 200_000 : 1) }, + { date: '2020-08-08', amount: 100_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-09', amount: 130_000 / (metric ? 200_000 : 1) }, + { date: '2020-08-10', amount: 140_000 / (metric ? 200_000 : 1) }, + ], + change: { + ratio: 0.86, + amount: 65_000, + }, + trendline: { + slope: 0, + intercept: 90_000, + }, + }, + ); + + return groupDailyCost; + } + + async getProjectDailyCost( + project: string, + metric: string | null, + intervals: string, + ): Promise { + const projectDailyCost: Cost = await this.request( + { project, metric, intervals }, + { + id: 'project-a', + aggregation: [ + { date: '2020-08-01', amount: 1000 }, + { date: '2020-08-02', amount: 2000 }, + { date: '2020-08-03', amount: 3000 }, + { date: '2020-08-04', amount: 4000 }, + { date: '2020-08-05', amount: 5000 }, + { date: '2020-08-06', amount: 6000 }, + { date: '2020-08-07', amount: 7000 }, + { date: '2020-08-08', amount: 8000 }, + { date: '2020-08-09', amount: 9000 }, + { date: '2020-08-10', amount: 10_000 }, + ], + change: { + ratio: 0.5, + amount: 10000, + }, + trendline: { + slope: 0, + intercept: 0, + }, + }, + ); + + return projectDailyCost; + } + + async getProductInsights( + product: string, + group: string, + duration: Duration, + ): Promise { + const productInsights: ProductCost = await this.request( + { product, group, duration }, + { + aggregation: [200_000, 250_000], + change: { + ratio: 0.2, + amount: 50_000, + }, + entities: [ + { + id: null, // entities with null ids will be appear as "Unlabeled" in product panels + aggregation: [45_000, 50_000], + }, + { + id: 'entity-a', + aggregation: [15_000, 20_000], + }, + { + id: 'entity-b', + aggregation: [20_000, 30_000], + }, + { + id: 'entity-c', + aggregation: [18_000, 25_000], + }, + { + id: 'entity-d', + aggregation: [36_000, 42_000], + }, + { + id: 'entity-e', + aggregation: [0, 10_000], + }, + { + id: 'entity-f', + aggregation: [17_000, 19_000], + }, + { + id: 'entity-g', + aggregation: [49_000, 30_000], + }, + { + id: 'entity-h', + aggregation: [0, 34_000], + }, + ], + }, + ); + + return productInsights; + } + + async getAlerts(group: string): Promise { + const alerts: Alert[] = await this.request({ group }, [ + { + id: 'projectGrowth', + project: 'example-project', + periodStart: 'Q1 2020', + periodEnd: 'Q2 2020', + aggregation: [60_000, 120_000], + change: { + ratio: 1, + amount: 60000, + }, + products: [ + { + id: 'Compute Engine', + aggregation: [58_000, 118_000], + }, + { + id: 'Cloud Dataflow', + aggregation: [1200, 1500], + }, + { + id: 'Cloud Storage', + aggregation: [800, 500], + }, + ], + }, + ]); + + return alerts; + } +} diff --git a/packages/app/src/plugins/cost-insights/index.ts b/packages/app/src/plugins/cost-insights/index.ts new file mode 100644 index 0000000000..47d540049f --- /dev/null +++ b/packages/app/src/plugins/cost-insights/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { ExampleCostInsightsClient } from './ExampleCostInsightsClient'; diff --git a/packages/backend-common/package.json b/packages/backend-common/package.json index 72f047761d..08b2cb71a0 100644 --- a/packages/backend-common/package.json +++ b/packages/backend-common/package.json @@ -39,11 +39,13 @@ "express": "^4.17.1", "express-prom-bundle": "^6.1.0", "express-promise-router": "^3.0.3", + "git-url-parse": "^11.2.0", "helmet": "^4.0.0", "knex": "^0.21.1", "lodash": "^4.17.15", "logform": "^2.1.1", "morgan": "^1.10.0", + "node-fetch": "^2.6.0", "prom-client": "^12.0.0", "selfsigned": "^1.10.7", "stoppable": "^1.1.0", @@ -62,6 +64,7 @@ "@types/compression": "^1.7.0", "@types/http-errors": "^1.6.3", "@types/morgan": "^1.9.0", + "@types/node-fetch": "^2.5.7", "@types/stoppable": "^1.1.0", "@types/supertest": "^2.0.8", "@types/webpack-env": "^1.15.2", @@ -70,6 +73,7 @@ "http-errors": "^1.7.3", "jest": "^26.0.1", "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", "supertest": "^4.0.2" }, "files": [ diff --git a/packages/backend-common/src/database/connection.ts b/packages/backend-common/src/database/connection.ts index 009a85239f..4cd8606fc0 100644 --- a/packages/backend-common/src/database/connection.ts +++ b/packages/backend-common/src/database/connection.ts @@ -17,7 +17,7 @@ import knex from 'knex'; import { Config } from '@backstage/config'; import { mergeDatabaseConfig } from './config'; -import { createPgDatabaseClient } from './postgres'; +import { createPgDatabaseClient, ensurePgDatabaseExists } from './postgres'; import { createSqliteDatabaseClient } from './sqlite3'; type DatabaseClient = 'pg' | 'sqlite3' | string; @@ -48,3 +48,19 @@ export function createDatabaseClient( * @deprecated Use createDatabaseClient instead */ export const createDatabase = createDatabaseClient; + +/** + * Ensures that the given databases all exist, creating them if they do not. + */ +export async function ensureDatabaseExists( + dbConfig: Config, + ...databases: Array +) { + const client: DatabaseClient = dbConfig.getString('client'); + + if (client === 'pg') { + return ensurePgDatabaseExists(dbConfig, ...databases); + } + + return undefined; +} diff --git a/packages/backend-common/src/database/postgres.ts b/packages/backend-common/src/database/postgres.ts index 03a74156c7..82e971f081 100644 --- a/packages/backend-common/src/database/postgres.ts +++ b/packages/backend-common/src/database/postgres.ts @@ -95,3 +95,39 @@ function requirePgConnectionString() { throw new Error(`${message}\n${e.message}`); } } + +/** + * Creates the missing Postgres database if it does not exist + * + * @param dbConfig The database config + * @param databases The name of the databases to create + */ +export async function ensurePgDatabaseExists( + dbConfig: Config, + ...databases: Array +) { + const admin = createPgDatabaseClient(dbConfig, { + connection: { + database: 'postgres', + }, + }); + + try { + const ensureDatabase = async (database: string) => { + const result = await admin + .from('pg_database') + .where('datname', database) + .count>(); + + if (parseInt(result[0].count, 10) > 0) { + return; + } + + await admin.raw(`CREATE DATABASE ??`, [database]); + }; + + await Promise.all(databases.map(ensureDatabase)); + } finally { + await admin.destroy(); + } +} diff --git a/packages/backend-common/src/discovery/SingleHostDiscovery.ts b/packages/backend-common/src/discovery/SingleHostDiscovery.ts new file mode 100644 index 0000000000..184746b924 --- /dev/null +++ b/packages/backend-common/src/discovery/SingleHostDiscovery.ts @@ -0,0 +1,83 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Config } from '@backstage/config'; +import { PluginEndpointDiscovery } from './types'; +import { readBaseOptions } from '../service/lib/config'; +import { DEFAULT_PORT } from '../service/lib/ServiceBuilderImpl'; + +/** + * SingleHostDiscovery is a basic PluginEndpointDiscovery implementation + * that assumes that all plugins are hosted in a single deployment. + * + * The deployment may be scaled horizontally, as long as the external URL + * is the same for all instances. However, internal URLs will always be + * resolved to the same host, so there won't be any balancing of internal traffic. + */ +export class SingleHostDiscovery implements PluginEndpointDiscovery { + /** + * Creates a new SingleHostDiscovery discovery instance by reading + * from the `backend` config section, specifically the `.baseUrl` for + * discovering the external URL, and the `.listen` and `.https` config + * for the internal one. + * + * The basePath defaults to `/api`, meaning the default full internal + * path for the `catalog` plugin will be `http://localhost:7000/api/catalog`. + */ + static fromConfig(config: Config, options?: { basePath?: string }) { + const basePath = options?.basePath ?? '/api'; + const externalBaseUrl = config.getString('backend.baseUrl'); + + const { listenHost = '::', listenPort = DEFAULT_PORT } = readBaseOptions( + config.getConfig('backend'), + ); + const protocol = config.has('backend.https') ? 'https' : 'http'; + + // Translate bind-all to localhost, and support IPv6 + let host = listenHost; + if (host === '::') { + // We use localhost instead of ::1, since IPv6-compatible systems should default + // to using IPv6 when they see localhost, but if the system doesn't support IPv6 + // things will still work. + host = 'localhost'; + } else if (host === '0.0.0.0') { + host = '127.0.0.1'; + } + if (host.includes(':')) { + host = `[${host}]`; + } + + const internalBaseUrl = `${protocol}://${host}:${listenPort}`; + + return new SingleHostDiscovery( + internalBaseUrl + basePath, + externalBaseUrl + basePath, + ); + } + + private constructor( + private readonly internalBaseUrl: string, + private readonly externalBaseUrl: string, + ) {} + + async getBaseUrl(pluginId: string): Promise { + return `${this.internalBaseUrl}/${pluginId}`; + } + + async getExternalBaseUrl(pluginId: string): Promise { + return `${this.externalBaseUrl}/${pluginId}`; + } +} diff --git a/packages/backend-common/src/discovery/index.ts b/packages/backend-common/src/discovery/index.ts new file mode 100644 index 0000000000..7fe320c1e5 --- /dev/null +++ b/packages/backend-common/src/discovery/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { SingleHostDiscovery } from './SingleHostDiscovery'; +export type { PluginEndpointDiscovery } from './types'; diff --git a/packages/backend-common/src/discovery/types.ts b/packages/backend-common/src/discovery/types.ts new file mode 100644 index 0000000000..22eb4b23d4 --- /dev/null +++ b/packages/backend-common/src/discovery/types.ts @@ -0,0 +1,61 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The PluginEndpointDiscovery is used to provide a mechanism for backend + * plugins to discover the endpoints for itself or other backend plugins. + * + * The purpose of the discovery API is to allow for many different deployment + * setups and routing methods through a central configuration, instead + * of letting each individual plugin manage that configuration. + * + * Implementations of the discovery API can be as simple as a URL pattern + * using the pluginId, but could also have overrides for individual plugins, + * or query a separate discovery service. + */ +export type PluginEndpointDiscovery = { + /** + * Returns the internal HTTP base URL for a given plugin, without a trailing slash. + * + * The returned URL should point to an internal endpoint for the plugin, with + * the shortest route possible. The URL should be used for service-to-service + * communication within a Backstage backend deployment. + * + * This method must always be called just before making a request, as opposed to + * fetching the URL when constructing an API client. That is to ensure that more + * flexible routing patterns can be supported. + * + * For example, asking for the URL for `catalog` may return something + * like `http://10.1.2.3/api/catalog` + */ + getBaseUrl(pluginId: string): Promise; + + /** + * Returns the external HTTP base backend URL for a given plugin, without a trailing slash. + * + * The returned URL should point to an external endpoint for the plugin, such that + * it is reachable from the Backstage frontend and other external services. The returned + * URL should be usable for example as a callback / webhook URL. + * + * The returned URL should be stable and in general not change unless other static + * or external configuration is changed. Changes should not come as a surprise + * to an operator of the Backstage backend. + * + * For example, asking for the URL for `catalog` may return something + * like `https://backstage.example.com/api/catalog` + */ + getExternalBaseUrl(pluginId: string): Promise; +}; diff --git a/packages/backend-common/src/index.ts b/packages/backend-common/src/index.ts index c527f5fea1..e968edef69 100644 --- a/packages/backend-common/src/index.ts +++ b/packages/backend-common/src/index.ts @@ -16,9 +16,11 @@ export * from './config'; export * from './database'; +export * from './discovery'; export * from './errors'; export * from './logging'; export * from './middleware'; +export * from './reading'; export * from './service'; export * from './paths'; export * from './hot'; diff --git a/packages/backend-common/src/reading/AzureUrlReader.test.ts b/packages/backend-common/src/reading/AzureUrlReader.test.ts new file mode 100644 index 0000000000..c9e1fc5bc7 --- /dev/null +++ b/packages/backend-common/src/reading/AzureUrlReader.test.ts @@ -0,0 +1,124 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rest } from 'msw'; +import { setupServer } from 'msw/node'; +import { ConfigReader } from '@backstage/config'; +import { getVoidLogger } from '../logging'; +import { AzureUrlReader } from './AzureUrlReader'; + +const logger = getVoidLogger(); + +describe('AzureUrlReader', () => { + const worker = setupServer(); + + beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); + afterAll(() => worker.close()); + + beforeEach(() => { + worker.use( + rest.get('*', (req, res, ctx) => + res( + ctx.status(200), + ctx.json({ + url: req.url.toString(), + headers: req.headers.getAllHeaders(), + }), + ), + ), + ); + }); + afterEach(() => worker.resetHandlers()); + + const createConfig = (token?: string) => + new ConfigReader( + { + integrations: { azure: [{ host: 'dev.azure.com', token }] }, + }, + 'test-config', + ); + + it.each([ + { + url: + 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', + config: createConfig(), + response: expect.objectContaining({ + url: + 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml&version=master', + }), + }, + { + url: + 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml', + config: createConfig(), + response: expect.objectContaining({ + url: + 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml', + }), + }, + { + url: 'https://dev.azure.com/a/b/_git/repo-name?path=my-template.yaml', + config: createConfig('0123456789'), + response: expect.objectContaining({ + headers: expect.objectContaining({ + authorization: 'Basic OjAxMjM0NTY3ODk=', + }), + }), + }, + { + url: 'https://dev.azure.com/a/b/_git/repo-name?path=my-template.yaml', + config: createConfig(undefined), + response: expect.objectContaining({ + headers: expect.not.objectContaining({ + authorization: expect.anything(), + }), + }), + }, + ])('should handle happy path %#', async ({ url, config, response }) => { + const [{ reader }] = AzureUrlReader.factory({ config, logger }); + + const data = await reader.read(url); + const res = await JSON.parse(data.toString('utf-8')); + expect(res).toEqual(response); + }); + + it.each([ + { + url: 'https://api.com/a/b/blob/master/path/to/c.yaml', + config: createConfig(), + error: + 'Incorrect url: https://api.com/a/b/blob/master/path/to/c.yaml, Error: Wrong Azure Devops URL or Invalid file path', + }, + { + url: 'com/a/b/blob/master/path/to/c.yaml', + config: createConfig(), + error: + 'Incorrect url: com/a/b/blob/master/path/to/c.yaml, TypeError: Invalid URL: com/a/b/blob/master/path/to/c.yaml', + }, + { + url: '', + config: createConfig(''), + error: + "Invalid type in config for key 'integrations.azure[0].token' in 'test-config', got empty-string, wanted string", + }, + ])('should handle error path %#', async ({ url, config, error }) => { + await expect(async () => { + const [{ reader }] = AzureUrlReader.factory({ config, logger }); + await reader.read(url); + }).rejects.toThrow(error); + }); +}); diff --git a/packages/backend-common/src/reading/AzureUrlReader.ts b/packages/backend-common/src/reading/AzureUrlReader.ts new file mode 100644 index 0000000000..28fbf25eea --- /dev/null +++ b/packages/backend-common/src/reading/AzureUrlReader.ts @@ -0,0 +1,165 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fetch, { RequestInit, HeadersInit, Response } from 'node-fetch'; +import { Config } from '@backstage/config'; +import { NotFoundError } from '../errors'; +import { ReaderFactory, UrlReader } from './types'; + +type Options = { + // TODO: added here for future support, but we only allow dev.azure.com for now + host: string; + token?: string; +}; + +function readConfig(config: Config): Options[] { + const optionsArr = Array(); + + const providerConfigs = + config.getOptionalConfigArray('integrations.azure') ?? []; + + for (const providerConfig of providerConfigs) { + const host = providerConfig.getOptionalString('host') ?? 'dev.azure.com'; + const token = providerConfig.getOptionalString('token'); + + optionsArr.push({ host, token }); + } + + // As a convenience we always make sure there's at least an unauthenticated + // reader for public azure repos. + if (!optionsArr.some(p => p.host === 'dev.azure.com')) { + optionsArr.push({ host: 'dev.azure.com' }); + } + + return optionsArr; +} + +export class AzureUrlReader implements UrlReader { + static factory: ReaderFactory = ({ config }) => { + return readConfig(config).map(options => { + const reader = new AzureUrlReader(options); + const predicate = (url: URL) => url.host === options.host; + return { reader, predicate }; + }); + }; + + constructor(private readonly options: Options) { + if (options.host !== 'dev.azure.com') { + throw Error( + `Azure integration currently only supports 'dev.azure.com', tried to use host '${options.host}'`, + ); + } + } + + async read(url: string): Promise { + const builtUrl = this.buildRawUrl(url); + + let response: Response; + try { + response = await fetch(builtUrl.toString(), this.getRequestOptions()); + } catch (e) { + throw new Error(`Unable to read ${url}, ${e}`); + } + + // for private repos when PAT is not valid, Azure API returns a http status code 203 with sign in page html + if (response.ok && response.status !== 203) { + return response.buffer(); + } + + const message = `${url} could not be read as ${builtUrl}, ${response.status} ${response.statusText}`; + if (response.status === 404) { + throw new NotFoundError(message); + } + throw new Error(message); + } + + // Converts + // from: https://dev.azure.com/{organization}/{project}/_git/reponame?path={path}&version=GB{commitOrBranch}&_a=contents + // to: https://dev.azure.com/{organization}/{project}/_apis/git/repositories/reponame/items?path={path}&version={commitOrBranch} + private buildRawUrl(target: string): URL { + try { + const url = new URL(target); + + const [ + empty, + userOrOrg, + project, + srcKeyword, + repoName, + ] = url.pathname.split('/'); + + const path = url.searchParams.get('path') || ''; + const ref = url.searchParams.get('version')?.substr(2); + + if ( + url.hostname !== 'dev.azure.com' || + empty !== '' || + userOrOrg === '' || + project === '' || + srcKeyword !== '_git' || + repoName === '' || + path === '' || + ref === '' + ) { + throw new Error('Wrong Azure Devops URL or Invalid file path'); + } + + // transform to api + url.pathname = [ + empty, + userOrOrg, + project, + '_apis', + 'git', + 'repositories', + repoName, + 'items', + ].join('/'); + + const queryParams = [`path=${path}`]; + + if (ref) { + queryParams.push(`version=${ref}`); + } + + url.search = queryParams.join('&'); + + url.protocol = 'https'; + + return url; + } catch (e) { + throw new Error(`Incorrect url: ${target}, ${e}`); + } + } + + private getRequestOptions(): RequestInit { + const headers: HeadersInit = {}; + + if (this.options.token) { + headers.Authorization = `Basic ${Buffer.from( + `:${this.options.token}`, + 'utf8', + ).toString('base64')}`; + } + + return { headers }; + } + + toString() { + const { host, token } = this.options; + return `azure{host=${host},authed=${Boolean(token)}}`; + } +} diff --git a/packages/backend-common/src/reading/BitbucketUrlReader.test.ts b/packages/backend-common/src/reading/BitbucketUrlReader.test.ts new file mode 100644 index 0000000000..c3e61fb821 --- /dev/null +++ b/packages/backend-common/src/reading/BitbucketUrlReader.test.ts @@ -0,0 +1,153 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rest } from 'msw'; +import { setupServer } from 'msw/node'; +import { ConfigReader } from '@backstage/config'; +import { getVoidLogger } from '../logging'; +import { BitbucketUrlReader } from './BitbucketUrlReader'; + +const logger = getVoidLogger(); + +describe('BitbucketUrlReader', () => { + const worker = setupServer(); + + beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); + afterAll(() => worker.close()); + + beforeEach(() => { + worker.use( + rest.get('*', (req, res, ctx) => + res( + ctx.status(200), + ctx.json({ + url: req.url.toString(), + headers: req.headers.getAllHeaders(), + }), + ), + ), + ); + }); + afterEach(() => worker.resetHandlers()); + + const createConfig = (username?: string, appPassword?: string) => + new ConfigReader( + { + integrations: { + bitbucket: [ + { + host: 'bitbucket.org', + username: username, + appPassword: appPassword, + }, + ], + }, + }, + 'test-config', + ); + + it.each([ + { + url: + 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', + config: createConfig(), + response: expect.objectContaining({ + url: + 'https://api.bitbucket.org/2.0/repositories/org-name/repo-name/src/master/templates/my-template.yaml', + }), + }, + { + url: + 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', + config: createConfig('some-user', 'my-secret'), + response: expect.objectContaining({ + headers: expect.objectContaining({ + authorization: 'Basic c29tZS11c2VyOm15LXNlY3JldA==', + }), + }), + }, + { + url: + 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', + config: createConfig(), + response: expect.objectContaining({ + headers: expect.not.objectContaining({ + authorization: expect.anything(), + }), + }), + }, + { + url: + 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', + config: createConfig(undefined, 'only-password-provided'), + response: expect.objectContaining({ + headers: expect.not.objectContaining({ + authorization: expect.anything(), + }), + }), + }, + ])('should handle happy path %#', async ({ url, config, response }) => { + const [{ reader }] = BitbucketUrlReader.factory({ config, logger }); + + const data = await reader.read(url); + const res = await JSON.parse(data.toString('utf-8')); + expect(res).toEqual(response); + }); + + it.each([ + { + url: 'https://api.com/a/b/blob/master/path/to/c.yaml', + config: createConfig(), + error: + 'Incorrect url: https://api.com/a/b/blob/master/path/to/c.yaml, Error: Wrong Bitbucket URL or Invalid file path', + }, + { + url: 'com/a/b/blob/master/path/to/c.yaml', + config: createConfig(), + error: + 'Incorrect url: com/a/b/blob/master/path/to/c.yaml, TypeError: Invalid URL: com/a/b/blob/master/path/to/c.yaml', + }, + { + url: '', + config: createConfig('', ''), + error: + "Invalid type in config for key 'integrations.bitbucket[0].username' in 'test-config', got empty-string, wanted string", + }, + { + url: '', + config: createConfig('only-user-provided', ''), + error: + "Invalid type in config for key 'integrations.bitbucket[0].appPassword' in 'test-config', got empty-string, wanted string", + }, + { + url: '', + config: createConfig('', 'only-password-provided'), + error: + "Invalid type in config for key 'integrations.bitbucket[0].username' in 'test-config', got empty-string, wanted string", + }, + { + url: '', + config: createConfig('only-user-provided', undefined), + error: + "Missing required config value at 'integrations.bitbucket[0].appPassword'", + }, + ])('should handle error path %#', async ({ url, config, error }) => { + await expect(async () => { + const [{ reader }] = BitbucketUrlReader.factory({ config, logger }); + await reader.read(url); + }).rejects.toThrow(error); + }); +}); diff --git a/packages/backend-common/src/reading/BitbucketUrlReader.ts b/packages/backend-common/src/reading/BitbucketUrlReader.ts new file mode 100644 index 0000000000..e2576eed47 --- /dev/null +++ b/packages/backend-common/src/reading/BitbucketUrlReader.ts @@ -0,0 +1,162 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fetch, { RequestInit, HeadersInit, Response } from 'node-fetch'; +import { Config } from '@backstage/config'; +import { ReaderFactory, UrlReader } from './types'; +import { NotFoundError } from '../errors'; + +type Options = { + // TODO: added here for future support, but we only allow bitbucket.org for now + host: string; + auth?: { + username: string; + appPassword: string; + }; +}; + +function readConfig(config: Config): Options[] { + const optionsArr = Array(); + + const providerConfigs = + config.getOptionalConfigArray('integrations.bitbucket') ?? []; + + for (const providerConfig of providerConfigs) { + const host = providerConfig.getOptionalString('host') ?? 'bitbucket.org'; + + let auth; + if (providerConfig.has('username')) { + const username = providerConfig.getString('username'); + const appPassword = providerConfig.getString('appPassword'); + auth = { username, appPassword }; + } + + optionsArr.push({ host, auth }); + } + + // As a convenience we always make sure there's at least an unauthenticated + // reader for public bitbucket repos. + if (!optionsArr.some(p => p.host === 'bitbucket.org')) { + optionsArr.push({ host: 'bitbucket.org' }); + } + + return optionsArr; +} + +export class BitbucketUrlReader implements UrlReader { + static factory: ReaderFactory = ({ config }) => { + return readConfig(config).map(options => { + const reader = new BitbucketUrlReader(options); + const predicate = (url: URL) => url.host === options.host; + return { reader, predicate }; + }); + }; + + constructor(private readonly options: Options) { + if (options.host !== 'bitbucket.org') { + throw Error( + `Bitbucket integration currently only supports 'bitbucket.org', tried to use host '${options.host}'`, + ); + } + } + + async read(url: string): Promise { + const builtUrl = this.buildRawUrl(url); + + let response: Response; + try { + response = await fetch(builtUrl.toString(), this.getRequestOptions()); + } catch (e) { + throw new Error(`Unable to read ${url}, ${e}`); + } + + if (response.ok) { + return response.buffer(); + } + + const message = `${url} could not be read as ${builtUrl}, ${response.status} ${response.statusText}`; + if (response.status === 404) { + throw new NotFoundError(message); + } + throw new Error(message); + } + + // Converts + // from: https://bitbucket.org/orgname/reponame/src/master/file.yaml + // to: https://api.bitbucket.org/2.0/repositories/orgname/reponame/src/master/file.yaml + private buildRawUrl(target: string): URL { + try { + const url = new URL(target); + + const [ + empty, + userOrOrg, + repoName, + srcKeyword, + ref, + ...restOfPath + ] = url.pathname.split('/'); + + if ( + url.hostname !== 'bitbucket.org' || + empty !== '' || + userOrOrg === '' || + repoName === '' || + srcKeyword !== 'src' + ) { + throw new Error('Wrong Bitbucket URL or Invalid file path'); + } + + // transform to api + url.pathname = [ + empty, + '2.0', + 'repositories', + userOrOrg, + repoName, + 'src', + ref, + ...restOfPath, + ].join('/'); + url.hostname = 'api.bitbucket.org'; + url.protocol = 'https'; + + return url; + } catch (e) { + throw new Error(`Incorrect url: ${target}, ${e}`); + } + } + + private getRequestOptions(): RequestInit { + const headers: HeadersInit = {}; + + if (this.options.auth) { + headers.Authorization = `Basic ${Buffer.from( + `${this.options.auth.username}:${this.options.auth.appPassword}`, + 'utf8', + ).toString('base64')}`; + } + + return { + headers, + }; + } + + toString() { + const { host, auth } = this.options; + return `bitbucket{host=${host},authed=${Boolean(auth)}}`; + } +} diff --git a/packages/backend-common/src/reading/FetchUrlReader.ts b/packages/backend-common/src/reading/FetchUrlReader.ts new file mode 100644 index 0000000000..ea56f2182d --- /dev/null +++ b/packages/backend-common/src/reading/FetchUrlReader.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fetch, { Response } from 'node-fetch'; +import { NotFoundError } from '../errors'; +import { UrlReader } from './types'; + +/** + * A UrlReader that does a plain fetch of the URL. + */ +export class FetchUrlReader implements UrlReader { + async read(url: string): Promise { + let response: Response; + try { + response = await fetch(url); + } catch (e) { + throw new Error(`Unable to read ${url}, ${e}`); + } + + if (response.ok) { + return response.buffer(); + } + + const message = `could not read ${url}, ${response.status} ${response.statusText}`; + if (response.status === 404) { + throw new NotFoundError(message); + } + throw new Error(message); + } + + toString() { + return 'fetch{}'; + } +} diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.test.ts b/packages/backend-common/src/reading/GithubUrlReader.test.ts similarity index 66% rename from plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.test.ts rename to packages/backend-common/src/reading/GithubUrlReader.test.ts index 3ab24541e7..8df464db9f 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.test.ts +++ b/packages/backend-common/src/reading/GithubUrlReader.test.ts @@ -14,23 +14,21 @@ * limitations under the License. */ -import { getVoidLogger } from '@backstage/backend-common'; -import { LocationSpec } from '@backstage/catalog-model'; import { ConfigReader } from '@backstage/config'; import { getApiRequestOptions, getApiUrl, getRawRequestOptions, getRawUrl, - GithubReaderProcessor, + GithubUrlReader, ProviderConfig, readConfig, -} from './GithubReaderProcessor'; +} from './GithubUrlReader'; -describe('GithubReaderProcessor', () => { +describe('GithubUrlReader', () => { describe('getApiRequestOptions', () => { it('sets the correct API version', () => { - const config: ProviderConfig = { target: '', apiBaseUrl: '' }; + const config: ProviderConfig = { host: '', apiBaseUrl: '' }; expect((getApiRequestOptions(config).headers as any).Accept).toEqual( 'application/vnd.github.v3.raw', ); @@ -38,12 +36,12 @@ describe('GithubReaderProcessor', () => { it('inserts a token when needed', () => { const withToken: ProviderConfig = { - target: '', + host: '', apiBaseUrl: '', token: 'A', }; const withoutToken: ProviderConfig = { - target: '', + host: '', apiBaseUrl: '', }; expect( @@ -58,12 +56,12 @@ describe('GithubReaderProcessor', () => { describe('getRawRequestOptions', () => { it('inserts a token when needed', () => { const withToken: ProviderConfig = { - target: '', + host: '', rawBaseUrl: '', token: 'A', }; const withoutToken: ProviderConfig = { - target: '', + host: '', rawBaseUrl: '', }; expect( @@ -77,13 +75,13 @@ describe('GithubReaderProcessor', () => { describe('getApiUrl', () => { it('rejects targets that do not look like URLs', () => { - const config: ProviderConfig = { target: '', apiBaseUrl: '' }; + const config: ProviderConfig = { host: '', apiBaseUrl: '' }; expect(() => getApiUrl('a/b', config)).toThrow(/Incorrect URL: a\/b/); }); it('happy path for github', () => { const config: ProviderConfig = { - target: 'https://github.com', + host: 'github.com', apiBaseUrl: 'https://api.github.com', }; expect( @@ -110,7 +108,7 @@ describe('GithubReaderProcessor', () => { it('happy path for ghe', () => { const config: ProviderConfig = { - target: 'https://ghe.mycompany.net', + host: 'ghe.mycompany.net', apiBaseUrl: 'https://ghe.mycompany.net/api/v3', }; expect( @@ -128,13 +126,13 @@ describe('GithubReaderProcessor', () => { describe('getRawUrl', () => { it('rejects targets that do not look like URLs', () => { - const config: ProviderConfig = { target: '', apiBaseUrl: '' }; + const config: ProviderConfig = { host: '', apiBaseUrl: '' }; expect(() => getRawUrl('a/b', config)).toThrow(/Incorrect URL: a\/b/); }); it('happy path for github', () => { const config: ProviderConfig = { - target: 'https://github.com', + host: 'github.com', rawBaseUrl: 'https://raw.githubusercontent.com', }; expect( @@ -151,7 +149,7 @@ describe('GithubReaderProcessor', () => { it('happy path for ghe', () => { const config: ProviderConfig = { - target: 'https://ghe.mycompany.net', + host: 'ghe.mycompany.net', rawBaseUrl: 'https://ghe.mycompany.net/raw', }; expect( @@ -167,23 +165,23 @@ describe('GithubReaderProcessor', () => { describe('readConfig', () => { function config( - providers: { target: string; apiBaseUrl?: string; token?: string }[], + providers: { host: string; apiBaseUrl?: string; token?: string }[], ) { return ConfigReader.fromConfigs([ { context: '', data: { - catalog: { processors: { github: { providers } } }, + integrations: { github: providers }, }, }, ]); } it('adds a default GitHub entry when missing', () => { - const output = readConfig(config([]), getVoidLogger()); + const output = readConfig(config([])); expect(output).toEqual([ { - target: 'https://github.com', + host: 'github.com', apiBaseUrl: 'https://api.github.com', rawBaseUrl: 'https://raw.githubusercontent.com', }, @@ -191,13 +189,10 @@ describe('GithubReaderProcessor', () => { }); it('injects the correct GitHub API base URL when missing', () => { - const output = readConfig( - config([{ target: 'https://github.com' }]), - getVoidLogger(), - ); + const output = readConfig(config([{ host: 'github.com' }])); expect(output).toEqual([ { - target: 'https://github.com', + host: 'github.com', apiBaseUrl: 'https://api.github.com', rawBaseUrl: 'https://raw.githubusercontent.com', }, @@ -205,64 +200,33 @@ describe('GithubReaderProcessor', () => { }); it('rejects custom targets with no base URLs', () => { - expect(() => - readConfig( - config([{ target: 'https://ghe.company.com' }]), - getVoidLogger(), - ), - ).toThrow( - 'Provider at https://ghe.company.com must configure an explicit apiBaseUrl or rawBaseUrl', + expect(() => readConfig(config([{ host: 'ghe.company.com' }]))).toThrow( + "GitHub integration for 'ghe.company.com' must configure an explicit apiBaseUrl and rawBaseUrl", ); }); it('rejects funky configs', () => { + expect(() => readConfig(config([{ host: 7 } as any]))).toThrow(/host/); + expect(() => readConfig(config([{ token: 7 } as any]))).toThrow(/token/); expect(() => - readConfig(config([{ target: 7 } as any]), getVoidLogger()), - ).toThrow(/target/); - expect(() => - readConfig(config([{ noTarget: '7' } as any]), getVoidLogger()), - ).toThrow(/target/); - expect(() => - readConfig( - config([{ target: 'https://github.com', apiBaseUrl: 7 } as any]), - getVoidLogger(), - ), + readConfig(config([{ host: 'github.com', apiBaseUrl: 7 } as any])), ).toThrow(/apiBaseUrl/); expect(() => - readConfig( - config([{ target: 'https://github.com', token: 7 } as any]), - getVoidLogger(), - ), + readConfig(config([{ host: 'github.com', token: 7 } as any])), ).toThrow(/token/); }); }); describe('implementation', () => { - it('rejects unknown types', async () => { - const processor = new GithubReaderProcessor([ - { target: 'https://github.com', apiBaseUrl: 'https://api.github.com' }, - ]); - const location: LocationSpec = { - type: 'not-github/api', - target: 'https://github.com', - }; - await expect( - processor.readLocation(location, false, () => {}), - ).resolves.toBeFalsy(); - }); - it('rejects unknown targets', async () => { - const processor = new GithubReaderProcessor([ - { target: 'https://github.com', apiBaseUrl: 'https://api.github.com' }, - ]); - const location: LocationSpec = { - type: 'github/api', - target: 'https://not.github.com/apa', - }; + const processor = new GithubUrlReader({ + host: 'github.com', + apiBaseUrl: 'https://api.github.com', + }); await expect( - processor.readLocation(location, false, () => {}), + processor.read('https://not.github.com/apa'), ).rejects.toThrow( - /There is no GitHub provider that matches https:\/\/not.github.com\/apa/, + 'Incorrect URL: https://not.github.com/apa, Error: Invalid GitHub URL or file path', ); }); }); diff --git a/packages/backend-common/src/reading/GithubUrlReader.ts b/packages/backend-common/src/reading/GithubUrlReader.ts new file mode 100644 index 0000000000..e5bed6dd26 --- /dev/null +++ b/packages/backend-common/src/reading/GithubUrlReader.ts @@ -0,0 +1,236 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Config } from '@backstage/config'; +import parseGitUri from 'git-url-parse'; +import fetch, { HeadersInit, RequestInit, Response } from 'node-fetch'; +import { NotFoundError } from '../errors'; +import { ReaderFactory, UrlReader } from './types'; + +/** + * The configuration parameters for a single GitHub API provider. + */ +export type ProviderConfig = { + /** + * The host of the target that this matches on, e.g. "github.com" + */ + host: string; + + /** + * The base URL of the API of this provider, e.g. "https://api.github.com", + * with no trailing slash. + * + * May be omitted specifically for GitHub; then it will be deduced. + * + * The API will always be preferred if both its base URL and a token are + * present. + */ + apiBaseUrl?: string; + + /** + * The base URL of the raw fetch endpoint of this provider, e.g. + * "https://raw.githubusercontent.com", with no trailing slash. + * + * May be omitted specifically for GitHub; then it will be deduced. + * + * The API will always be preferred if both its base URL and a token are + * present. + */ + rawBaseUrl?: string; + + /** + * The authorization token to use for requests to this provider. + * + * If no token is specified, anonymous access is used. + */ + token?: string; +}; + +export function getApiRequestOptions(provider: ProviderConfig): RequestInit { + const headers: HeadersInit = { + Accept: 'application/vnd.github.v3.raw', + }; + + if (provider.token) { + headers.Authorization = `token ${provider.token}`; + } + + return { + headers, + }; +} + +export function getRawRequestOptions(provider: ProviderConfig): RequestInit { + const headers: HeadersInit = {}; + + if (provider.token) { + headers.Authorization = `token ${provider.token}`; + } + + return { + headers, + }; +} + +// Converts for example +// from: https://github.com/a/b/blob/branchname/path/to/c.yaml +// to: https://api.github.com/repos/a/b/contents/path/to/c.yaml?ref=branchname +export function getApiUrl(target: string, provider: ProviderConfig): URL { + try { + const { owner, name, ref, filepathtype, filepath } = parseGitUri(target); + + if ( + !owner || + !name || + !ref || + (filepathtype !== 'blob' && filepathtype !== 'raw') + ) { + throw new Error('Invalid GitHub URL or file path'); + } + + const pathWithoutSlash = filepath.replace(/^\//, ''); + return new URL( + `${provider.apiBaseUrl}/repos/${owner}/${name}/contents/${pathWithoutSlash}?ref=${ref}`, + ); + } catch (e) { + throw new Error(`Incorrect URL: ${target}, ${e}`); + } +} + +// Converts for example +// from: https://github.com/a/b/blob/branchname/c.yaml +// to: https://raw.githubusercontent.com/a/b/branchname/c.yaml +export function getRawUrl(target: string, provider: ProviderConfig): URL { + try { + const { owner, name, ref, filepathtype, filepath } = parseGitUri(target); + + if ( + !owner || + !name || + !ref || + (filepathtype !== 'blob' && filepathtype !== 'raw') + ) { + throw new Error('Invalid GitHub URL or file path'); + } + + const pathWithoutSlash = filepath.replace(/^\//, ''); + return new URL( + `${provider.rawBaseUrl}/${owner}/${name}/${ref}/${pathWithoutSlash}`, + ); + } catch (e) { + throw new Error(`Incorrect URL: ${target}, ${e}`); + } +} + +export function readConfig(config: Config): ProviderConfig[] { + const providers: ProviderConfig[] = []; + + const providerConfigs = + config.getOptionalConfigArray('integrations.github') ?? []; + + // First read all the explicit providers + for (const providerConfig of providerConfigs) { + const host = providerConfig.getOptionalString('host') ?? 'github.com'; + let apiBaseUrl = providerConfig.getOptionalString('apiBaseUrl'); + let rawBaseUrl = providerConfig.getOptionalString('rawBaseUrl'); + const token = providerConfig.getOptionalString('token'); + + if (apiBaseUrl) { + apiBaseUrl = apiBaseUrl.replace(/\/+$/, ''); + } else if (host === 'github.com') { + apiBaseUrl = 'https://api.github.com'; + } + + if (rawBaseUrl) { + rawBaseUrl = rawBaseUrl.replace(/\/+$/, ''); + } else if (host === 'github.com') { + rawBaseUrl = 'https://raw.githubusercontent.com'; + } + + if (!apiBaseUrl && !rawBaseUrl) { + throw new Error( + `GitHub integration for '${host}' must configure an explicit apiBaseUrl and rawBaseUrl`, + ); + } + + providers.push({ host, apiBaseUrl, rawBaseUrl, token }); + } + + // If no explicit github.com provider was added, put one in the list as + // a convenience + if (!providers.some(p => p.host === 'github.com')) { + providers.push({ + host: 'github.com', + apiBaseUrl: 'https://api.github.com', + rawBaseUrl: 'https://raw.githubusercontent.com', + }); + } + + return providers; +} + +/** + * A processor that adds the ability to read files from GitHub v3 APIs, such as + * the one exposed by GitHub itself. + */ +export class GithubUrlReader implements UrlReader { + private config: ProviderConfig; + + static factory: ReaderFactory = ({ config }) => { + return readConfig(config).map(provider => { + const reader = new GithubUrlReader(provider); + const predicate = (url: URL) => url.host === provider.host; + return { reader, predicate }; + }); + }; + + constructor(config: ProviderConfig) { + this.config = config; + } + + async read(url: string): Promise { + const useApi = + this.config.apiBaseUrl && (this.config.token || !this.config.rawBaseUrl); + const ghUrl = useApi + ? getApiUrl(url, this.config) + : getRawUrl(url, this.config); + const options = useApi + ? getApiRequestOptions(this.config) + : getRawRequestOptions(this.config); + + let response: Response; + try { + response = await fetch(ghUrl.toString(), options); + } catch (e) { + throw new Error(`Unable to read ${url}, ${e}`); + } + + if (response.ok) { + return response.buffer(); + } + + const message = `${url} could not be read as ${ghUrl}, ${response.status} ${response.statusText}`; + if (response.status === 404) { + throw new NotFoundError(message); + } + throw new Error(message); + } + + toString() { + const { host, token } = this.config; + return `github{host=${host},authed=${Boolean(token)}}`; + } +} diff --git a/packages/backend-common/src/reading/GitlabUrlReader.test.ts b/packages/backend-common/src/reading/GitlabUrlReader.test.ts new file mode 100644 index 0000000000..09da9c4e0a --- /dev/null +++ b/packages/backend-common/src/reading/GitlabUrlReader.test.ts @@ -0,0 +1,122 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { rest } from 'msw'; +import { setupServer } from 'msw/node'; +import { ConfigReader } from '@backstage/config'; +import { getVoidLogger } from '../logging'; +import { GitlabUrlReader } from './GitlabUrlReader'; + +const logger = getVoidLogger(); + +describe('GitlabUrlReader', () => { + const worker = setupServer(); + + beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); + afterAll(() => worker.close()); + + beforeEach(() => { + worker.use( + rest.get('*/api/v4/projects/:name', (_, res, ctx) => + res(ctx.status(200), ctx.json({ id: 12345 })), + ), + rest.get('*', (req, res, ctx) => + res( + ctx.status(200), + ctx.json({ + url: req.url.toString(), + headers: req.headers.getAllHeaders(), + }), + ), + ), + ); + }); + afterEach(() => worker.resetHandlers()); + + const createConfig = (token?: string) => + new ConfigReader( + { + integrations: { gitlab: [{ host: 'gitlab.com', token }] }, + }, + 'test-config', + ); + + it.each([ + // Project URLs + { + url: + 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', + config: createConfig(), + response: expect.objectContaining({ + url: + 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', + headers: expect.objectContaining({ + 'private-token': '', + }), + }), + }, + { + url: + 'https://gitlab.example.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', + config: createConfig('0123456789'), + response: expect.objectContaining({ + url: + 'https://gitlab.example.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', + headers: expect.objectContaining({ + 'private-token': '0123456789', + }), + }), + }, + { + url: + 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path/to/file.yaml', // Repo not in subgroup + config: createConfig(), + response: expect.objectContaining({ + url: + 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', + }), + }, + + // Raw URLs + { + url: 'https://gitlab.example.com/a/b/blob/master/c.yaml', + config: createConfig(), + response: expect.objectContaining({ + url: 'https://gitlab.example.com/a/b/raw/master/c.yaml', + }), + }, + ])('should handle happy path %#', async ({ url, config, response }) => { + const [{ reader }] = GitlabUrlReader.factory({ config, logger }); + + const data = await reader.read(url); + const res = await JSON.parse(data.toString('utf-8')); + expect(res).toEqual(response); + }); + + it.each([ + { + url: '', + config: createConfig(''), + error: + "Invalid type in config for key 'integrations.gitlab[0].token' in 'test-config', got empty-string, wanted string", + }, + ])('should handle error path %#', async ({ url, config, error }) => { + await expect(async () => { + const [{ reader }] = GitlabUrlReader.factory({ config, logger }); + await reader.read(url); + }).rejects.toThrow(error); + }); +}); diff --git a/packages/backend-common/src/reading/GitlabUrlReader.ts b/packages/backend-common/src/reading/GitlabUrlReader.ts new file mode 100644 index 0000000000..0e430d650c --- /dev/null +++ b/packages/backend-common/src/reading/GitlabUrlReader.ts @@ -0,0 +1,197 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fetch, { RequestInit, Response } from 'node-fetch'; +import { Config } from '@backstage/config'; +import { NotFoundError } from '../errors'; +import { ReaderFactory, UrlReader } from './types'; + +type Options = { + host: string; + token?: string; +}; + +function readConfig(config: Config): Options[] { + const optionsArr = Array(); + + const providerConfigs = + config.getOptionalConfigArray('integrations.gitlab') ?? []; + + for (const providerConfig of providerConfigs) { + const host = providerConfig.getOptionalString('host') ?? 'gitlab.com'; + const token = providerConfig.getOptionalString('token'); + + optionsArr.push({ host, token }); + } + + // As a convenience we always make sure there's at least an unauthenticated + // reader for public gitlab repos. + if (!optionsArr.some(p => p.host === 'gitlab.com')) { + optionsArr.push({ host: 'gitlab.com' }); + } + + return optionsArr; +} + +export class GitlabUrlReader implements UrlReader { + static factory: ReaderFactory = ({ config }) => { + return readConfig(config).map(options => { + const reader = new GitlabUrlReader(options); + const predicate = (url: URL) => url.host === options.host; + return { reader, predicate }; + }); + }; + + constructor(private readonly options: Options) {} + + async read(url: string): Promise { + // TODO(Rugvip): merged the old GitlabReaderProcessor in here and used + // the existence of /~/blob/ to switch the logic. Don't know if this + // makes sense and it might require some more work. + let builtUrl: URL; + if (url.includes('/-/blob/')) { + const projectID = await this.getProjectID(url); + builtUrl = this.buildProjectUrl(url, projectID); + } else { + builtUrl = this.buildRawUrl(url); + } + + let response: Response; + try { + response = await fetch(builtUrl.toString(), this.getRequestOptions()); + } catch (e) { + throw new Error(`Unable to read ${url}, ${e}`); + } + + if (response.ok) { + return response.buffer(); + } + + const message = `${url} could not be read as ${builtUrl}, ${response.status} ${response.statusText}`; + if (response.status === 404) { + throw new NotFoundError(message); + } + throw new Error(message); + } + + // Converts + // from: https://gitlab.example.com/a/b/blob/master/c.yaml + // to: https://gitlab.example.com/a/b/raw/master/c.yaml + private buildRawUrl(target: string): URL { + try { + const url = new URL(target); + + const [ + empty, + userOrOrg, + repoName, + blobKeyword, + ...restOfPath + ] = url.pathname.split('/'); + + if ( + empty !== '' || + userOrOrg === '' || + repoName === '' || + blobKeyword !== 'blob' || + !restOfPath.join('/').match(/\.yaml$/) + ) { + throw new Error('Wrong GitLab URL'); + } + + // Replace 'blob' with 'raw' + url.pathname = [empty, userOrOrg, repoName, 'raw', ...restOfPath].join( + '/', + ); + + return url; + } catch (e) { + throw new Error(`Incorrect url: ${target}, ${e}`); + } + } + + // convert https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/filepath + // to https://gitlab.com/api/v4/projects//repository/files/filepath?ref=branch + private buildProjectUrl(target: string, projectID: Number): URL { + try { + const url = new URL(target); + + const branchAndfilePath = url.pathname.split('/-/blob/')[1]; + + const [branch, ...filePath] = branchAndfilePath.split('/'); + + url.pathname = [ + '/api/v4/projects', + projectID, + 'repository/files', + encodeURIComponent(filePath.join('/')), + 'raw', + ].join('/'); + url.search = `?ref=${branch}`; + + return url; + } catch (e) { + throw new Error(`Incorrect url: ${target}, ${e}`); + } + } + + private async getProjectID(target: string): Promise { + const url = new URL(target); + + if ( + // absPaths to gitlab files should contain /-/blob + // ex: https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/filepath + !url.pathname.match(/\/\-\/blob\//) + ) { + throw new Error('Please provide full path to yaml file from Gitlab'); + } + try { + const repo = url.pathname.split('/-/blob/')[0]; + + // Find ProjectID from url + // convert 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/filepath' + // to 'https://gitlab.com/api/v4/projects/groupA%2Fteams%2FsubgroupA%2FteamA%2Frepo' + const repoIDLookup = new URL( + `${url.protocol + url.hostname}/api/v4/projects/${encodeURIComponent( + repo.replace(/^\//, ''), + )}`, + ); + const response = await fetch( + repoIDLookup.toString(), + this.getRequestOptions(), + ); + const projectIDJson = await response.json(); + const projectID: Number = projectIDJson.id; + + return projectID; + } catch (e) { + throw new Error(`Could not get GitLab ProjectID for: ${target}, ${e}`); + } + } + + private getRequestOptions(): RequestInit { + return { + headers: { + ['PRIVATE-TOKEN']: this.options.token ?? '', + }, + }; + } + + toString() { + const { host, token } = this.options; + return `gitlab{host=${host},authed=${Boolean(token)}}`; + } +} diff --git a/packages/backend-common/src/reading/UrlReaderPredicateMux.ts b/packages/backend-common/src/reading/UrlReaderPredicateMux.ts new file mode 100644 index 0000000000..7654cc8aac --- /dev/null +++ b/packages/backend-common/src/reading/UrlReaderPredicateMux.ts @@ -0,0 +1,61 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { UrlReader, UrlReaderPredicateTuple } from './types'; + +type Options = { + // UrlReader to fall back to if no other reader is matched + fallback?: UrlReader; +}; + +/** + * A UrlReader implementation that selects from a set of UrlReaders + * based on a predicate tied to each reader. + */ +export class UrlReaderPredicateMux implements UrlReader { + private readonly readers: UrlReaderPredicateTuple[] = []; + private readonly fallback?: UrlReader; + + constructor({ fallback }: Options) { + this.fallback = fallback; + } + + register(tuple: UrlReaderPredicateTuple): void { + this.readers.push(tuple); + } + + read(url: string): Promise { + const parsed = new URL(url); + + for (const { predicate, reader } of this.readers) { + if (predicate(parsed)) { + return reader.read(url); + } + } + + if (this.fallback) { + return this.fallback.read(url); + } + + throw new Error(`No reader found that could handle '${url}'`); + } + + toString() { + return `predicateMux{readers=${this.readers + .map(t => t.reader) + .join(',')},fallback=${this.fallback}}`; + } +} diff --git a/packages/backend-common/src/reading/UrlReaders.ts b/packages/backend-common/src/reading/UrlReaders.ts new file mode 100644 index 0000000000..e1d99a2c49 --- /dev/null +++ b/packages/backend-common/src/reading/UrlReaders.ts @@ -0,0 +1,84 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Logger } from 'winston'; +import { Config } from '@backstage/config'; +import { ReaderFactory, UrlReader } from './types'; +import { UrlReaderPredicateMux } from './UrlReaderPredicateMux'; +import { AzureUrlReader } from './AzureUrlReader'; +import { BitbucketUrlReader } from './BitbucketUrlReader'; +import { GithubUrlReader } from './GithubUrlReader'; +import { GitlabUrlReader } from './GitlabUrlReader'; +import { FetchUrlReader } from './FetchUrlReader'; + +type CreateOptions = { + /** Root config object */ + config: Config; + /** Logger used by all the readers */ + logger: Logger; + /** A list of factories used to construct individual readers that match on URLs */ + factories?: ReaderFactory[]; + /** Fallback reader to use if none of the readers created by the factories match */ + fallback?: UrlReader; +}; + +/** + * UrlReaders provide various utilities related to the UrlReader interface. + */ +export class UrlReaders { + /** + * Creates a UrlReader without any known types. + */ + static create({ + logger, + config, + factories, + fallback, + }: CreateOptions): UrlReader { + const mux = new UrlReaderPredicateMux({ fallback: fallback }); + + for (const factory of factories ?? []) { + const tuples = factory({ config, logger: logger }); + + for (const tuple of tuples) { + mux.register(tuple); + } + } + + return mux; + } + + /** + * Creates a UrlReader that includes all the default factories from this package. + * + * Any additional factories passed will be loaded before the default ones. + * + * If no fallback reader is passed, a plain fetch reader will be used. + */ + static default({ logger, config, factories = [], fallback }: CreateOptions) { + return UrlReaders.create({ + logger, + config, + factories: factories.concat([ + AzureUrlReader.factory, + BitbucketUrlReader.factory, + GithubUrlReader.factory, + GitlabUrlReader.factory, + ]), + fallback: fallback ?? new FetchUrlReader(), + }); + } +} diff --git a/packages/backend-common/src/reading/index.ts b/packages/backend-common/src/reading/index.ts new file mode 100644 index 0000000000..8ecc08ebca --- /dev/null +++ b/packages/backend-common/src/reading/index.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type { UrlReader } from './types'; +export { UrlReaders } from './UrlReaders'; +export { AzureUrlReader } from './AzureUrlReader'; +export { BitbucketUrlReader } from './BitbucketUrlReader'; +export { GithubUrlReader } from './GithubUrlReader'; +export { GitlabUrlReader } from './GitlabUrlReader'; diff --git a/packages/backend-common/src/reading/types.ts b/packages/backend-common/src/reading/types.ts new file mode 100644 index 0000000000..e423db3eca --- /dev/null +++ b/packages/backend-common/src/reading/types.ts @@ -0,0 +1,39 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Logger } from 'winston'; +import { Config } from '@backstage/config'; + +/** + * A generic interface for fetching plain data from URLs. + */ +export type UrlReader = { + read(url: string): Promise; +}; + +export type UrlReaderPredicateTuple = { + predicate: (url: URL) => boolean; + reader: UrlReader; +}; + +/** + * A factory function that can read config to construct zero or more + * UrlReaders along with a predicate for when it should be used. + */ +export type ReaderFactory = (options: { + config: Config; + logger: Logger; +}) => UrlReaderPredicateTuple[]; diff --git a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts index 10f9ca4d9b..5ff7ed4271 100644 --- a/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts +++ b/packages/backend-common/src/service/lib/ServiceBuilderImpl.ts @@ -31,23 +31,40 @@ import { } from '../../middleware'; import { ServiceBuilder } from '../types'; import { + CspOptions, + HttpsSettings, readBaseOptions, readCorsOptions, + readCspOptions, readHttpsSettings, - HttpsSettings, } from './config'; import { createHttpServer, createHttpsServer } from './hostFactory'; import { metricsHandler } from './metrics'; -const DEFAULT_PORT = 7000; +export const DEFAULT_PORT = 7000; // '' is express default, which listens to all interfaces const DEFAULT_HOST = ''; +// taken from the helmet source code - don't seem to be exported +const DEFAULT_CSP = { + 'default-src': ["'self'"], + 'base-uri': ["'self'"], + 'block-all-mixed-content': [], + 'font-src': ["'self'", 'https:', 'data:'], + 'frame-ancestors': ["'self'"], + 'img-src': ["'self'", 'data:'], + 'object-src': ["'none'"], + 'script-src': ["'self'"], + 'script-src-attr': ["'none'"], + 'style-src': ["'self'", 'https:', "'unsafe-inline'"], + 'upgrade-insecure-requests': [], +}; export class ServiceBuilderImpl implements ServiceBuilder { private port: number | undefined; private host: string | undefined; private logger: Logger | undefined; private corsOptions: cors.CorsOptions | undefined; + private cspOptions: CspOptions | undefined; private httpsSettings: HttpsSettings | undefined; private enableMetrics: boolean = true; private routers: [string, Router][]; @@ -79,6 +96,11 @@ export class ServiceBuilderImpl implements ServiceBuilder { this.corsOptions = corsOptions; } + const cspOptions = readCspOptions(backendConfig); + if (cspOptions) { + this.cspOptions = cspOptions; + } + const httpsSettings = readHttpsSettings(backendConfig); if (httpsSettings) { this.httpsSettings = httpsSettings; @@ -115,6 +137,11 @@ export class ServiceBuilderImpl implements ServiceBuilder { return this; } + setCsp(options: CspOptions): ServiceBuilder { + this.cspOptions = options; + return this; + } + addRouter(root: string, router: Router): ServiceBuilder { this.routers.push([root, router]); return this; @@ -127,10 +154,20 @@ export class ServiceBuilderImpl implements ServiceBuilder { host, logger, corsOptions, + cspOptions, httpsSettings, } = this.getOptions(); - app.use(helmet()); + app.use( + helmet({ + contentSecurityPolicy: { + directives: { + ...DEFAULT_CSP, + ...cspOptions, + }, + }, + }), + ); if (corsOptions) { app.use(cors(corsOptions)); } @@ -177,6 +214,7 @@ export class ServiceBuilderImpl implements ServiceBuilder { host: string; logger: Logger; corsOptions?: cors.CorsOptions; + cspOptions?: CspOptions; httpsSettings?: HttpsSettings; } { return { @@ -184,6 +222,7 @@ export class ServiceBuilderImpl implements ServiceBuilder { host: this.host ?? DEFAULT_HOST, logger: this.logger ?? getRootLogger(), corsOptions: this.corsOptions, + cspOptions: this.cspOptions, httpsSettings: this.httpsSettings, }; } diff --git a/packages/backend-common/src/service/lib/config.ts b/packages/backend-common/src/service/lib/config.ts index e257bd4111..bfd966b499 100644 --- a/packages/backend-common/src/service/lib/config.ts +++ b/packages/backend-common/src/service/lib/config.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { ConfigReader } from '@backstage/config'; +import { Config } from '@backstage/config'; import { CorsOptions } from 'cors'; export type BaseOptions = { @@ -57,6 +57,13 @@ export type CertificateAttributes = { commonName?: string; }; +/** + * A map from CSP directive names to their values. + * + * Added here since helmet doesn't export this type publicly. + */ +export type CspOptions = Record; + /** * Reads some base options out of a config object. * @@ -71,7 +78,7 @@ export type CertificateAttributes = { * } * ``` */ -export function readBaseOptions(config: ConfigReader): BaseOptions { +export function readBaseOptions(config: Config): BaseOptions { if (typeof config.get('listen') === 'string') { // TODO(freben): Expand this to support more addresses and perhaps optional const { host, port } = parseListenAddress(config.getString('listen')); @@ -105,7 +112,7 @@ export function readBaseOptions(config: ConfigReader): BaseOptions { * } * ``` */ -export function readCorsOptions(config: ConfigReader): CorsOptions | undefined { +export function readCorsOptions(config: Config): CorsOptions | undefined { const cc = config.getOptionalConfig('cors'); if (!cc) { return undefined; @@ -123,6 +130,33 @@ export function readCorsOptions(config: ConfigReader): CorsOptions | undefined { }); } +/** + * Attempts to read a CSP options object from the root of a config object. + * + * @param config The root of a backend config object + * @returns A CSP options object, or undefined if not specified + * + * @example + * ```yaml + * backend: + * csp: + * connect-src: ["'self'", 'http:', 'https:'] + * ``` + */ +export function readCspOptions(config: Config): CspOptions | undefined { + const cc = config.getOptionalConfig('csp'); + if (!cc) { + return undefined; + } + + const result: CspOptions = {}; + for (const key of cc.keys()) { + result[key] = cc.getStringArray(key); + } + + return result; +} + /** * Attempts to read a https settings object from the root of a config object. * @@ -138,9 +172,7 @@ export function readCorsOptions(config: ConfigReader): CorsOptions | undefined { * } * ``` */ -export function readHttpsSettings( - config: ConfigReader, -): HttpsSettings | undefined { +export function readHttpsSettings(config: Config): HttpsSettings | undefined { const cc = config.getOptionalConfig('https'); if (!cc) { @@ -157,7 +189,7 @@ export function readHttpsSettings( } function getOptionalStringOrStrings( - config: ConfigReader, + config: Config, key: string, ): string | string[] | undefined { const value = config.getOptional(key); diff --git a/packages/backend-common/src/setupTests.ts b/packages/backend-common/src/setupTests.ts index f7b6ca962d..ba33cf996b 100644 --- a/packages/backend-common/src/setupTests.ts +++ b/packages/backend-common/src/setupTests.ts @@ -14,6 +14,4 @@ * limitations under the License. */ -require('jest-fetch-mock').enableMocks(); - export {}; diff --git a/packages/backend/Dockerfile b/packages/backend/Dockerfile index a7bd814b19..93929ceb86 100644 --- a/packages/backend/Dockerfile +++ b/packages/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM node:12 +FROM node:12-buster WORKDIR /usr/src/app diff --git a/packages/backend/package.json b/packages/backend/package.json index e1b8665b57..0941af248a 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -6,7 +6,7 @@ "private": true, "license": "Apache-2.0", "engines": { - "node": "12" + "node": "12 || 14" }, "scripts": { "build": "backstage-cli backend:build", @@ -25,7 +25,6 @@ "@backstage/plugin-auth-backend": "^0.1.1-alpha.23", "@backstage/plugin-catalog-backend": "^0.1.1-alpha.23", "@backstage/plugin-graphql-backend": "^0.1.1-alpha.23", - "@backstage/plugin-identity-backend": "^0.1.1-alpha.23", "@backstage/plugin-kubernetes-backend": "^0.1.1-alpha.23", "@backstage/plugin-proxy-backend": "^0.1.1-alpha.23", "@backstage/plugin-rollbar-backend": "^0.1.1-alpha.23", @@ -34,13 +33,15 @@ "@backstage/plugin-techdocs-backend": "^0.1.1-alpha.23", "@gitbeaker/node": "^23.5.0", "@octokit/rest": "^18.0.0", + "azure-devops-node-api": "^10.1.1", "dockerode": "^3.2.0", "example-app": "^0.1.1-alpha.23", "express": "^4.17.1", + "express-promise-router": "^3.0.3", "knex": "^0.21.1", "pg": "^8.3.0", "pg-connection-string": "^2.3.0", - "sqlite3": "^4.2.0", + "sqlite3": "^5.0.0", "winston": "^3.2.1" }, "devDependencies": { diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index 7c52175d76..959af71427 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -22,18 +22,22 @@ * Happy hacking! */ +import Router from 'express-promise-router'; import { + ensureDatabaseExists, createDatabaseClient, createServiceBuilder, loadBackendConfig, getRootLogger, useHotMemoize, + notFoundHandler, + SingleHostDiscovery, + UrlReaders, } from '@backstage/backend-common'; import { ConfigReader, AppConfig } from '@backstage/config'; import healthcheck from './plugins/healthcheck'; import auth from './plugins/auth'; import catalog from './plugins/catalog'; -import identity from './plugins/identity'; import kubernetes from './plugins/kubernetes'; import rollbar from './plugins/rollbar'; import scaffolder from './plugins/scaffolder'; @@ -46,9 +50,14 @@ import { PluginEnvironment } from './types'; function makeCreateEnv(loadedConfigs: AppConfig[]) { const config = ConfigReader.fromConfigs(loadedConfigs); + const root = getRootLogger(); + const reader = UrlReaders.default({ logger: root, config }); + const discovery = SingleHostDiscovery.fromConfig(config); + + root.info(`Created UrlReader ${reader}`); return (plugin: string): PluginEnvironment => { - const logger = getRootLogger().child({ type: 'plugin', plugin }); + const logger = root.child({ type: 'plugin', plugin }); const database = createDatabaseClient( config.getConfig('backend.database'), { @@ -57,7 +66,7 @@ function makeCreateEnv(loadedConfigs: AppConfig[]) { }, }, ); - return { logger, database, config }; + return { logger, database, config, reader, discovery }; }; } @@ -65,11 +74,16 @@ async function main() { const configs = await loadBackendConfig(); const configReader = ConfigReader.fromConfigs(configs); const createEnv = makeCreateEnv(configs); + await ensureDatabaseExists( + configReader.getConfig('backend.database'), + 'backstage_plugin_catalog', + 'backstage_plugin_auth', + ); + const healthcheckEnv = useHotMemoize(module, () => createEnv('healthcheck')); const catalogEnv = useHotMemoize(module, () => createEnv('catalog')); const scaffolderEnv = useHotMemoize(module, () => createEnv('scaffolder')); const authEnv = useHotMemoize(module, () => createEnv('auth')); - const identityEnv = useHotMemoize(module, () => createEnv('identity')); const proxyEnv = useHotMemoize(module, () => createEnv('proxy')); const rollbarEnv = useHotMemoize(module, () => createEnv('rollbar')); const sentryEnv = useHotMemoize(module, () => createEnv('sentry')); @@ -78,19 +92,22 @@ async function main() { const graphqlEnv = useHotMemoize(module, () => createEnv('graphql')); const appEnv = useHotMemoize(module, () => createEnv('app')); + const apiRouter = Router(); + apiRouter.use('/catalog', await catalog(catalogEnv)); + apiRouter.use('/rollbar', await rollbar(rollbarEnv)); + apiRouter.use('/scaffolder', await scaffolder(scaffolderEnv)); + apiRouter.use('/sentry', await sentry(sentryEnv)); + apiRouter.use('/auth', await auth(authEnv)); + apiRouter.use('/techdocs', await techdocs(techdocsEnv)); + apiRouter.use('/kubernetes', await kubernetes(kubernetesEnv)); + apiRouter.use('/proxy', await proxy(proxyEnv)); + apiRouter.use('/graphql', await graphql(graphqlEnv)); + apiRouter.use(notFoundHandler()); + const service = createServiceBuilder(module) .loadConfig(configReader) .addRouter('', await healthcheck(healthcheckEnv)) - .addRouter('/catalog', await catalog(catalogEnv)) - .addRouter('/rollbar', await rollbar(rollbarEnv)) - .addRouter('/scaffolder', await scaffolder(scaffolderEnv)) - .addRouter('/sentry', await sentry(sentryEnv)) - .addRouter('/auth', await auth(authEnv)) - .addRouter('/identity', await identity(identityEnv)) - .addRouter('/techdocs', await techdocs(techdocsEnv)) - .addRouter('/kubernetes', await kubernetes(kubernetesEnv)) - .addRouter('/proxy', await proxy(proxyEnv, '/proxy')) - .addRouter('/graphql', await graphql(graphqlEnv)) + .addRouter('/api', apiRouter) .addRouter('', await app(appEnv)); await service.start().catch(err => { diff --git a/packages/backend/src/plugins/auth.ts b/packages/backend/src/plugins/auth.ts index b24dd6ca6b..913c8b783d 100644 --- a/packages/backend/src/plugins/auth.ts +++ b/packages/backend/src/plugins/auth.ts @@ -21,6 +21,7 @@ export default async function createPlugin({ logger, database, config, + discovery, }: PluginEnvironment) { - return await createRouter({ logger, config, database }); + return await createRouter({ logger, config, database, discovery }); } diff --git a/packages/backend/src/plugins/catalog.ts b/packages/backend/src/plugins/catalog.ts index fdac6dd938..c1d390f8cc 100644 --- a/packages/backend/src/plugins/catalog.ts +++ b/packages/backend/src/plugins/catalog.ts @@ -28,10 +28,11 @@ import { useHotCleanup } from '@backstage/backend-common'; export default async function createPlugin({ logger, - database, config, + reader, + database, }: PluginEnvironment) { - const locationReader = new LocationReaders({ logger, config }); + const locationReader = new LocationReaders({ logger, reader, config }); const db = await DatabaseManager.createDatabase(database, { logger }); const entitiesCatalog = new DatabaseEntitiesCatalog(db); @@ -45,7 +46,7 @@ export default async function createPlugin({ useHotCleanup( module, - runPeriodically(() => higherOrderOperation.refreshAllLocations(), 10000), + runPeriodically(() => higherOrderOperation.refreshAllLocations(), 100000), ); return await createRouter({ diff --git a/packages/backend/src/plugins/kubernetes.ts b/packages/backend/src/plugins/kubernetes.ts index 42b7722ff6..7906765533 100644 --- a/packages/backend/src/plugins/kubernetes.ts +++ b/packages/backend/src/plugins/kubernetes.ts @@ -17,6 +17,9 @@ import { createRouter } from '@backstage/plugin-kubernetes-backend'; import { PluginEnvironment } from '../types'; -export default async function createPlugin({ logger }: PluginEnvironment) { - return await createRouter({ logger }); +export default async function createPlugin({ + logger, + config, +}: PluginEnvironment) { + return await createRouter({ logger, config }); } diff --git a/packages/backend/src/plugins/proxy.ts b/packages/backend/src/plugins/proxy.ts index e96acf69d3..867e742dc0 100644 --- a/packages/backend/src/plugins/proxy.ts +++ b/packages/backend/src/plugins/proxy.ts @@ -18,9 +18,10 @@ import { createRouter } from '@backstage/plugin-proxy-backend'; import { PluginEnvironment } from '../types'; -export default async function createPlugin( - { logger, config }: PluginEnvironment, - pathPrefix: string, -) { - return await createRouter({ logger, config, pathPrefix }); +export default async function createPlugin({ + logger, + config, + discovery, +}: PluginEnvironment) { + return await createRouter({ logger, config, discovery }); } diff --git a/packages/backend/src/plugins/scaffolder.ts b/packages/backend/src/plugins/scaffolder.ts index f902ee76f0..c5b36ab8da 100644 --- a/packages/backend/src/plugins/scaffolder.ts +++ b/packages/backend/src/plugins/scaffolder.ts @@ -20,16 +20,19 @@ import { FilePreparer, GithubPreparer, GitlabPreparer, + AzurePreparer, Preparers, Publishers, GithubPublisher, GitlabPublisher, + AzurePublisher, CreateReactAppTemplater, Templaters, RepoVisibilityOptions, } from '@backstage/plugin-scaffolder-backend'; import { Octokit } from '@octokit/rest'; import { Gitlab } from '@gitbeaker/node'; +import { getPersonalAccessTokenHandler, WebApi } from 'azure-devops-node-api'; import type { PluginEnvironment } from '../types'; import Docker from 'dockerode'; @@ -46,12 +49,14 @@ export default async function createPlugin({ const filePreparer = new FilePreparer(); const githubPreparer = new GithubPreparer(); const gitlabPreparer = new GitlabPreparer(config); + const azurePreparer = new AzurePreparer(config); const preparers = new Preparers(); preparers.register('file', filePreparer); preparers.register('github', githubPreparer); preparers.register('gitlab', gitlabPreparer); preparers.register('gitlab/api', gitlabPreparer); + preparers.register('azure/api', azurePreparer); const publishers = new Publishers(); @@ -111,6 +116,32 @@ export default async function createPlugin({ } } + const azureConfig = config.getOptionalConfig('scaffolder.azure'); + if (azureConfig) { + try { + const baseUrl = azureConfig.getString('baseUrl'); + const azureToken = azureConfig.getConfig('api').getString('token'); + + const authHandler = getPersonalAccessTokenHandler(azureToken); + const webApi = new WebApi(baseUrl, authHandler); + const azureClient = await webApi.getGitApi(); + + const azurePublisher = new AzurePublisher(azureClient, azureToken); + publishers.register('azure/api', azurePublisher); + } catch (e) { + const providerName = 'azure'; + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, + ); + } + + logger.warn( + `Skipping ${providerName} scaffolding provider, ${e.message}`, + ); + } + } + const dockerClient = new Docker(); return await createRouter({ preparers, diff --git a/packages/backend/src/plugins/techdocs.ts b/packages/backend/src/plugins/techdocs.ts index 58dca83b43..e04d2a2732 100644 --- a/packages/backend/src/plugins/techdocs.ts +++ b/packages/backend/src/plugins/techdocs.ts @@ -22,6 +22,7 @@ import { LocalPublish, TechdocsGenerator, GithubPreparer, + GitlabPreparer, } from '@backstage/plugin-techdocs-backend'; import { PluginEnvironment } from '../types'; import Docker from 'dockerode'; @@ -29,6 +30,7 @@ import Docker from 'dockerode'; export default async function createPlugin({ logger, config, + discovery, }: PluginEnvironment) { const generators = new Generators(); const techdocsGenerator = new TechdocsGenerator(logger, config); @@ -36,9 +38,11 @@ export default async function createPlugin({ const preparers = new Preparers(); const githubPreparer = new GithubPreparer(logger); + const gitlabPreparer = new GitlabPreparer(logger); const directoryPreparer = new DirectoryPreparer(logger); preparers.register('dir', directoryPreparer); preparers.register('github', githubPreparer); + preparers.register('gitlab', gitlabPreparer); const publisher = new LocalPublish(logger); @@ -51,5 +55,6 @@ export default async function createPlugin({ dockerClient, logger, config, + discovery, }); } diff --git a/packages/backend/src/types.ts b/packages/backend/src/types.ts index f7df3d05c6..9257fcc9cf 100644 --- a/packages/backend/src/types.ts +++ b/packages/backend/src/types.ts @@ -17,9 +17,12 @@ import Knex from 'knex'; import { Logger } from 'winston'; import { Config } from '@backstage/config'; +import { PluginEndpointDiscovery, UrlReader } from '@backstage/backend-common'; export type PluginEnvironment = { logger: Logger; database: Knex; config: Config; + reader: UrlReader; + discovery: PluginEndpointDiscovery; }; diff --git a/packages/catalog-model/examples/all-apis.yaml b/packages/catalog-model/examples/all-apis.yaml index 33b000d1ae..3c4f7804bf 100644 --- a/packages/catalog-model/examples/all-apis.yaml +++ b/packages/catalog-model/examples/all-apis.yaml @@ -8,3 +8,5 @@ spec: targets: - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/hello-world-api.yaml - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/streetlights-api.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/spotify-api.yaml + - https://github.com/spotify/backstage/blob/master/packages/catalog-model/examples/swapi-graphql.yaml diff --git a/packages/catalog-model/examples/spotify-api.yaml b/packages/catalog-model/examples/spotify-api.yaml new file mode 100644 index 0000000000..30524dfdd4 --- /dev/null +++ b/packages/catalog-model/examples/spotify-api.yaml @@ -0,0 +1,14 @@ +apiVersion: backstage.io/v1alpha1 +kind: API +metadata: + name: spotify + description: The Spotify web API + tags: + - spotify + - rest + annotations: + backstage.io/definition-at-location: 'url:https://raw.githubusercontent.com/APIs-guru/openapi-directory/master/APIs/spotify.com/v1/swagger.yaml' +spec: + type: openapi + lifecycle: production + owner: spotify@example.com diff --git a/packages/catalog-model/src/EntityPolicies.ts b/packages/catalog-model/src/EntityPolicies.ts index 8cc51e5aa8..ca59338c16 100644 --- a/packages/catalog-model/src/EntityPolicies.ts +++ b/packages/catalog-model/src/EntityPolicies.ts @@ -23,11 +23,12 @@ import { SchemaValidEntityPolicy, } from './entity'; import { - ApiEntityV1alpha1Policy, - ComponentEntityV1alpha1Policy, - GroupEntityV1alpha1Policy, - LocationEntityV1alpha1Policy, - TemplateEntityV1alpha1Policy, + apiEntityV1alpha1Policy, + componentEntityV1alpha1Policy, + groupEntityV1alpha1Policy, + locationEntityV1alpha1Policy, + templateEntityV1alpha1Policy, + userEntityV1alpha1Policy, } from './kinds'; import { EntityPolicy } from './types'; @@ -39,7 +40,10 @@ class AllEntityPolicies implements EntityPolicy { async enforce(entity: Entity): Promise { let result = entity; for (const policy of this.policies) { - result = await policy.enforce(entity); + const output = await policy.enforce(entity); + if (output) { + result = output; + } } return result; } @@ -50,12 +54,11 @@ class AllEntityPolicies implements EntityPolicy { class AnyEntityPolicy implements EntityPolicy { constructor(private readonly policies: EntityPolicy[]) {} - async enforce(entity: Entity): Promise { + async enforce(entity: Entity): Promise { for (const policy of this.policies) { - try { - return await policy.enforce(entity); - } catch { - continue; + const output = await policy.enforce(entity); + if (output !== null) { + return output; } } throw new Error(`The entity did not match any known policy`); @@ -75,11 +78,12 @@ export class EntityPolicies implements EntityPolicy { new ReservedFieldsEntityPolicy(), ]), EntityPolicies.anyOf([ - new ComponentEntityV1alpha1Policy(), - new GroupEntityV1alpha1Policy(), - new LocationEntityV1alpha1Policy(), - new TemplateEntityV1alpha1Policy(), - new ApiEntityV1alpha1Policy(), + componentEntityV1alpha1Policy, + groupEntityV1alpha1Policy, + userEntityV1alpha1Policy, + locationEntityV1alpha1Policy, + templateEntityV1alpha1Policy, + apiEntityV1alpha1Policy, ]), ]); } @@ -96,7 +100,7 @@ export class EntityPolicies implements EntityPolicy { this.policy = policy; } - enforce(entity: Entity): Promise { + enforce(entity: Entity): Promise { return this.policy.enforce(entity); } } diff --git a/packages/catalog-model/src/entity/Entity.ts b/packages/catalog-model/src/entity/Entity.ts index 7f323043b1..9e0aec7de6 100644 --- a/packages/catalog-model/src/entity/Entity.ts +++ b/packages/catalog-model/src/entity/Entity.ts @@ -87,7 +87,7 @@ export type EntityMeta = JsonObject & { /** * The name of the entity. * - * Must be uniqe within the catalog at any given point in time, for any + * Must be unique within the catalog at any given point in time, for any * given namespace + kind pair. */ name: string; @@ -120,8 +120,3 @@ export type EntityMeta = JsonObject & { */ tags?: string[]; }; - -/** - * The keys of EntityMeta that are auto-generated. - */ -export const entityMetaGeneratedFields = ['uid', 'etag', 'generation'] as const; diff --git a/packages/catalog-model/src/entity/constants.ts b/packages/catalog-model/src/entity/constants.ts new file mode 100644 index 0000000000..42ea2ae8ba --- /dev/null +++ b/packages/catalog-model/src/entity/constants.ts @@ -0,0 +1,29 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The namespace that entities without an explicit namespace fall into. + */ +export const ENTITY_DEFAULT_NAMESPACE = 'default'; + +/** + * The keys of EntityMeta that are auto-generated. + */ +export const ENTITY_META_GENERATED_FIELDS = [ + 'uid', + 'etag', + 'generation', +] as const; diff --git a/packages/catalog-model/src/entity/index.ts b/packages/catalog-model/src/entity/index.ts index 380f5458cc..759a94ca67 100644 --- a/packages/catalog-model/src/entity/index.ts +++ b/packages/catalog-model/src/entity/index.ts @@ -14,9 +14,18 @@ * limitations under the License. */ -export { entityMetaGeneratedFields } from './Entity'; +export { + ENTITY_DEFAULT_NAMESPACE, + ENTITY_META_GENERATED_FIELDS, +} from './constants'; export type { Entity, EntityMeta } from './Entity'; export * from './policies'; +export { + getEntityName, + parseEntityName, + parseEntityRef, + serializeEntityRef, +} from './ref'; export { entityHasChanges, generateEntityEtag, diff --git a/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.test.ts b/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.test.ts index 68f1cec649..c6bda864cb 100644 --- a/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.test.ts +++ b/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.test.ts @@ -15,6 +15,7 @@ */ import yaml from 'yaml'; +import { ENTITY_DEFAULT_NAMESPACE } from '../constants'; import { DefaultNamespaceEntityPolicy } from './DefaultNamespaceEntityPolicy'; describe('DefaultNamespaceEntityPolicy', () => { @@ -54,7 +55,10 @@ describe('DefaultNamespaceEntityPolicy', () => { await expect(result).resolves.not.toBe(withoutNamespace); await expect(result).resolves.toEqual( expect.objectContaining({ - metadata: { name: 'my-component-yay', namespace: 'default' }, + metadata: { + name: 'my-component-yay', + namespace: ENTITY_DEFAULT_NAMESPACE, + }, }), ); }); diff --git a/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.ts b/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.ts index e5aba745c7..3119164454 100644 --- a/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.ts +++ b/packages/catalog-model/src/entity/policies/DefaultNamespaceEntityPolicy.ts @@ -16,6 +16,7 @@ import lodash from 'lodash'; import { EntityPolicy } from '../../types'; +import { ENTITY_DEFAULT_NAMESPACE } from '../constants'; import { Entity } from '../Entity'; /** @@ -24,7 +25,7 @@ import { Entity } from '../Entity'; export class DefaultNamespaceEntityPolicy implements EntityPolicy { private readonly namespace: string; - constructor(namespace: string = 'default') { + constructor(namespace: string = ENTITY_DEFAULT_NAMESPACE) { this.namespace = namespace; } diff --git a/packages/catalog-model/src/entity/ref.test.ts b/packages/catalog-model/src/entity/ref.test.ts new file mode 100644 index 0000000000..d9787fe675 --- /dev/null +++ b/packages/catalog-model/src/entity/ref.test.ts @@ -0,0 +1,363 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ENTITY_DEFAULT_NAMESPACE } from './constants'; +import { parseEntityName, parseEntityRef, serializeEntityRef } from './ref'; + +describe('ref', () => { + describe('parseEntityName', () => { + it('handles some omissions', () => { + expect(parseEntityName('a:b/c')).toEqual({ + kind: 'a', + namespace: 'b', + name: 'c', + }); + expect(() => parseEntityName('b/c')).toThrow(/kind/); + expect(parseEntityName('a:c')).toEqual({ + kind: 'a', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'c', + }); + expect(() => parseEntityName('c')).toThrow(/kind/); + }); + + it('rejects bad inputs', () => { + expect(() => parseEntityName(null as any)).toThrow(); + expect(() => parseEntityName(7 as any)).toThrow(); + expect(() => parseEntityName('a:b:c')).toThrow(); + expect(() => parseEntityName('a/b/c')).toThrow(); + expect(() => parseEntityName('a/b:c')).toThrow(); + expect(() => parseEntityName('a:b/c/d')).toThrow(); + expect(() => parseEntityName('a:b/c:d')).toThrow(); + }); + + it('rejects empty parts in strings', () => { + // one is empty + expect(() => parseEntityName(':b/c')).toThrow(); + expect(() => parseEntityName('a:/c')).toThrow(); + expect(() => parseEntityName('a:b/')).toThrow(); + // two are empty + expect(() => parseEntityName('a:/')).toThrow(); + expect(() => parseEntityName(':b/')).toThrow(); + expect(() => parseEntityName(':/c')).toThrow(); + // three are empty + expect(() => parseEntityName(':/')).toThrow(); + // one is left out, one empty + expect(() => parseEntityName('/c')).toThrow(); + expect(() => parseEntityName('b/')).toThrow(); + expect(() => parseEntityName(':c')).toThrow(); + expect(() => parseEntityName('a:')).toThrow(); + // nothing at all + expect(() => parseEntityName('')).toThrow(); + }); + + it('rejects empty parts in compounds', () => { + // one is empty + expect(() => + parseEntityName({ kind: '', namespace: 'b', name: 'c' }), + ).toThrow(); + expect(() => parseEntityName({ namespace: 'b', name: 'c' })).toThrow(); + expect(() => + parseEntityName({ kind: 'a', namespace: '', name: 'c' }), + ).toThrow(); + expect(() => parseEntityName({ kind: 'a', name: 'c' })).not.toThrow(); + expect(() => + parseEntityName({ kind: 'a', namespace: 'b', name: '' }), + ).toThrow(); + expect(() => + parseEntityName({ kind: 'a', namespace: 'b' } as any), + ).toThrow(); + // two are empty + expect(() => + parseEntityName({ kind: '', namespace: '', name: 'c' }), + ).toThrow(); + expect(() => parseEntityName({ name: 'c' })).toThrow(); + expect(() => + parseEntityName({ kind: '', namespace: 'b', name: '' }), + ).toThrow(); + expect(() => parseEntityName({ namespace: 'b' } as any)).toThrow(); + expect(() => + parseEntityName({ kind: 'a', namespace: '', name: '' }), + ).toThrow(); + expect(() => parseEntityName({ kind: 'a' } as any)).toThrow(); + // three are empty + expect(() => + parseEntityName({ kind: '', namespace: '', name: '' }), + ).toThrow(); + expect(() => parseEntityName({} as any)).toThrow(); + // one is left out, one empty + expect(() => parseEntityName({ namespace: '', name: 'c' })).toThrow(); + expect(() => parseEntityName({ namespace: 'b', name: '' })).toThrow(); + expect(() => parseEntityName({ kind: '', name: 'c' })).toThrow(); + expect(() => parseEntityName({ kind: 'a', name: '' })).toThrow(); + }); + + it('adds defaults where necessary to strings', () => { + expect( + parseEntityName('a:b/c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'a', namespace: 'b', name: 'c' }); + expect( + parseEntityName('b/c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'x', namespace: 'b', name: 'c' }); + expect( + parseEntityName('a:c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'a', namespace: 'y', name: 'c' }); + expect(parseEntityName('a:c', { defaultKind: 'x' })).toEqual({ + kind: 'a', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'c', + }); + expect( + parseEntityName('c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'x', namespace: 'y', name: 'c' }); + expect(parseEntityName('c', { defaultKind: 'x' })).toEqual({ + kind: 'x', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'c', + }); + }); + + it('adds defaults where necessary to compounds', () => { + expect( + parseEntityName( + { kind: 'a', namespace: 'b', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'a', namespace: 'b', name: 'c' }); + expect( + parseEntityName( + { namespace: 'b', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'x', namespace: 'b', name: 'c' }); + expect( + parseEntityName( + { kind: 'a', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'a', namespace: 'y', name: 'c' }); + expect( + parseEntityName({ kind: 'a', name: 'c' }, { defaultKind: 'x' }), + ).toEqual({ kind: 'a', namespace: ENTITY_DEFAULT_NAMESPACE, name: 'c' }); + expect( + parseEntityName( + { name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'x', namespace: 'y', name: 'c' }); + expect(parseEntityName({ name: 'c' }, { defaultKind: 'x' })).toEqual({ + kind: 'x', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'c', + }); + // empty strings are errors, not defaults + expect(() => + parseEntityName( + { kind: '', namespace: 'b', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toThrow(/kind/); + expect(() => + parseEntityName( + { kind: 'a', namespace: '', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toThrow(/namespace/); + }); + }); + + describe('parseEntityRef', () => { + it('handles some omissions', () => { + expect(parseEntityRef('a:b/c')).toEqual({ + kind: 'a', + namespace: 'b', + name: 'c', + }); + expect(parseEntityRef('b/c')).toEqual({ + kind: undefined, + namespace: 'b', + name: 'c', + }); + expect(parseEntityRef('a:c')).toEqual({ + kind: 'a', + namespace: undefined, + name: 'c', + }); + expect(parseEntityRef('c')).toEqual({ + kind: undefined, + namespace: undefined, + name: 'c', + }); + }); + + it('rejects bad inputs', () => { + expect(() => parseEntityRef(null as any)).toThrow(); + expect(() => parseEntityRef(7 as any)).toThrow(); + expect(() => parseEntityRef('a:b:c')).toThrow(); + expect(() => parseEntityRef('a/b/c')).toThrow(); + expect(() => parseEntityRef('a/b:c')).toThrow(); + expect(() => parseEntityRef('a:b/c/d')).toThrow(); + expect(() => parseEntityRef('a:b/c:d')).toThrow(); + }); + + it('rejects empty parts in strings', () => { + // one is empty + expect(() => parseEntityRef(':b/c')).toThrow(); + expect(() => parseEntityRef('a:/c')).toThrow(); + expect(() => parseEntityRef('a:b/')).toThrow(); + // two are empty + expect(() => parseEntityRef('a:/')).toThrow(); + expect(() => parseEntityRef(':b/')).toThrow(); + expect(() => parseEntityRef(':/c')).toThrow(); + // three are empty + expect(() => parseEntityRef(':/')).toThrow(); + // one is left out, one empty + expect(() => parseEntityRef('/c')).toThrow(); + expect(() => parseEntityRef('b/')).toThrow(); + expect(() => parseEntityRef(':c')).toThrow(); + expect(() => parseEntityRef('a:')).toThrow(); + // nothing at all + expect(() => parseEntityRef('')).toThrow(); + }); + + it('rejects empty parts in compounds', () => { + // one is empty + expect(() => + parseEntityRef({ kind: '', namespace: 'b', name: 'c' }), + ).toThrow(); + expect(() => + parseEntityRef({ kind: 'a', namespace: '', name: 'c' }), + ).toThrow(); + expect(() => + parseEntityRef({ kind: 'a', namespace: 'b', name: '' }), + ).toThrow(); + // two are empty + expect(() => + parseEntityRef({ kind: '', namespace: '', name: 'c' }), + ).toThrow(); + expect(() => + parseEntityRef({ kind: '', namespace: 'b', name: '' }), + ).toThrow(); + expect(() => + parseEntityRef({ kind: 'a', namespace: '', name: '' }), + ).toThrow(); + // three are empty + expect(() => + parseEntityRef({ kind: '', namespace: '', name: '' }), + ).toThrow(); + // one is left out, one empty + expect(() => parseEntityRef({ namespace: '', name: 'c' })).toThrow(); + expect(() => parseEntityRef({ namespace: 'b', name: '' })).toThrow(); + expect(() => parseEntityRef({ kind: '', name: 'c' })).toThrow(); + expect(() => parseEntityRef({ kind: 'a', name: '' })).toThrow(); + // nothing at all + expect(() => parseEntityRef({} as any)).toThrow(); + }); + + it('adds defaults where necessary to strings', () => { + expect( + parseEntityRef('a:b/c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'a', namespace: 'b', name: 'c' }); + expect( + parseEntityRef('b/c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'x', namespace: 'b', name: 'c' }); + expect( + parseEntityRef('a:c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'a', namespace: 'y', name: 'c' }); + expect( + parseEntityRef('c', { defaultKind: 'x', defaultNamespace: 'y' }), + ).toEqual({ kind: 'x', namespace: 'y', name: 'c' }); + }); + + it('adds defaults where necessary to compounds', () => { + expect( + parseEntityRef( + { kind: 'a', namespace: 'b', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'a', namespace: 'b', name: 'c' }); + expect( + parseEntityRef( + { namespace: 'b', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'x', namespace: 'b', name: 'c' }); + expect( + parseEntityRef( + { kind: 'a', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'a', namespace: 'y', name: 'c' }); + expect( + parseEntityRef( + { name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toEqual({ kind: 'x', namespace: 'y', name: 'c' }); + // empty strings are errors, not defaults + expect(() => + parseEntityRef( + { kind: '', namespace: 'b', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toThrow(/kind/); + expect(() => + parseEntityRef( + { kind: 'a', namespace: '', name: 'c' }, + { defaultKind: 'x', defaultNamespace: 'y' }, + ), + ).toThrow(/namespace/); + }); + }); + + describe('serializeEntityRef', () => { + it('handles partials', () => { + expect( + serializeEntityRef({ kind: 'a', namespace: 'b', name: 'c' }), + ).toEqual('a:b/c'); + expect(serializeEntityRef({ namespace: 'b', name: 'c' })).toEqual('b/c'); + expect(serializeEntityRef({ kind: 'a', name: 'c' })).toEqual('a:c'); + expect(serializeEntityRef({ name: 'c' })).toEqual('c'); + }); + + it('picks the least complex form', () => { + expect( + serializeEntityRef({ kind: 'a', namespace: 'b', name: 'c' }), + ).toEqual('a:b/c'); + expect(serializeEntityRef({ namespace: 'b', name: 'c' })).toEqual('b/c'); + expect(serializeEntityRef({ kind: 'a', name: 'c' })).toEqual('a:c'); + expect(serializeEntityRef({ name: 'c' })).toEqual('c'); + expect( + serializeEntityRef({ kind: 'a:x', namespace: 'b', name: 'c' }), + ).toEqual({ kind: 'a:x', namespace: 'b', name: 'c' }); + expect( + serializeEntityRef({ kind: 'a/x', namespace: 'b', name: 'c' }), + ).toEqual({ kind: 'a/x', namespace: 'b', name: 'c' }); + expect( + serializeEntityRef({ kind: 'a', namespace: 'b:x', name: 'c' }), + ).toEqual({ kind: 'a', namespace: 'b:x', name: 'c' }); + expect( + serializeEntityRef({ kind: 'a', namespace: 'b/x', name: 'c' }), + ).toEqual({ kind: 'a', namespace: 'b/x', name: 'c' }); + expect( + serializeEntityRef({ kind: 'a', namespace: 'b', name: 'c:x' }), + ).toEqual({ kind: 'a', namespace: 'b', name: 'c:x' }); + expect( + serializeEntityRef({ kind: 'a', namespace: 'b', name: 'c/x' }), + ).toEqual({ kind: 'a', namespace: 'b', name: 'c/x' }); + }); + }); +}); diff --git a/packages/catalog-model/src/entity/ref.ts b/packages/catalog-model/src/entity/ref.ts new file mode 100644 index 0000000000..c4c86b176c --- /dev/null +++ b/packages/catalog-model/src/entity/ref.ts @@ -0,0 +1,181 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { EntityName, EntityRef } from '../types'; +import { ENTITY_DEFAULT_NAMESPACE } from './constants'; +import { Entity } from './Entity'; + +/** + * Extracts the kind, namespace and name that form the name triplet of the + * given entity. + * + * @param entity An entity + * @returns The complete entity name + */ +export function getEntityName(entity: Entity): EntityName { + return { + kind: entity.kind, + namespace: entity.metadata.namespace || ENTITY_DEFAULT_NAMESPACE, + name: entity.metadata.name, + }; +} + +/** + * The context of defaults that entity reference parsing happens within. + */ +type EntityRefContext = { + /** The default kind, if none is given in the reference */ + defaultKind?: string; + /** The default namespace, if none is given in the reference */ + defaultNamespace?: string; +}; + +/** + * Parses an entity reference, either on string or compound form, and always + * returns a complete entity name including kind, namespace and name. + * + * This function automatically assumes the default namespace "default" unless + * otherwise specified as part of the options, and will throw an error if no + * kind was specified in the input reference and no default kind was given. + * + * @param ref The reference to parse + * @param context The context of defaults that the parsing happens within + * @returns A complete entity name + */ +export function parseEntityName( + ref: EntityRef, + context: EntityRefContext = {}, +): EntityName { + const { kind, namespace, name } = parseEntityRef(ref, { + defaultNamespace: ENTITY_DEFAULT_NAMESPACE, + ...context, + }); + + if (!kind) { + throw new Error( + `Entity reference ${namespace}/${name} did not contain a kind`, + ); + } + + return { kind, namespace, name }; +} + +/** + * Parses an entity reference, either on string or compound form, and returns + * a structure with a name, and optional kind and namespace. + * + * The options object can contain default values for the kind and namespace, + * that will be used if the input reference did not specify any. + * + * @param ref The reference to parse + * @param context The context of defaults that the parsing happens within + * @returns The compound form of the reference + */ +export function parseEntityRef( + ref: EntityRef, + context?: { defaultKind: string }, +): { + kind: string; + namespace?: string; + name: string; +}; +export function parseEntityRef( + ref: EntityRef, + context?: { defaultNamespace: string }, +): { + kind?: string; + namespace: string; + name: string; +}; +export function parseEntityRef( + ref: EntityRef, + context?: { defaultKind: string; defaultNamespace: string }, +): { + kind: string; + namespace: string; + name: string; +}; +export function parseEntityRef( + ref: EntityRef, + context: EntityRefContext = {}, +): { + kind?: string; + namespace?: string; + name: string; +} { + if (!ref) { + throw new Error(`Entity reference must not be empty`); + } + + if (typeof ref === 'string') { + const match = /^([^:/]+:)?([^:/]+\/)?([^:/]+)$/.exec(ref.trim()); + if (!match) { + throw new Error( + `Entity reference "${ref}" was not on the form [:][/]`, + ); + } + + return { + kind: match[1]?.slice(0, -1) ?? context.defaultKind, + namespace: match[2]?.slice(0, -1) ?? context.defaultNamespace, + name: match[3], + }; + } + + const { kind, namespace, name } = ref; + if (kind === '') { + throw new Error('Entity reference kinds must not be empty'); + } else if (namespace === '') { + throw new Error('Entity reference namespaces must not be empty'); + } else if (!name) { + throw new Error('Entity references must contain a name'); + } + + return { + kind: kind ?? context.defaultKind, + namespace: namespace ?? context.defaultNamespace, + name, + }; +} + +/** + * Takes an entity reference or name, and outputs an entity reference on the + * most compact form possible. I.e. if the parts do not contain any + * special/reserved characters, it outputs the string form, otherwise it + * outputs the compound form. + * + * @param ref The reference to serialize + * @returns The same reference on either string or compound form + */ +export function serializeEntityRef(ref: { + kind?: string; + namespace?: string; + name: string; +}): EntityRef { + const { kind, namespace, name } = ref; + if ( + kind?.includes(':') || + kind?.includes('/') || + namespace?.includes(':') || + namespace?.includes('/') || + name.includes(':') || + name.includes('/') + ) { + return { kind, namespace, name }; + } + + return `${kind ? `${kind}:` : ''}${namespace ? `${namespace}/` : ''}${name}`; +} diff --git a/packages/catalog-model/src/index.ts b/packages/catalog-model/src/index.ts index 9469319b28..f93a4001a5 100644 --- a/packages/catalog-model/src/index.ts +++ b/packages/catalog-model/src/index.ts @@ -18,5 +18,5 @@ export * from './entity'; export { EntityPolicies } from './EntityPolicies'; export * from './kinds'; export * from './location'; -export type { EntityPolicy, JSONSchema } from './types'; +export type { EntityName, EntityPolicy, EntityRef, JSONSchema } from './types'; export * from './validation'; diff --git a/packages/catalog-model/src/kinds/ApiEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/ApiEntityV1alpha1.test.ts index 35a1c59ef8..142a8d8160 100644 --- a/packages/catalog-model/src/kinds/ApiEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/ApiEntityV1alpha1.test.ts @@ -14,15 +14,13 @@ * limitations under the License. */ -import { EntityPolicy } from '../types'; import { ApiEntityV1alpha1, - ApiEntityV1alpha1Policy, + apiEntityV1alpha1Policy as policy, } from './ApiEntityV1alpha1'; describe('ApiV1alpha1Policy', () => { let entity: ApiEntityV1alpha1; - let policy: EntityPolicy; beforeEach(() => { entity = { @@ -49,7 +47,7 @@ paths: '200': description: A paged array of pets content: - application/json: + application/json: schema: $ref: "#/components/schemas/Pets" components: @@ -74,7 +72,6 @@ components: `, }, }; - policy = new ApiEntityV1alpha1Policy(); }); it('happy path: accepts valid data', async () => { @@ -86,14 +83,14 @@ components: await expect(policy.enforce(entity)).resolves.toBe(entity); }); - it('rejects unknown apiVersion', async () => { + it('ignores unknown apiVersion', async () => { (entity as any).apiVersion = 'backstage.io/v1beta0'; - await expect(policy.enforce(entity)).rejects.toThrow(/apiVersion/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); - it('rejects unknown kind', async () => { + it('ignores unknown kind', async () => { (entity as any).kind = 'Wizard'; - await expect(policy.enforce(entity)).rejects.toThrow(/kind/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); it('rejects missing type', async () => { diff --git a/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts b/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts index 972f6df96d..052172d0a1 100644 --- a/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/ApiEntityV1alpha1.ts @@ -16,11 +16,24 @@ import * as yup from 'yup'; import type { Entity } from '../entity/Entity'; -import type { EntityPolicy } from '../types'; +import { schemaPolicy } from './util'; const API_VERSION = ['backstage.io/v1alpha1', 'backstage.io/v1beta1'] as const; const KIND = 'API' as const; +const schema = yup.object>({ + apiVersion: yup.string().required().oneOf(API_VERSION), + kind: yup.string().required().equals([KIND]), + spec: yup + .object({ + type: yup.string().required().min(1), + lifecycle: yup.string().required().min(1), + owner: yup.string().required().min(1), + definition: yup.string().required().min(1), + }) + .required(), +}); + export interface ApiEntityV1alpha1 extends Entity { apiVersion: typeof API_VERSION[number]; kind: typeof KIND; @@ -32,25 +45,4 @@ export interface ApiEntityV1alpha1 extends Entity { }; } -export class ApiEntityV1alpha1Policy implements EntityPolicy { - private schema: yup.Schema; - - constructor() { - this.schema = yup.object>({ - apiVersion: yup.string().required().oneOf(API_VERSION), - kind: yup.string().required().equals([KIND]), - spec: yup - .object({ - type: yup.string().required().min(1), - lifecycle: yup.string().required().min(1), - owner: yup.string().required().min(1), - definition: yup.string().required().min(1), - }) - .required(), - }); - } - - async enforce(envelope: Entity): Promise { - return await this.schema.validate(envelope, { strict: true }); - } -} +export const apiEntityV1alpha1Policy = schemaPolicy(KIND, API_VERSION, schema); diff --git a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts index e784934d48..57d6d47388 100644 --- a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.test.ts @@ -14,15 +14,13 @@ * limitations under the License. */ -import { EntityPolicy } from '../types'; import { ComponentEntityV1alpha1, - ComponentEntityV1alpha1Policy, + componentEntityV1alpha1Policy as policy, } from './ComponentEntityV1alpha1'; describe('ComponentV1alpha1Policy', () => { let entity: ComponentEntityV1alpha1; - let policy: EntityPolicy; beforeEach(() => { entity = { @@ -38,7 +36,6 @@ describe('ComponentV1alpha1Policy', () => { implementsApis: ['api-0'], }, }; - policy = new ComponentEntityV1alpha1Policy(); }); it('happy path: accepts valid data', async () => { @@ -50,14 +47,14 @@ describe('ComponentV1alpha1Policy', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); - it('rejects unknown apiVersion', async () => { + it('ignores unknown apiVersion', async () => { (entity as any).apiVersion = 'backstage.io/v1beta0'; - await expect(policy.enforce(entity)).rejects.toThrow(/apiVersion/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); - it('rejects unknown kind', async () => { + it('ignores unknown kind', async () => { (entity as any).kind = 'Wizard'; - await expect(policy.enforce(entity)).rejects.toThrow(/kind/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); it('rejects missing type', async () => { diff --git a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts index 38b9c27720..9efc491ca9 100644 --- a/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/ComponentEntityV1alpha1.ts @@ -16,11 +16,24 @@ import * as yup from 'yup'; import type { Entity } from '../entity/Entity'; -import type { EntityPolicy } from '../types'; +import { schemaPolicy } from './util'; const API_VERSION = ['backstage.io/v1alpha1', 'backstage.io/v1beta1'] as const; const KIND = 'Component' as const; +const schema = yup.object>({ + apiVersion: yup.string().required().oneOf(API_VERSION), + kind: yup.string().required().equals([KIND]), + spec: yup + .object({ + type: yup.string().required().min(1), + lifecycle: yup.string().required().min(1), + owner: yup.string().required().min(1), + implementsApis: yup.array(yup.string()).notRequired(), + }) + .required(), +}); + export interface ComponentEntityV1alpha1 extends Entity { apiVersion: typeof API_VERSION[number]; kind: typeof KIND; @@ -32,25 +45,8 @@ export interface ComponentEntityV1alpha1 extends Entity { }; } -export class ComponentEntityV1alpha1Policy implements EntityPolicy { - private schema: yup.Schema; - - constructor() { - this.schema = yup.object>({ - apiVersion: yup.string().required().oneOf(API_VERSION), - kind: yup.string().required().equals([KIND]), - spec: yup - .object({ - type: yup.string().required().min(1), - lifecycle: yup.string().required().min(1), - owner: yup.string().required().min(1), - implementsApis: yup.array(yup.string()).notRequired(), - }) - .required(), - }); - } - - async enforce(envelope: Entity): Promise { - return await this.schema.validate(envelope, { strict: true }); - } -} +export const componentEntityV1alpha1Policy = schemaPolicy( + KIND, + API_VERSION, + schema, +); diff --git a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts index 94dcc2f14f..dc0ecd3fa3 100644 --- a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.test.ts @@ -14,15 +14,13 @@ * limitations under the License. */ -import { EntityPolicy } from '../types'; import { GroupEntityV1alpha1, - GroupEntityV1alpha1Policy, + groupEntityV1alpha1Policy as policy, } from './GroupEntityV1alpha1'; describe('GroupV1alpha1Policy', () => { let entity: GroupEntityV1alpha1; - let policy: EntityPolicy; beforeEach(() => { entity = { @@ -41,7 +39,6 @@ describe('GroupV1alpha1Policy', () => { descendants: ['desc-a', 'desc-b'], }, }; - policy = new GroupEntityV1alpha1Policy(); }); it('happy path: accepts valid data', async () => { @@ -53,14 +50,14 @@ describe('GroupV1alpha1Policy', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); - it('rejects unknown apiVersion', async () => { + it('ignores unknown apiVersion', async () => { (entity as any).apiVersion = 'backstage.io/v1beta0'; - await expect(policy.enforce(entity)).rejects.toThrow(/apiVersion/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); - it('rejects unknown kind', async () => { + it('ignores unknown kind', async () => { (entity as any).kind = 'Wizard'; - await expect(policy.enforce(entity)).rejects.toThrow(/kind/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); it('rejects missing type', async () => { @@ -98,6 +95,11 @@ describe('GroupV1alpha1Policy', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); + it('accepts no ancestors', async () => { + (entity as any).spec.ancestors = []; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + it('rejects missing children', async () => { delete (entity as any).spec.children; await expect(policy.enforce(entity)).rejects.toThrow(/children/); @@ -108,6 +110,11 @@ describe('GroupV1alpha1Policy', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); + it('accepts no children', async () => { + (entity as any).spec.children = []; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + it('rejects missing descendants', async () => { delete (entity as any).spec.descendants; await expect(policy.enforce(entity)).rejects.toThrow(/descendants/); @@ -117,4 +124,9 @@ describe('GroupV1alpha1Policy', () => { (entity as any).spec.descendants = ['']; await expect(policy.enforce(entity)).resolves.toBe(entity); }); + + it('accepts no descendants', async () => { + (entity as any).spec.descendants = []; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); }); diff --git a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts index c1d39d5b44..073332d707 100644 --- a/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/GroupEntityV1alpha1.ts @@ -16,11 +16,39 @@ import * as yup from 'yup'; import type { Entity } from '../entity/Entity'; -import type { EntityPolicy } from '../types'; +import { schemaPolicy } from './util'; const API_VERSION = ['backstage.io/v1alpha1', 'backstage.io/v1beta1'] as const; const KIND = 'Group' as const; +const schema = yup.object>({ + apiVersion: yup.string().required().oneOf(API_VERSION), + kind: yup.string().required().equals([KIND]), + spec: yup + .object({ + type: yup.string().required().min(1), + parent: yup.string().notRequired().min(1), + // Use these manual tests because yup .required() requires at least + // one element and there is no simple workaround -_- + ancestors: yup.array(yup.string()).test({ + name: 'isDefined', + message: 'ancestors must be defined', + test: v => Boolean(v), + }), + children: yup.array(yup.string()).test({ + name: 'isDefined', + message: 'children must be defined', + test: v => Boolean(v), + }), + descendants: yup.array(yup.string()).test({ + name: 'isDefined', + message: 'descendants must be defined', + test: v => Boolean(v), + }), + }) + .required(), +}); + export interface GroupEntityV1alpha1 extends Entity { apiVersion: typeof API_VERSION[number]; kind: typeof KIND; @@ -33,26 +61,8 @@ export interface GroupEntityV1alpha1 extends Entity { }; } -export class GroupEntityV1alpha1Policy implements EntityPolicy { - private schema: yup.Schema; - - constructor() { - this.schema = yup.object>({ - apiVersion: yup.string().required().oneOf(API_VERSION), - kind: yup.string().required().equals([KIND]), - spec: yup - .object({ - type: yup.string().required().min(1), - parent: yup.string().notRequired().min(1), - ancestors: yup.array(yup.string()).required(), - children: yup.array(yup.string()).required(), - descendants: yup.array(yup.string()).required(), - }) - .required(), - }); - } - - async enforce(envelope: Entity): Promise { - return await this.schema.validate(envelope, { strict: true }); - } -} +export const groupEntityV1alpha1Policy = schemaPolicy( + KIND, + API_VERSION, + schema, +); diff --git a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts index 62837ed500..a259eaeca8 100644 --- a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.test.ts @@ -14,15 +14,13 @@ * limitations under the License. */ -import { EntityPolicy } from '../types'; import { LocationEntityV1alpha1, - LocationEntityV1alpha1Policy, + locationEntityV1alpha1Policy as policy, } from './LocationEntityV1alpha1'; describe('LocationV1alpha1Policy', () => { let entity: LocationEntityV1alpha1; - let policy: EntityPolicy; beforeEach(() => { entity = { @@ -35,7 +33,6 @@ describe('LocationV1alpha1Policy', () => { type: 'github', }, }; - policy = new LocationEntityV1alpha1Policy(); }); it('happy path: accepts valid data', async () => { @@ -47,14 +44,14 @@ describe('LocationV1alpha1Policy', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); - it('rejects unknown apiVersion', async () => { + it('ignores unknown apiVersion', async () => { (entity as any).apiVersion = 'backstage.io/v1beta0'; - await expect(policy.enforce(entity)).rejects.toThrow(/apiVersion/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); - it('rejects unknown kind', async () => { + it('ignores unknown kind', async () => { (entity as any).kind = 'Wizard'; - await expect(policy.enforce(entity)).rejects.toThrow(/kind/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); it('rejects missing type', async () => { diff --git a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts index a69a3a574a..6d1f1f5515 100644 --- a/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/LocationEntityV1alpha1.ts @@ -16,11 +16,23 @@ import * as yup from 'yup'; import type { Entity } from '../entity/Entity'; -import type { EntityPolicy } from '../types'; +import { schemaPolicy } from './util'; const API_VERSION = ['backstage.io/v1alpha1', 'backstage.io/v1beta1'] as const; const KIND = 'Location' as const; +const schema = yup.object>({ + apiVersion: yup.string().required().oneOf(API_VERSION), + kind: yup.string().required().equals([KIND]), + spec: yup + .object({ + type: yup.string().required().min(1), + target: yup.string().notRequired().min(1), + targets: yup.array(yup.string()).notRequired(), + }) + .required(), +}); + export interface LocationEntityV1alpha1 extends Entity { apiVersion: typeof API_VERSION[number]; kind: typeof KIND; @@ -31,24 +43,8 @@ export interface LocationEntityV1alpha1 extends Entity { }; } -export class LocationEntityV1alpha1Policy implements EntityPolicy { - private schema: yup.Schema; - - constructor() { - this.schema = yup.object>({ - apiVersion: yup.string().required().oneOf(API_VERSION), - kind: yup.string().required().equals([KIND]), - spec: yup - .object({ - type: yup.string().required().min(1), - target: yup.string().notRequired().min(1), - targets: yup.array(yup.string()).notRequired(), - }) - .required(), - }); - } - - async enforce(envelope: Entity): Promise { - return await this.schema.validate(envelope, { strict: true }); - } -} +export const locationEntityV1alpha1Policy = schemaPolicy( + KIND, + API_VERSION, + schema, +); diff --git a/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.test.ts index ce9ed8bedd..86351b41aa 100644 --- a/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.test.ts +++ b/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.test.ts @@ -14,15 +14,13 @@ * limitations under the License. */ -import { EntityPolicy } from '../types'; import { TemplateEntityV1alpha1, - TemplateEntityV1alpha1Policy, + templateEntityV1alpha1Policy as policy, } from './TemplateEntityV1alpha1'; -describe('TemplateEntityV1alpah1', () => { +describe('templateEntityV1alpha1', () => { let entity: TemplateEntityV1alpha1; - let policy: EntityPolicy; beforeEach(() => { entity = { @@ -52,7 +50,6 @@ describe('TemplateEntityV1alpah1', () => { }, }, }; - policy = new TemplateEntityV1alpha1Policy(); }); it('happy path: accepts valid data', async () => { @@ -64,14 +61,14 @@ describe('TemplateEntityV1alpah1', () => { await expect(policy.enforce(entity)).resolves.toBe(entity); }); - it('rejects unknown apiVersion', async () => { + it('ignores unknown apiVersion', async () => { (entity as any).apiVersion = 'backstage.io/v1beta0'; - await expect(policy.enforce(entity)).rejects.toThrow(/apiVersion/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); - it('rejects unknown kind', async () => { + it('ignores unknown kind', async () => { (entity as any).kind = 'Wizard'; - await expect(policy.enforce(entity)).rejects.toThrow(/kind/); + await expect(policy.enforce(entity)).resolves.toBeUndefined(); }); it('rejects missing type', async () => { diff --git a/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.ts b/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.ts index 8aa79d57db..a26540fda2 100644 --- a/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.ts +++ b/packages/catalog-model/src/kinds/TemplateEntityV1alpha1.ts @@ -16,11 +16,25 @@ import * as yup from 'yup'; import type { Entity } from '../entity/Entity'; -import type { EntityPolicy, JSONSchema } from '../types'; +import type { JSONSchema } from '../types'; +import { schemaPolicy } from './util'; const API_VERSION = ['backstage.io/v1alpha1', 'backstage.io/v1beta1'] as const; const KIND = 'Template' as const; +const schema = yup.object>({ + apiVersion: yup.string().required().oneOf(API_VERSION), + kind: yup.string().required().equals([KIND]), + spec: yup + .object({ + type: yup.string().required().min(1), + path: yup.string(), + schema: yup.object().required(), + templater: yup.string().required(), + }) + .required(), +}); + export interface TemplateEntityV1alpha1 extends Entity { apiVersion: typeof API_VERSION[number]; kind: typeof KIND; @@ -32,25 +46,8 @@ export interface TemplateEntityV1alpha1 extends Entity { }; } -export class TemplateEntityV1alpha1Policy implements EntityPolicy { - private schema: yup.Schema; - - constructor() { - this.schema = yup.object>({ - apiVersion: yup.string().required().oneOf(API_VERSION), - kind: yup.string().required().equals([KIND]), - spec: yup - .object({ - type: yup.string().required().min(1), - path: yup.string(), - schema: yup.object().required(), - templater: yup.string().required(), - }) - .required(), - }); - } - - async enforce(envelope: Entity): Promise { - return await this.schema.validate(envelope, { strict: true }); - } -} +export const templateEntityV1alpha1Policy = schemaPolicy( + KIND, + API_VERSION, + schema, +); diff --git a/packages/catalog-model/src/kinds/UserEntityV1alpha1.test.ts b/packages/catalog-model/src/kinds/UserEntityV1alpha1.test.ts new file mode 100644 index 0000000000..97fe0888f1 --- /dev/null +++ b/packages/catalog-model/src/kinds/UserEntityV1alpha1.test.ts @@ -0,0 +1,157 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + UserEntityV1alpha1, + userEntityV1alpha1Policy as policy, +} from './UserEntityV1alpha1'; + +describe('userEntityV1alpha1Policy', () => { + let entity: UserEntityV1alpha1; + + beforeEach(() => { + entity = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'User', + metadata: { + name: 'doe', + }, + spec: { + profile: { + displayName: 'John Doe', + email: 'john@doe.org', + picture: 'https://doe.org/john.jpeg', + }, + memberOf: ['team-a', 'developers'], + }, + }; + }); + + it('happy path: accepts valid data', async () => { + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + // root + + it('silently accepts v1beta1 as well', async () => { + (entity as any).apiVersion = 'backstage.io/v1beta1'; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('ignores unknown apiVersion', async () => { + (entity as any).apiVersion = 'backstage.io/v1beta0'; + await expect(policy.enforce(entity)).resolves.toBeUndefined(); + }); + + it('ignores unknown kind', async () => { + (entity as any).kind = 'Wizard'; + await expect(policy.enforce(entity)).resolves.toBeUndefined(); + }); + + it('spec accepts unknown additional fields', async () => { + (entity as any).spec.foo = 'data'; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + // profile + + it('accepts missing profile', async () => { + delete (entity as any).spec.profile; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('rejects wrong profile', async () => { + (entity as any).spec.profile = 7; + await expect(policy.enforce(entity)).rejects.toThrow(/profile/); + }); + + it('profile accepts missing displayName', async () => { + delete (entity as any).spec.profile.displayName; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('profile rejects wrong displayName', async () => { + (entity as any).spec.profile.displayName = 7; + await expect(policy.enforce(entity)).rejects.toThrow(/displayName/); + }); + + it('profile rejects empty displayName', async () => { + (entity as any).spec.profile.displayName = ''; + await expect(policy.enforce(entity)).rejects.toThrow(/displayName/); + }); + + it('profile accepts missing email', async () => { + delete (entity as any).spec.profile.email; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('profile rejects wrong email', async () => { + (entity as any).spec.profile.email = 7; + await expect(policy.enforce(entity)).rejects.toThrow(/email/); + }); + + it('profile rejects empty email', async () => { + (entity as any).spec.profile.email = ''; + await expect(policy.enforce(entity)).rejects.toThrow(/email/); + }); + + it('profile accepts missing picture', async () => { + delete (entity as any).spec.profile.picture; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('profile rejects wrong picture', async () => { + (entity as any).spec.profile.picture = 7; + await expect(policy.enforce(entity)).rejects.toThrow(/picture/); + }); + + it('profile rejects empty picture', async () => { + (entity as any).spec.profile.picture = ''; + await expect(policy.enforce(entity)).rejects.toThrow(/picture/); + }); + + it('profile accepts unknown additional fields', async () => { + (entity as any).spec.profile.foo = 'data'; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + // memberOf + + it('rejects missing memberOf', async () => { + delete (entity as any).spec.memberOf; + await expect(policy.enforce(entity)).rejects.toThrow(/memberOf/); + }); + + it('rejects wrong memberOf', async () => { + (entity as any).spec.memberOf = 7; + await expect(policy.enforce(entity)).rejects.toThrow(/memberOf/); + }); + + it('rejects wrong memberOf item', async () => { + (entity as any).spec.memberOf[0] = 7; + await expect(policy.enforce(entity)).rejects.toThrow(/memberOf/); + }); + + it('accepts empty memberOf', async () => { + (entity as any).spec.memberOf = []; + await expect(policy.enforce(entity)).resolves.toBe(entity); + }); + + it('rejects null memberOf', async () => { + (entity as any).spec.memberOf = null; + await expect(policy.enforce(entity)).rejects.toThrow(/memberOf/); + }); +}); diff --git a/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts b/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts new file mode 100644 index 0000000000..ff4edcc8a2 --- /dev/null +++ b/packages/catalog-model/src/kinds/UserEntityV1alpha1.ts @@ -0,0 +1,60 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as yup from 'yup'; +import type { Entity } from '../entity/Entity'; +import { schemaPolicy } from './util'; + +const API_VERSION = ['backstage.io/v1alpha1', 'backstage.io/v1beta1'] as const; +const KIND = 'User' as const; + +const schema = yup.object>({ + apiVersion: yup.string().required().oneOf(API_VERSION), + kind: yup.string().required().equals([KIND]), + spec: yup + .object({ + profile: yup + .object({ + displayName: yup.string().min(1).notRequired(), + email: yup.string().min(1).notRequired(), + picture: yup.string().min(1).notRequired(), + }) + .notRequired(), + // Use this manual test because yup .required() requires at least one + // element and there is no simple workaround -_- + memberOf: yup.array(yup.string()).test({ + name: 'isDefined', + message: 'memberOf must be defined', + test: v => Boolean(v), + }), + }) + .required(), +}); + +export interface UserEntityV1alpha1 extends Entity { + apiVersion: typeof API_VERSION[number]; + kind: typeof KIND; + spec: { + profile?: { + displayName?: string; + email?: string; + picture?: string; + }; + memberOf: string[]; + }; +} + +export const userEntityV1alpha1Policy = schemaPolicy(KIND, API_VERSION, schema); diff --git a/packages/catalog-model/src/kinds/index.ts b/packages/catalog-model/src/kinds/index.ts index 6e8d27d204..6df4f1212a 100644 --- a/packages/catalog-model/src/kinds/index.ts +++ b/packages/catalog-model/src/kinds/index.ts @@ -14,28 +14,33 @@ * limitations under the License. */ -export { ComponentEntityV1alpha1Policy } from './ComponentEntityV1alpha1'; -export type { - ComponentEntityV1alpha1 as ComponentEntity, - ComponentEntityV1alpha1, -} from './ComponentEntityV1alpha1'; -export { GroupEntityV1alpha1Policy } from './GroupEntityV1alpha1'; -export type { - GroupEntityV1alpha1 as GroupEntity, - GroupEntityV1alpha1, -} from './GroupEntityV1alpha1'; -export { LocationEntityV1alpha1Policy } from './LocationEntityV1alpha1'; -export type { - LocationEntityV1alpha1 as LocationEntity, - LocationEntityV1alpha1, -} from './LocationEntityV1alpha1'; -export { TemplateEntityV1alpha1Policy } from './TemplateEntityV1alpha1'; -export type { - TemplateEntityV1alpha1 as TemplateEntity, - TemplateEntityV1alpha1, -} from './TemplateEntityV1alpha1'; -export { ApiEntityV1alpha1Policy } from './ApiEntityV1alpha1'; +export { apiEntityV1alpha1Policy } from './ApiEntityV1alpha1'; export type { ApiEntityV1alpha1 as ApiEntity, ApiEntityV1alpha1, } from './ApiEntityV1alpha1'; +export { componentEntityV1alpha1Policy } from './ComponentEntityV1alpha1'; +export type { + ComponentEntityV1alpha1 as ComponentEntity, + ComponentEntityV1alpha1, +} from './ComponentEntityV1alpha1'; +export { groupEntityV1alpha1Policy } from './GroupEntityV1alpha1'; +export type { + GroupEntityV1alpha1 as GroupEntity, + GroupEntityV1alpha1, +} from './GroupEntityV1alpha1'; +export { locationEntityV1alpha1Policy } from './LocationEntityV1alpha1'; +export type { + LocationEntityV1alpha1 as LocationEntity, + LocationEntityV1alpha1, +} from './LocationEntityV1alpha1'; +export { templateEntityV1alpha1Policy } from './TemplateEntityV1alpha1'; +export type { + TemplateEntityV1alpha1 as TemplateEntity, + TemplateEntityV1alpha1, +} from './TemplateEntityV1alpha1'; +export { userEntityV1alpha1Policy } from './UserEntityV1alpha1'; +export type { + UserEntityV1alpha1 as UserEntity, + UserEntityV1alpha1, +} from './UserEntityV1alpha1'; diff --git a/packages/catalog-model/src/kinds/util.ts b/packages/catalog-model/src/kinds/util.ts new file mode 100644 index 0000000000..491b2c5e2f --- /dev/null +++ b/packages/catalog-model/src/kinds/util.ts @@ -0,0 +1,37 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as yup from 'yup'; +import { Entity } from '../entity'; +import { EntityPolicy } from '../types'; + +export function schemaPolicy( + kind: string, + apiVersion: readonly string[], + schema: yup.Schema, +): EntityPolicy { + return { + async enforce(envelope: Entity): Promise { + if ( + kind !== envelope.kind || + !apiVersion.includes(envelope.apiVersion as any) + ) { + return undefined; + } + return await schema.validate(envelope, { strict: true }); + }, + }; +} diff --git a/packages/catalog-model/src/location/annotation.ts b/packages/catalog-model/src/location/annotation.ts index ab7a90249a..371d095685 100644 --- a/packages/catalog-model/src/location/annotation.ts +++ b/packages/catalog-model/src/location/annotation.ts @@ -13,4 +13,5 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + export const LOCATION_ANNOTATION = 'backstage.io/managed-by-location'; diff --git a/packages/catalog-model/src/types.ts b/packages/catalog-model/src/types.ts index cba6438ccb..aa96e46102 100644 --- a/packages/catalog-model/src/types.ts +++ b/packages/catalog-model/src/types.ts @@ -27,10 +27,37 @@ export type EntityPolicy = { * Applies validation or mutation on an entity. * * @param entity The entity, as validated/mutated so far in the policy tree - * @returns The incoming entity, or a mutated version of the same + * @returns The incoming entity, or a mutated version of the same, or + * undefined if this processor could not handle the entity * @throws An error if the entity should be rejected */ - enforce(entity: Entity): Promise; + enforce(entity: Entity): Promise; }; export type JSONSchema = JSONSchema7 & { [key in string]?: JsonValue }; + +/** + * A complete entity name, with the full kind-namespace-name triplet. + */ +export type EntityName = { + kind: string; + namespace: string; + name: string; +}; + +/** + * A reference by name to an entity, either as a compact string representation, + * or as a compound reference structure. + * + * The string representation is on the form [:][/]. + * + * Left-out parts of the reference need to be handled by the application, + * either by rejecting the reference or by falling back to default values. + */ +export type EntityRef = + | string + | { + kind?: string; + namespace?: string; + name: string; + }; diff --git a/packages/cli/config/tsconfig.json b/packages/cli/config/tsconfig.json index ef1a8df353..62609aad5b 100644 --- a/packages/cli/config/tsconfig.json +++ b/packages/cli/config/tsconfig.json @@ -11,7 +11,7 @@ "incremental": true, "isolatedModules": true, "jsx": "react", - "lib": ["DOM", "DOM.Iterable", "ScriptHost", "ES2019"], + "lib": ["DOM", "DOM.Iterable", "ScriptHost", "ES2019", "ESNext.Promise"], "module": "ESNext", "moduleResolution": "node", "noEmit": false, diff --git a/packages/cli/package.json b/packages/cli/package.json index 6f65658539..dc2ac1c5f7 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -54,7 +54,7 @@ "css-loader": "^3.5.3", "dashify": "^2.0.0", "diff": "^4.0.2", - "esbuild": "0.6.3", + "esbuild": "^0.7.7", "eslint": "^7.1.0", "eslint-formatter-friendly": "^7.0.0", "eslint-plugin-import": "^2.20.2", @@ -78,10 +78,10 @@ "rollup": "2.23.x", "rollup-plugin-dts": "1.4.11", "rollup-plugin-esbuild": "^2.0.0", - "rollup-plugin-image-files": "^1.4.2", "rollup-plugin-peer-deps-external": "^2.2.2", "rollup-plugin-postcss": "^3.1.1", - "rollup-plugin-typescript2": "^0.26.0", + "rollup-plugin-typescript2": "^0.27.3", + "rollup-pluginutils": "^2.8.2", "start-server-webpack-plugin": "^2.2.5", "style-loader": "^1.2.1", "sucrase": "^3.14.1", @@ -114,6 +114,7 @@ "@types/webpack": "^4.41.7", "@types/webpack-dev-server": "^3.10.0", "del": "^5.1.0", + "mock-fs": "^4.13.0", "nodemon": "^2.0.2", "ts-node": "^8.6.2" }, diff --git a/packages/cli/src/commands/create-plugin/createPlugin.ts b/packages/cli/src/commands/create-plugin/createPlugin.ts index 247812b6fd..cbaf956bdb 100644 --- a/packages/cli/src/commands/create-plugin/createPlugin.ts +++ b/packages/cli/src/commands/create-plugin/createPlugin.ts @@ -231,7 +231,11 @@ export default async (cmd: Command) => { const privatePackage = cmd.private === false ? false : true; const isMonoRepo = await fs.pathExists(paths.resolveTargetRoot('lerna.json')); const appPackage = paths.resolveTargetRoot('packages/app'); - const templateDir = paths.resolveOwn('templates/default-plugin'); + const templateDir = paths.resolveOwn( + cmd.backend + ? 'templates/default-backend-plugin' + : 'templates/default-plugin', + ); const tempDir = resolvePath(os.tmpdir(), answers.id); const pluginDir = isMonoRepo ? paths.resolveTargetRoot('plugins', answers.id) @@ -252,6 +256,7 @@ export default async (cmd: Command) => { await createTemporaryPluginFolder(tempDir); Task.section('Preparing files'); + await templatingTask(templateDir, tempDir, { ...answers, version, @@ -267,7 +272,7 @@ export default async (cmd: Command) => { Task.section('Building the plugin'); await buildPlugin(pluginDir); - if (await fs.pathExists(appPackage)) { + if ((await fs.pathExists(appPackage)) && !cmd.backend) { Task.section('Adding plugin as dependency in app'); await addPluginDependencyToApp(paths.targetRoot, name, version); diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts index f1828cef84..fea250cd55 100644 --- a/packages/cli/src/commands/index.ts +++ b/packages/cli/src/commands/index.ts @@ -61,6 +61,10 @@ export function registerCommands(program: CommanderStatic) { program .command('create-plugin') + .option( + '--backend', + 'Create plugin with the backend dependencies as default', + ) .description('Creates a new plugin in the current repository') .option('--scope ', 'NPM scope') .option('--npm-registry ', 'NPM registry URL') diff --git a/packages/cli/src/lib/builder/config.ts b/packages/cli/src/lib/builder/config.ts index afcedaae59..2566460494 100644 --- a/packages/cli/src/lib/builder/config.ts +++ b/packages/cli/src/lib/builder/config.ts @@ -22,13 +22,13 @@ import commonjs from '@rollup/plugin-commonjs'; import resolve from '@rollup/plugin-node-resolve'; import postcss from 'rollup-plugin-postcss'; import esbuild from 'rollup-plugin-esbuild'; -import imageFiles from 'rollup-plugin-image-files'; import svgr from '@svgr/rollup'; import dts from 'rollup-plugin-dts'; import json from '@rollup/plugin-json'; import yaml from '@rollup/plugin-yaml'; import { RollupOptions, OutputOptions } from 'rollup'; +import { forwardFileImports } from './plugins'; import { BuildOptions, Output } from './types'; import { paths } from '../paths'; import { svgrTemplate } from '../svgrTemplate'; @@ -92,7 +92,7 @@ export const makeConfigs = async ( exclude: [/\/[^/]+\.(?:stories|test)\.[^/]+$/], }), postcss(), - imageFiles({ + forwardFileImports({ exclude: /\.icon\.svg$/, include: [/\.svg$/, /\.png$/, /\.gif$/, /\.jpg$/, /\.jpeg$/], }), diff --git a/packages/cli/src/lib/builder/plugins.test.ts b/packages/cli/src/lib/builder/plugins.test.ts new file mode 100644 index 0000000000..41504a700e --- /dev/null +++ b/packages/cli/src/lib/builder/plugins.test.ts @@ -0,0 +1,178 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs-extra'; +import mockFs from 'mock-fs'; +import { + NormalizedOutputOptions, + OutputAsset, + OutputChunk, + PluginContext, +} from 'rollup'; + +import { forwardFileImports } from './plugins'; + +const context = { + meta: { + rollupVersion: '0.0.0', + watchMode: false, + }, +} as PluginContext; + +describe('forwardFileImports', () => { + it('should be created', () => { + const plugin = forwardFileImports({ include: /\.png$/ }); + expect(plugin.name).toBe('forward-file-imports'); + }); + + it('should call through to original external option', () => { + const plugin = forwardFileImports({ include: /\.png$/ }); + const external = jest.fn((id: string) => id.endsWith('external')); + + const options = plugin.options?.call(context, { external })!; + if (typeof options.external !== 'function') { + throw new Error('options.external is not a function'); + } + + expect(external).toHaveBeenCalledTimes(0); + expect(options.external('./my-module', '/dev/src/index.ts', false)).toBe( + false, + ); + expect(external).toHaveBeenCalledTimes(1); + expect(options.external('./my-external', '/dev/src/index.ts', false)).toBe( + true, + ); + expect(external).toHaveBeenCalledTimes(2); + expect(options.external('./my-image.png', '/dev/src/index.ts', false)).toBe( + true, + ); + expect(external).toHaveBeenCalledTimes(3); + expect(options.external('./my-image.png', '/dev/src/index.ts', true)).toBe( + true, + ); + expect(external).toHaveBeenCalledTimes(4); + + expect(() => + (options as any).external('./my-image.png', undefined, false), + ).toThrow('Unknown importer of file module ./my-image.png'); + }); + + it('should handle original external array', () => { + const plugin = forwardFileImports({ include: /\.png$/ }); + + const options = plugin.options?.call(context, { + external: ['my-external'], + })!; + if (typeof options.external !== 'function') { + throw new Error('options.external is not a function'); + } + + expect(options.external('my-module', '/dev/src/index.ts', false)).toBe( + false, + ); + expect(options.external('my-external', '/dev/src/index.ts', false)).toBe( + true, + ); + expect(options.external('my-image.png', '/dev/src/index.ts', false)).toBe( + true, + ); + }); + + describe('with mock fs', () => { + beforeEach(() => { + mockFs({ + '/dev/src/my-module.ts': '', + '/dev/src/dir/my-image.png': 'my-image', + }); + }); + + afterEach(() => { + mockFs.restore(); + }); + + it('should extract files', async () => { + const plugin = forwardFileImports({ include: /\.png$/ }); + + const options = plugin.options?.call(context, {})!; + if (typeof options.external !== 'function') { + throw new Error('options.external is not a function'); + } + + expect(options.external('./my-module', '/dev/src/index.ts', false)).toBe( + false, + ); + expect( + options.external('./my-image.png', '/dev/src/dir/index.ts', false), + ).toBe(true); + + const outPath = '/dev/dist/dir/my-image.png'; + await expect(fs.pathExists(outPath)).resolves.toBe(false); + + await plugin.generateBundle?.call( + context, + { dir: '/dev/dist' } as NormalizedOutputOptions, + { + ['index.js']: { + type: 'chunk', + facadeModuleId: '/dev/src/index.ts', + } as OutputChunk, + }, + false, // isWrite = false -> no write + ); + await expect(fs.pathExists(outPath)).resolves.toBe(false); + + await plugin.generateBundle?.call( + context, + { dir: '/dev/dist' } as NormalizedOutputOptions, + { + // output assets should not cause a write + ['index.js']: { type: 'asset' } as OutputAsset, + // missing facadeModuleId should not cause a write either + ['index2.js']: { type: 'chunk' } as OutputChunk, + }, + true, + ); + await expect(fs.pathExists(outPath)).resolves.toBe(false); + + // output chunk + isWrite -> generate files + await plugin.generateBundle?.call( + context, + { dir: '/dev/dist' } as NormalizedOutputOptions, + { + ['index.js']: { + type: 'chunk', + facadeModuleId: '/dev/src/index.ts', + } as OutputChunk, + }, + true, + ); + await expect(fs.pathExists(outPath)).resolves.toBe(true); + + // should not break when triggering another write + await plugin.generateBundle?.call( + context, + { file: '/dev/dist/my-output.js' } as NormalizedOutputOptions, + { + ['index.js']: { + type: 'chunk', + facadeModuleId: '/dev/src/index.ts', + } as OutputChunk, + }, + true, + ); + }); + }); +}); diff --git a/packages/cli/src/lib/builder/plugins.ts b/packages/cli/src/lib/builder/plugins.ts new file mode 100644 index 0000000000..48b6b65c61 --- /dev/null +++ b/packages/cli/src/lib/builder/plugins.ts @@ -0,0 +1,135 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fs from 'fs-extra'; +import { + dirname, + resolve as resolvePath, + relative as relativePath, +} from 'path'; +import { createFilter } from 'rollup-pluginutils'; +import { Plugin, InputOptions, OutputChunk } from 'rollup'; + +type ForwardFileImportsOptions = { + include: Array | string | RegExp | null; + exclude?: Array | string | RegExp | null; +}; + +/** + * This rollup plugin leaves all encountered asset imports as-is, but + * copies the imported files into the output directory. + * + * For example `import ImageUrl from './my-image.png'` inside `src/MyComponent` will + * cause `src/MyComponent/my-image.png` to be copied to the output directory at the + * path `dist/MyComponent/my-image.png`. The import itself will stay, but be resolved, + * resulting in something like `import ImageUrl from './MyComponent/my-image.png'` + */ +export function forwardFileImports(options: ForwardFileImportsOptions): Plugin { + const filter = createFilter(options.include, options.exclude); + + // We collect the absolute paths to all files we want to bundle into the + // output dir here. Resolving to relative paths in the output dir happens later. + const exportedFiles = new Set(); + + // We keep track of output directories that we've already copied files + // into, so that we don't duplicate that work + const generatedFor = new Set(); + + return { + name: 'forward-file-imports', + async generateBundle(outputOptions, bundle, isWrite) { + if (!isWrite) { + return; + } + + const dir = outputOptions.dir || dirname(outputOptions.file!); + if (generatedFor.has(dir)) { + return; + } + + for (const output of Object.values(bundle)) { + if (output.type !== 'chunk') { + continue; + } + const chunk = output as OutputChunk; + + // This'll be an absolute path pointing to the initial index file of the + // build, and we use it to find the location of the `src` dir + if (!chunk.facadeModuleId) { + continue; + } + generatedFor.add(dir); + + // We're assuming that the index file is at the root of the source dir, and + // that all assets exist within that dir. + const srcRoot = dirname(chunk.facadeModuleId); + + // Copy all the files we found into the dist dir + await Promise.all( + Array.from(exportedFiles).map(async exportedFile => { + const outputPath = relativePath(srcRoot, exportedFile); + const targetFile = resolvePath(dir, outputPath); + + await fs.ensureDir(dirname(targetFile)); + await fs.copyFile(exportedFile, targetFile); + }), + ); + return; + } + }, + options(inputOptions) { + const origExternal = inputOptions.external; + + // We decorate any existing `external` option with our own way of determining + // if a module should be external. The can't use `resolveId`, since asset files + // aren't passed there, might be some better way to do this though. + const external: InputOptions['external'] = (id, importer, isResolved) => { + // Call to inner external option + if ( + typeof origExternal === 'function' && + origExternal(id, importer, isResolved) + ) { + return true; + } + + if (Array.isArray(origExternal) && origExternal.includes(id)) { + return true; + } + + // The piece that we're adding + if (!filter(id)) { + return false; + } + + // Sanity check, dunno if this can happen + if (!importer) { + throw new Error(`Unknown importer of file module ${id}`); + } + + // Resolve relative imports to the full file URL, for deduping and copying later + const fullId = isResolved ? id : resolvePath(dirname(importer), id); + exportedFiles.add(fullId); + + // Treating this module as external from here, meaning rollup won't try to + // put it in the output bundle, but still keep track of the relative imports + // as needed in the output code. + return true; + }; + + return { ...inputOptions, external }; + }, + }; +} diff --git a/plugins/identity-backend/.eslintrc.js b/packages/cli/templates/default-backend-plugin/.eslintrc.js similarity index 100% rename from plugins/identity-backend/.eslintrc.js rename to packages/cli/templates/default-backend-plugin/.eslintrc.js diff --git a/packages/cli/templates/default-backend-plugin/README.md.hbs b/packages/cli/templates/default-backend-plugin/README.md.hbs new file mode 100644 index 0000000000..5c34b40360 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/README.md.hbs @@ -0,0 +1,14 @@ +# {{id}} + +Welcome to the {{id}} backend plugin! + +_This plugin was created through the Backstage CLI_ + +## Getting started + +Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn +start` in the root directory, and then navigating to [/{{id}}](http://localhost:3000/{{id}}). + +You can also serve the plugin in isolation by running `yarn start` in the plugin directory. +This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads. +It is only meant for local development, and the setup for it can be found inside the [/dev](/dev) directory. diff --git a/packages/cli/templates/default-backend-plugin/package.json.hbs b/packages/cli/templates/default-backend-plugin/package.json.hbs new file mode 100644 index 0000000000..40e612609a --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/package.json.hbs @@ -0,0 +1,44 @@ +{ + "name": "{{name}}", + "version": "{{version}}", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + {{#if privatePackage}} "private": {{privatePackage}}, + {{/if}} + "publishConfig": { + {{#if npmRegistry}} "registry": "{{npmRegistry}}", + {{/if}} + "access": "public", + "main": "dist/index.cjs.js", + "types": "dist/index.d.ts" + }, + "scripts": { + "start": "backstage-cli backend:dev", + "build": "backstage-cli backend:build", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/backend-common": "^{{version}}", + "@backstage/config": "^{{version}}", + "@types/express": "^4.17.6", + "express": "^4.17.1", + "express-promise-router": "^3.0.3", + "winston": "^3.2.1", + "node-fetch": "^2.6.1", + "yn": "^4.0.0" + }, + "devDependencies": { + "@backstage/cli": "^{{version}}", + "@types/supertest": "^2.0.8", + "supertest": "^4.0.2", + "msw": "^0.20.5" + }, + "files": [ + "dist" + ] + } diff --git a/plugins/identity-backend/src/index.ts b/packages/cli/templates/default-backend-plugin/src/index.ts similarity index 100% rename from plugins/identity-backend/src/index.ts rename to packages/cli/templates/default-backend-plugin/src/index.ts diff --git a/plugins/identity-backend/src/run.ts b/packages/cli/templates/default-backend-plugin/src/run.ts.hbs similarity index 98% rename from plugins/identity-backend/src/run.ts rename to packages/cli/templates/default-backend-plugin/src/run.ts.hbs index a2c2601258..b96989e4b8 100644 --- a/plugins/identity-backend/src/run.ts +++ b/packages/cli/templates/default-backend-plugin/src/run.ts.hbs @@ -14,11 +14,11 @@ * limitations under the License. */ -import yn from 'yn'; import { getRootLogger } from '@backstage/backend-common'; +import yn from 'yn'; import { startStandaloneServer } from './service/standaloneServer'; -const port = process.env.PLUGIN_PORT ? Number(process.env.PLUGIN_PORT) : 3003; +const port = process.env.PLUGIN_PORT ? Number(process.env.PLUGIN_PORT) : 7000; const enableCors = yn(process.env.PLUGIN_CORS, { default: false }); const logger = getRootLogger(); diff --git a/packages/cli/templates/default-backend-plugin/src/service/router.test.ts b/packages/cli/templates/default-backend-plugin/src/service/router.test.ts new file mode 100644 index 0000000000..0aaeafa379 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/service/router.test.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getVoidLogger } from '@backstage/backend-common'; +import express from 'express'; +import request from 'supertest'; + +import { createRouter } from './router'; + +describe('createRouter', () => { + let app: express.Express; + + beforeAll(async () => { + const router = await createRouter({ + logger: getVoidLogger(), + }); + app = express().use(router); + }); + + beforeEach(() => { + jest.resetAllMocks(); + }); + + describe('GET /health', () => { + it('returns ok', async () => { + const response = await request(app).get('/health'); + + expect(response.status).toEqual(200); + expect(response.body).toEqual({ status: 'ok' }); + }); + }); +}); diff --git a/plugins/identity-backend/src/service/router.ts b/packages/cli/templates/default-backend-plugin/src/service/router.ts similarity index 60% rename from plugins/identity-backend/src/service/router.ts rename to packages/cli/templates/default-backend-plugin/src/service/router.ts index 9d16e8f332..3ea8219365 100644 --- a/plugins/identity-backend/src/service/router.ts +++ b/packages/cli/templates/default-backend-plugin/src/service/router.ts @@ -14,37 +14,27 @@ * limitations under the License. */ +import { errorHandler } from '@backstage/backend-common'; import express from 'express'; import Router from 'express-promise-router'; import { Logger } from 'winston'; -import { StaticJsonAdapter } from '../adapters'; -import { IdentityApi } from '../adapters/types'; -import { userGroups } from '../adapters/userGroups'; export interface RouterOptions { logger: Logger; } -const makeRouter = (adapter: IdentityApi): express.Router => { - const router = Router(); - router.use(express.json()); - - router.get('/users/:user/groups', async (req, res) => { - const user = req.params.user; - const type = req.query.type?.toString() ?? ''; - const response = await adapter.getUserGroups({ user, type }); - res.send(response); - }); - - return router; -}; - export async function createRouter( options: RouterOptions, ): Promise { - const logger = options.logger; + const { logger } = options; - logger.info('Initializing identity API backend'); - const adapter = new StaticJsonAdapter(userGroups); - return makeRouter(adapter); + const router = Router(); + router.use(express.json()); + + router.get('/health', (_, response) => { + logger.info('PONG!'); + response.send({ status: 'ok' }); + }); + router.use(errorHandler()); + return router; } diff --git a/plugins/identity-backend/src/service/standaloneServer.ts b/packages/cli/templates/default-backend-plugin/src/service/standaloneServer.ts.hbs similarity index 59% rename from plugins/identity-backend/src/service/standaloneServer.ts rename to packages/cli/templates/default-backend-plugin/src/service/standaloneServer.ts.hbs index 42231b45a9..6e38965246 100644 --- a/plugins/identity-backend/src/service/standaloneServer.ts +++ b/packages/cli/templates/default-backend-plugin/src/service/standaloneServer.ts.hbs @@ -5,7 +5,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,9 +14,10 @@ * limitations under the License. */ +import { createServiceBuilder } from '@backstage/backend-common'; import { Server } from 'http'; import { Logger } from 'winston'; -import { createStandaloneApplication } from './standaloneApplication'; +import { createRouter } from './router'; export interface ServerOptions { port: number; @@ -27,24 +28,20 @@ export interface ServerOptions { export async function startStandaloneServer( options: ServerOptions, ): Promise { - const logger = options.logger.child({ service: 'identity-backend' }); - - logger.debug('Creating application...'); - const app = await createStandaloneApplication({ - enableCors: options.enableCors, + const logger = options.logger.child({ service: '{{id}}-backend' }); + logger.debug('Starting application server...'); + const router = await createRouter({ logger, }); - logger.debug('Starting application server...'); - return await new Promise((resolve, reject) => { - const server = app.listen(options.port, (err?: Error) => { - if (err) { - reject(err); - return; - } + const service = createServiceBuilder(module) + .enableCors({ origin: 'http://localhost:3000' }) + .addRouter('/{{id}}', router); - logger.info(`Listening on port ${options.port}`); - resolve(server); - }); + return await service.start().catch(err => { + logger.error(err); + process.exit(1); }); } + +module.hot?.accept(); diff --git a/packages/cli/templates/default-backend-plugin/src/setupTests.ts b/packages/cli/templates/default-backend-plugin/src/setupTests.ts new file mode 100644 index 0000000000..a5907fd52f --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/setupTests.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export {}; +global.fetch = require('node-fetch'); diff --git a/packages/cli/templates/default-plugin/package.json.hbs b/packages/cli/templates/default-plugin/package.json.hbs index 52cffeb621..e024884547 100644 --- a/packages/cli/templates/default-plugin/package.json.hbs +++ b/packages/cli/templates/default-plugin/package.json.hbs @@ -41,7 +41,8 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs b/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs index 37759313ee..fdb39444d8 100644 --- a/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs +++ b/packages/cli/templates/default-plugin/src/components/ExampleComponent/ExampleComponent.test.tsx.hbs @@ -1,18 +1,34 @@ import React from 'react'; import { render } from '@testing-library/react'; -import mockFetch from 'jest-fetch-mock'; import ExampleComponent from './ExampleComponent'; import { ThemeProvider } from '@material-ui/core'; import { lightTheme } from '@backstage/theme'; +import { rest } from 'msw'; +import { setupServer } from 'msw/node'; + describe('ExampleComponent', () => { + const server = setupServer(); + // Enable API mocking before tests. + beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) + + // Reset any runtime request handlers we may add during the tests. + afterEach(() => server.resetHandlers()) + + // Disable API mocking after the tests are done. + afterAll(() => server.close()) + + // setup mock response + beforeEach(() => { + server.use(rest.get('/*', (_, res, ctx) => res(ctx.status(200), ctx.json({})))) + }) + it('should render', () => { - mockFetch.mockResponse(() => new Promise(() => {})); const rendered = render( , - ); - expect(rendered.getByText('Welcome to {{ id }}!')).toBeInTheDocument(); + ); + expect(rendered.getByText('Welcome to {{ id }}!')).toBeInTheDocument(); }); }); diff --git a/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs b/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs index cc61c215cd..ca1990b4bc 100644 --- a/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs +++ b/packages/cli/templates/default-plugin/src/components/ExampleFetchComponent/ExampleFetchComponent.test.tsx.hbs @@ -1,11 +1,25 @@ import React from 'react'; import { render } from '@testing-library/react'; -import mockFetch from 'jest-fetch-mock'; import ExampleFetchComponent from './ExampleFetchComponent'; +import { rest } from 'msw'; +import { setupServer } from 'msw/node'; describe('ExampleFetchComponent', () => { + const server = setupServer(); + // Enable API mocking before tests. + beforeAll(() => server.listen({ onUnhandledRequest: 'error' })) + + // Reset any runtime request handlers we may add during the tests. + afterEach(() => server.resetHandlers()) + + // Disable API mocking after the tests are done. + afterAll(() => server.close()) + + // setup mock response + beforeEach(() => { + server.use(rest.get('https://randomuser.me/*', (_, res, ctx) => res(ctx.status(200), ctx.delay(2000), ctx.json({})))) + }) it('should render', async () => { - mockFetch.mockResponse(() => new Promise(() => {})); const rendered = render(); expect(await rendered.findByTestId('progress')).toBeInTheDocument(); }); diff --git a/packages/cli/templates/default-plugin/src/setupTests.ts b/packages/cli/templates/default-plugin/src/setupTests.ts index 3fa8703ac4..cc559f672e 100644 --- a/packages/cli/templates/default-plugin/src/setupTests.ts +++ b/packages/cli/templates/default-plugin/src/setupTests.ts @@ -1,3 +1,2 @@ import '@testing-library/jest-dom'; - -require('jest-fetch-mock').enableMocks(); +global.fetch = require('node-fetch'); diff --git a/packages/core-api/src/apis/definitions/auth.ts b/packages/core-api/src/apis/definitions/auth.ts index 800a865fea..109f15b26e 100644 --- a/packages/core-api/src/apis/definitions/auth.ts +++ b/packages/core-api/src/apis/definitions/auth.ts @@ -310,3 +310,13 @@ export const oauth2ApiRef = createApiRef< id: 'core.auth.oauth2', description: 'Example of how to use oauth2 custom provider', }); + +/** + * Provides authentication for saml based identity providers + */ +export const samlAuthApiRef = createApiRef< + ProfileInfoApi & BackstageIdentityApi & SessionApi +>({ + id: 'core.auth.saml', + description: 'Example of how to use SAML custom provider', +}); diff --git a/packages/core-api/src/apis/implementations/auth/gitlab/GitlabAuth.test.ts b/packages/core-api/src/apis/implementations/auth/gitlab/GitlabAuth.test.ts index 44b9aeb14e..6a592c7fbe 100644 --- a/packages/core-api/src/apis/implementations/auth/gitlab/GitlabAuth.test.ts +++ b/packages/core-api/src/apis/implementations/auth/gitlab/GitlabAuth.test.ts @@ -39,12 +39,12 @@ describe('GitlabAuth', () => { ], ['read_repository sudo', ['read_repository', 'sudo']], ])(`should normalize scopes correctly - %p`, (scope, scopes) => { - const googleAuth = GitlabAuth.create({ + const gitlabAuth = GitlabAuth.create({ oauthRequestApi: new MockOAuthApi(), discoveryApi: UrlPatternDiscovery.compile('http://example.com'), }); - googleAuth.getAccessToken(scope); + gitlabAuth.getAccessToken(scope); expect(getSession).toHaveBeenCalledWith({ scopes: new Set(scopes) }); }); }); diff --git a/packages/core-api/src/apis/implementations/auth/index.ts b/packages/core-api/src/apis/implementations/auth/index.ts index a6d7e2c989..39223e8e15 100644 --- a/packages/core-api/src/apis/implementations/auth/index.ts +++ b/packages/core-api/src/apis/implementations/auth/index.ts @@ -19,5 +19,6 @@ export * from './gitlab'; export * from './google'; export * from './oauth2'; export * from './okta'; +export * from './saml'; export * from './auth0'; export * from './microsoft'; diff --git a/packages/core-api/src/apis/implementations/auth/saml/SamlAuth.ts b/packages/core-api/src/apis/implementations/auth/saml/SamlAuth.ts new file mode 100644 index 0000000000..973b402756 --- /dev/null +++ b/packages/core-api/src/apis/implementations/auth/saml/SamlAuth.ts @@ -0,0 +1,104 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import SamlIcon from '@material-ui/icons/AcUnit'; +import { DirectAuthConnector } from '../../../../lib/AuthConnector'; +import { SessionManager } from '../../../../lib/AuthSessionManager/types'; +import { Observable } from '../../../../types'; +import { + ProfileInfo, + BackstageIdentity, + SessionState, + AuthRequestOptions, + ProfileInfoApi, + BackstageIdentityApi, + SessionApi, +} from '../../../definitions/auth'; +import { AuthProvider, DiscoveryApi } from '../../../definitions'; +import { SamlSession } from './types'; +import { + AuthSessionStore, + StaticAuthSessionManager, +} from '../../../../lib/AuthSessionManager'; + +type CreateOptions = { + discoveryApi: DiscoveryApi; + environment?: string; + provider?: AuthProvider & { id: string }; +}; + +export type SamlAuthResponse = { + profile: ProfileInfo; + backstageIdentity: BackstageIdentity; +}; + +const DEFAULT_PROVIDER = { + id: 'saml', + title: 'SAML', + icon: SamlIcon, +}; + +class SamlAuth implements ProfileInfoApi, BackstageIdentityApi, SessionApi { + static create({ + discoveryApi, + environment = 'development', + provider = DEFAULT_PROVIDER, + }: CreateOptions) { + const connector = new DirectAuthConnector({ + discoveryApi, + environment, + provider, + }); + + const sessionManager = new StaticAuthSessionManager({ + connector, + }); + + const authSessionStore = new AuthSessionStore({ + manager: sessionManager, + storageKey: 'samlSession', + }); + + return new SamlAuth(authSessionStore); + } + + sessionState$(): Observable { + return this.sessionManager.sessionState$(); + } + + constructor(private readonly sessionManager: SessionManager) {} + + async signIn() { + await this.getBackstageIdentity({}); + } + async signOut() { + await this.sessionManager.removeSession(); + } + + async getBackstageIdentity( + options: AuthRequestOptions, + ): Promise { + const session = await this.sessionManager.getSession(options); + return session?.backstageIdentity; + } + + async getProfile(options: AuthRequestOptions = {}) { + const session = await this.sessionManager.getSession(options); + return session?.profile; + } +} + +export default SamlAuth; diff --git a/packages/core-api/src/apis/implementations/auth/saml/index.ts b/packages/core-api/src/apis/implementations/auth/saml/index.ts new file mode 100644 index 0000000000..c2436ab435 --- /dev/null +++ b/packages/core-api/src/apis/implementations/auth/saml/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { default as SamlAuth } from './SamlAuth'; diff --git a/packages/core-api/src/apis/implementations/auth/saml/types.ts b/packages/core-api/src/apis/implementations/auth/saml/types.ts new file mode 100644 index 0000000000..296f70b0ea --- /dev/null +++ b/packages/core-api/src/apis/implementations/auth/saml/types.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ProfileInfo, BackstageIdentity } from '../../../definitions'; + +export type SamlSession = { + userId: string; + profile: ProfileInfo; + backstageIdentity: BackstageIdentity; +}; diff --git a/packages/core-api/src/lib/AuthConnector/DirectAuthConnector.ts b/packages/core-api/src/lib/AuthConnector/DirectAuthConnector.ts new file mode 100644 index 0000000000..517bf82ae7 --- /dev/null +++ b/packages/core-api/src/lib/AuthConnector/DirectAuthConnector.ts @@ -0,0 +1,89 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + AuthProvider, + ProfileInfo, + BackstageIdentity, + DiscoveryApi, +} from '../../apis/definitions'; +import { showLoginPopup } from '../loginPopup'; + +type Options = { + discoveryApi: DiscoveryApi; + environment?: string; + provider: AuthProvider & { id: string }; +}; + +export type DirectAuthResponse = { + userId: string; + profile: ProfileInfo; + backstageIdentity: BackstageIdentity; +}; + +export class DirectAuthConnector { + private readonly discoveryApi: DiscoveryApi; + private readonly environment: string | undefined; + private readonly provider: AuthProvider & { id: string }; + + constructor(options: Options) { + const { discoveryApi, environment, provider } = options; + + this.discoveryApi = discoveryApi; + this.environment = environment; + this.provider = provider; + } + + async createSession(): Promise { + const popupUrl = await this.buildUrl('/start'); + const payload = await showLoginPopup({ + url: popupUrl, + name: `${this.provider.title} Login`, + origin: new URL(popupUrl).origin, + width: 450, + height: 730, + }); + + return { + ...payload, + id: payload.profile.email, + }; + } + + async refreshSession(): Promise {} + + async removeSession(): Promise { + const res = await fetch(await this.buildUrl('/logout'), { + method: 'POST', + headers: { + 'x-requested-with': 'XMLHttpRequest', + }, + credentials: 'include', + }).catch(error => { + throw new Error(`Logout request failed, ${error}`); + }); + + if (!res.ok) { + const error: any = new Error(`Logout request failed, ${res.statusText}`); + error.status = res.status; + throw error; + } + } + + private async buildUrl(path: string): Promise { + const baseUrl = await this.discoveryApi.getBaseUrl('auth'); + return `${baseUrl}/${this.provider.id}${path}?env=${this.environment}`; + } +} diff --git a/packages/core-api/src/lib/AuthConnector/index.ts b/packages/core-api/src/lib/AuthConnector/index.ts index db5c582328..388619e2c1 100644 --- a/packages/core-api/src/lib/AuthConnector/index.ts +++ b/packages/core-api/src/lib/AuthConnector/index.ts @@ -15,4 +15,5 @@ */ export { DefaultAuthConnector } from './DefaultAuthConnector'; +export { DirectAuthConnector } from './DirectAuthConnector'; export * from './types'; diff --git a/packages/core-api/src/lib/AuthSessionManager/AuthSessionStore.ts b/packages/core-api/src/lib/AuthSessionManager/AuthSessionStore.ts index f2b8558f74..e82557b1ce 100644 --- a/packages/core-api/src/lib/AuthSessionManager/AuthSessionStore.ts +++ b/packages/core-api/src/lib/AuthSessionManager/AuthSessionStore.ts @@ -28,7 +28,7 @@ type Options = { /** Storage key to use to store sessions */ storageKey: string; /** Used to get the scope of the session */ - sessionScopes: SessionScopesFunc; + sessionScopes?: SessionScopesFunc; /** Used to check if the session needs to be refreshed, defaults to never refresh */ sessionShouldRefresh?: SessionShouldRefreshFunc; }; diff --git a/packages/core-api/src/lib/AuthSessionManager/StaticAuthSessionManager.ts b/packages/core-api/src/lib/AuthSessionManager/StaticAuthSessionManager.ts index e59c11421c..e02b600828 100644 --- a/packages/core-api/src/lib/AuthSessionManager/StaticAuthSessionManager.ts +++ b/packages/core-api/src/lib/AuthSessionManager/StaticAuthSessionManager.ts @@ -23,7 +23,7 @@ type Options = { /** The connector used for acting on the auth session */ connector: AuthConnector; /** Used to get the scope of the session */ - sessionScopes: (session: T) => Set; + sessionScopes?: (session: T) => Set; /** The default scopes that should always be present in a session, defaults to none. */ defaultScopes?: Set; }; diff --git a/packages/core-api/src/lib/AuthSessionManager/common.ts b/packages/core-api/src/lib/AuthSessionManager/common.ts index 83b81bc81a..ff2897535d 100644 --- a/packages/core-api/src/lib/AuthSessionManager/common.ts +++ b/packages/core-api/src/lib/AuthSessionManager/common.ts @@ -29,7 +29,7 @@ export function hasScopes( } type ScopeHelperOptions = { - sessionScopes: SessionScopesFunc; + sessionScopes: SessionScopesFunc | undefined; defaultScopes?: Set; }; @@ -46,13 +46,16 @@ export class SessionScopeHelper { if (!scopes) { return true; } + if (this.options.sessionScopes === undefined) { + return true; + } const sessionScopes = this.options.sessionScopes(session); return hasScopes(sessionScopes, scopes); } getExtendedScope(session: T | undefined, scopes?: Set) { const newScope = new Set(this.options.defaultScopes); - if (session) { + if (session && this.options.sessionScopes !== undefined) { const sessionScopes = this.options.sessionScopes(session); for (const scope of sessionScopes) { newScope.add(scope); diff --git a/packages/core-api/src/routing/RouteRef.ts b/packages/core-api/src/routing/RouteRef.ts index 9f9980ed0c..c33335cb38 100644 --- a/packages/core-api/src/routing/RouteRef.ts +++ b/packages/core-api/src/routing/RouteRef.ts @@ -14,30 +14,78 @@ * limitations under the License. */ -import type { RouteRefConfig, RouteRefOverrideConfig } from './types'; +import { + ConcreteRoute, + routeReference, + ReferencedRoute, + resolveRoute, + RouteRefConfig, +} from './types'; +import { generatePath } from 'react-router-dom'; -export class MutableRouteRef { - private effectiveConfig: RouteRefConfig = this.config; +type SubRouteConfig = { + path: string; +}; +export class SubRouteRef + implements ReferencedRoute { + constructor( + private readonly parent: ConcreteRoute, + private readonly config: SubRouteConfig, + ) {} + + get [routeReference]() { + return this; + } + + link(...args: Args): ConcreteRoute { + return { + [routeReference]: this, + [resolveRoute]: (path: string) => { + const ownPart = generatePath(this.config.path, args[0] ?? {}); + const parentPart = this.parent[resolveRoute](path); + return parentPart + ownPart; + }, + }; + } +} + +export class AbsoluteRouteRef implements ConcreteRoute { constructor(private readonly config: RouteRefConfig) {} - override(overrideConfig: RouteRefOverrideConfig) { - this.effectiveConfig = { ...this.config, ...overrideConfig }; - } - get icon() { - return this.effectiveConfig.icon; + return this.config.icon; } + // TODO(Rugvip): Remove this, routes are looked up via the registry instead get path() { - return this.effectiveConfig.path; + return this.config.path; } get title() { - return this.effectiveConfig.title; + return this.config.title; + } + + createSubRoute( + config: SubRouteConfig, + ) { + return new SubRouteRef(this, config); + } + + get [routeReference]() { + return this; + } + + [resolveRoute](path: string) { + return path; } } -export function createRouteRef(config: RouteRefConfig): MutableRouteRef { - return new MutableRouteRef(config); +export function createRouteRef(config: RouteRefConfig): AbsoluteRouteRef { + return new AbsoluteRouteRef(config); } + +// TODO(Rugvip): Added for backwards compatibility, remove once old usage is gone +// We may want to avoid exporting the AbsoluteRouteRef itself though, and consider +// a different model for how to create sub routes, just avoid this +export type MutableRouteRef = AbsoluteRouteRef; diff --git a/packages/core-api/src/routing/RouteRefRegistry.test.ts b/packages/core-api/src/routing/RouteRefRegistry.test.ts new file mode 100644 index 0000000000..fa1ef584f1 --- /dev/null +++ b/packages/core-api/src/routing/RouteRefRegistry.test.ts @@ -0,0 +1,105 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { RouteRefRegistry } from './RouteRefRegistry'; +import { createRouteRef } from './RouteRef'; + +const dummyConfig = { path: '/', icon: () => null, title: 'my-title' }; +const ref1 = createRouteRef(dummyConfig); +const ref11 = createRouteRef(dummyConfig); +const ref12 = createRouteRef(dummyConfig); +const ref121 = createRouteRef(dummyConfig); +const ref2 = createRouteRef(dummyConfig); +const ref2a = ref2.createSubRoute({ path: '/a' }); +const ref2b = ref2.createSubRoute<{ id: string }>({ path: '/b/:id' }); + +describe('RouteRefRegistry', () => { + it('should be constructed with a root route', () => { + const registry = new RouteRefRegistry(); + expect(registry.resolveRoute([], [])).toBe(''); + }); + + it('should register and resolve some absolute routes', () => { + const registry = new RouteRefRegistry(); + expect(registry.registerRoute([ref1], '1')).toBe(true); + expect(registry.registerRoute([ref1, ref11], '11')).toBe(true); + expect(registry.registerRoute([ref1, ref12], '12')).toBe(true); + expect(registry.registerRoute([ref1, ref12, ref121], '121')).toBe(true); + expect(registry.registerRoute([ref1, ref12, ref121], 'duplicate')).toBe( + false, + ); + expect(registry.registerRoute([ref1, ref12], 'duplicate')).toBe(false); + expect(registry.registerRoute([ref2], '2')).toBe(true); + expect(registry.registerRoute([ref2], 'duplicate')).toBe(false); + expect(registry.registerRoute([ref2], '2')).toBe(true); + + expect(registry.resolveRoute([], [ref1])).toBe('/1'); + expect(registry.resolveRoute([], [ref11])).toBe(undefined); + expect(registry.resolveRoute([], [ref1, ref11])).toBe('/1/11'); + expect(registry.resolveRoute([ref1], [ref11])).toBe('/1/11'); + expect(registry.resolveRoute([ref1], [ref2])).toBe('/2'); + expect(registry.resolveRoute([ref1, ref12, ref121], [])).toBe('/1/12/121'); + expect(registry.resolveRoute([ref1, ref12, ref121], [ref121])).toBe( + '/1/12/121', + ); + expect(registry.resolveRoute([ref1, ref12, ref121], [ref12, ref121])).toBe( + '/1/12/121', + ); + expect(registry.resolveRoute([ref1, ref12, ref121], [ref12])).toBe('/1/12'); + expect(registry.resolveRoute([ref1, ref12, ref121], [ref1])).toBe('/1'); + }); + + it('should register and resolve with sub routes', () => { + const registry = new RouteRefRegistry(); + expect(registry.registerRoute([ref1], '1')).toBe(true); + expect(registry.registerRoute([ref2], '2')).toBe(true); + expect(registry.registerRoute([ref2a], '2')).toBe(true); + expect(registry.registerRoute([ref2a, ref1], '1')).toBe(true); + expect(registry.registerRoute([ref2a, ref2], '2')).toBe(true); + expect(registry.registerRoute([ref2b], '2')).toBe(true); + expect(registry.registerRoute([ref2b, ref1], '1')).toBe(true); + expect(registry.registerRoute([ref2b, ref2], '2')).toBe(true); + + expect(registry.resolveRoute([], [ref1])).toBe('/1'); + expect(registry.resolveRoute([], [ref2])).toBe('/2'); + expect(registry.resolveRoute([], [ref2a.link(), ref1])).toBe('/2/a/1'); + expect(registry.resolveRoute([], [ref2a.link(), ref2])).toBe('/2/a/2'); + expect(registry.resolveRoute([ref2a.link()], [ref2])).toBe('/2/a/2'); + expect(registry.resolveRoute([ref2a.link(), ref1], [ref2])).toBe('/2/a/2'); + expect(registry.resolveRoute([], [ref2b.link({ id: 'abc' }), ref1])).toBe( + '/2/b/abc/1', + ); + expect(registry.resolveRoute([], [ref2b.link({ id: 'xyz' }), ref2])).toBe( + '/2/b/xyz/2', + ); + expect(registry.resolveRoute([ref2b.link({ id: 'abc' })], [ref2])).toBe( + '/2/b/abc/2', + ); + expect( + registry.resolveRoute([ref2b.link({ id: 'abc' }), ref1], [ref2]), + ).toBe('/2/b/abc/2'); + }); + + it('should throw when registering routes incorrectly', () => { + const registry = new RouteRefRegistry(); + expect(() => { + registry.registerRoute([ref1, ref11], '11'); + }).toThrow('Could not find parent for new routing node'); + expect(() => { + registry.registerRoute([], '11'); + }).toThrow('Must provide at least 1 route to add routing node'); + }); +}); diff --git a/packages/core-api/src/routing/RouteRefRegistry.ts b/packages/core-api/src/routing/RouteRefRegistry.ts new file mode 100644 index 0000000000..7e55cbe8f7 --- /dev/null +++ b/packages/core-api/src/routing/RouteRefRegistry.ts @@ -0,0 +1,155 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ConcreteRoute, + routeReference, + resolveRoute, + ReferencedRoute, +} from './types'; + +const rootRoute: ConcreteRoute = { + get [routeReference]() { + return this; + }, + [resolveRoute]: () => '', +}; + +export type RouteRefResolver = { + resolveRoute(from: ConcreteRoute[], to: ConcreteRoute[]): string; +}; + +class Node { + readonly children = new Map(); + + constructor(readonly path: string, readonly parent: Node | undefined) {} + + /** + * Look up a node in the tree given a path. + */ + findNode(routes: ReferencedRoute[]): Node | undefined { + let node = this as Node | undefined; + + for (let i = 0; i < routes.length; i++) { + node = node?.children.get(routes[i][routeReference]); + } + + return node; + } + + /** + * Assigns a path to a leaf node in the routing tree. All ancestor + * nodes of the new leaf node must already exist, or an error will be thrown. + * + * Returns true if the node was added, or false if the node already existed. + */ + addNode(routes: ReferencedRoute[], path: string): boolean { + if (routes.length === 0) { + throw new Error('Must provide at least 1 route to add routing node'); + } + + const parentNode = this.findNode(routes.slice(0, -1)); + if (!parentNode) { + throw new Error('Could not find parent for new routing node'); + } + + const lastRoute = routes[routes.length - 1]; + const lastRouteRef = lastRoute[routeReference]; + + const existingNode = parentNode.children.get(lastRouteRef); + if (existingNode) { + return existingNode.path === path; + } + + parentNode.children.set(lastRouteRef, new Node(path, parentNode)); + return true; + } + + /** + * Resolve an absolute URL that represents this node in the routing tree, using + * using the supplied concrete routes and ancestors of this node. + * + * The length of the provided routes array must match the depth of + * the routing tree that this node is at, or an error will be thrown. + */ + resolve(routes: ConcreteRoute[]) { + const parts = Array(routes.length); + + let node = this as Node | undefined; + for (let i = routes.length - 1; i >= 0; i--) { + if (!node) { + throw new Error('Route resolve missing required parent'); + } + + const route = routes[i]; + parts[i] = route[resolveRoute](node.path); + + node = node.parent; + } + + if (node) { + throw new Error('Route resolve did not reach root'); + } + + return parts.join('/'); + } +} + +/** + * A registry for resolving route refs into concrete string routes. + */ +export class RouteRefRegistry { + private readonly root = new Node('', undefined); + + /** + * Register a new leaf path for a sequence of routes. All ancestor + * routes must already exist. + */ + registerRoute(routes: ReferencedRoute[], path: string): boolean { + return this.root.addNode(routes, path); + } + + /** + * Resolve an absolute path from a point in the routing tree. + * + * The route referenced by `from` must exist, and is the starting + * point for the search, walking up the tree until a subtree that + * matches the routes reference in `to` are found. + * + * If `from` is empty, the search starts and ends at the root node. + * If `to` is empty, the route referenced by `from` will always be returned. + */ + resolveRoute(from: ConcreteRoute[], to: ConcreteRoute[]): string | undefined { + // Keep track of the `from` routes and pop the last ones as we traverse up + // the routing tree. The list of concrete routes that we're passing to + // `node.resolve()` should only include the ones in the resolve path. + const concreteStack = from.slice(); + + let fromNode = this.root.findNode(from); + while (fromNode) { + const resolvedNode = fromNode.findNode(to); + if (resolvedNode) { + return resolvedNode.resolve([rootRoute].concat(concreteStack, to)); + } + + // Search at this level of the tree failed, move up to parent + concreteStack.pop(); + fromNode = fromNode.parent; + } + + return undefined; + } +} diff --git a/packages/core-api/src/routing/index.ts b/packages/core-api/src/routing/index.ts index 67d4c82167..29de34ec42 100644 --- a/packages/core-api/src/routing/index.ts +++ b/packages/core-api/src/routing/index.ts @@ -14,6 +14,6 @@ * limitations under the License. */ -export * from './types'; +export type { RouteRef, RouteRefConfig, ConcreteRoute } from './types'; +export type { MutableRouteRef, AbsoluteRouteRef } from './RouteRef'; export { createRouteRef } from './RouteRef'; -export type { MutableRouteRef } from './RouteRef'; diff --git a/packages/core-api/src/routing/types.ts b/packages/core-api/src/routing/types.ts index 515dc31de6..162ac74bde 100644 --- a/packages/core-api/src/routing/types.ts +++ b/packages/core-api/src/routing/types.ts @@ -16,7 +16,19 @@ import { IconComponent } from '../icons'; +export const resolveRoute = Symbol('resolve-route'); +export const routeReference = Symbol('route-ref'); + +export type ReferencedRoute = { + [routeReference]: unknown; +}; + +export type ConcreteRoute = ReferencedRoute & { + [resolveRoute](path: string): string; +}; + export type RouteRef = { + // TODO(Rugvip): Remove path, look up via registry instead path: string; icon?: IconComponent; title: string; @@ -27,9 +39,3 @@ export type RouteRefConfig = { icon?: IconComponent; title: string; }; - -export type RouteRefOverrideConfig = { - path?: string; - icon?: IconComponent; - title?: string; -}; diff --git a/packages/core/src/api-wrappers/defaultApis.ts b/packages/core/src/api-wrappers/defaultApis.ts index a3f0cb0251..dedadf0456 100644 --- a/packages/core/src/api-wrappers/defaultApis.ts +++ b/packages/core/src/api-wrappers/defaultApis.ts @@ -44,6 +44,8 @@ import { createApiFactory, configApiRef, UrlPatternDiscovery, + samlAuthApiRef, + SamlAuth, } from '@backstage/core-api'; export const defaultApis = [ @@ -132,4 +134,11 @@ export const defaultApis = [ factory: ({ discoveryApi, oauthRequestApi }) => OAuth2.create({ discoveryApi, oauthRequestApi }), }), + createApiFactory({ + api: samlAuthApiRef, + deps: { + discoveryApi: discoveryApiRef, + }, + factory: ({ discoveryApi }) => SamlAuth.create({ discoveryApi }), + }), ]; diff --git a/packages/core/src/components/CodeSnippet/CodeSnippet.tsx b/packages/core/src/components/CodeSnippet/CodeSnippet.tsx index b6d9b3a5aa..84b5aa403e 100644 --- a/packages/core/src/components/CodeSnippet/CodeSnippet.tsx +++ b/packages/core/src/components/CodeSnippet/CodeSnippet.tsx @@ -14,8 +14,7 @@ * limitations under the License. */ -import React, { FC } from 'react'; -import PropTypes from 'prop-types'; +import React from 'react'; import SyntaxHighlighter from 'react-syntax-highlighter'; import { docco, dark } from 'react-syntax-highlighter/dist/cjs/styles/hljs'; import { useTheme } from '@material-ui/core'; @@ -27,28 +26,39 @@ type Props = { language: string; showLineNumbers?: boolean; showCopyCodeButton?: boolean; + highlightedNumbers?: number[]; + customStyle?: any; }; -const defaultProps = { - showLineNumbers: false, - showCopyCodeButton: false, -}; - -export const CodeSnippet: FC = props => { - const { text, language, showLineNumbers, showCopyCodeButton } = { - ...defaultProps, - ...props, - }; - +export const CodeSnippet = ({ + text, + language, + showLineNumbers = false, + showCopyCodeButton = false, + highlightedNumbers, + customStyle, +}: Props) => { const theme = useTheme(); const mode = theme.palette.type === 'dark' ? dark : docco; - + const highlightColor = theme.palette.type === 'dark' ? '#256bf3' : '#e6ffed'; return (
+ highlightedNumbers?.includes(lineNumber) + ? { + style: { + backgroundColor: highlightColor, + }, + } + : {} + } > {text} @@ -60,11 +70,3 @@ export const CodeSnippet: FC = props => {
); }; - -// Type check for the JS files using this core component -CodeSnippet.propTypes = { - text: PropTypes.string.isRequired, - language: PropTypes.string.isRequired, - showLineNumbers: PropTypes.bool, - showCopyCodeButton: PropTypes.bool, -}; diff --git a/packages/core/src/components/DismissableBanner/DismissableBanner.stories.tsx b/packages/core/src/components/DismissableBanner/DismissableBanner.stories.tsx index 62760f72fb..148e7b6803 100644 --- a/packages/core/src/components/DismissableBanner/DismissableBanner.stories.tsx +++ b/packages/core/src/components/DismissableBanner/DismissableBanner.stories.tsx @@ -100,3 +100,15 @@ export const WithLink = () => (
); +export const Fixed = () => ( +
+ + + +
+); diff --git a/packages/core/src/components/DismissableBanner/DismissableBanner.tsx b/packages/core/src/components/DismissableBanner/DismissableBanner.tsx index 747ed06b37..568ab6306b 100644 --- a/packages/core/src/components/DismissableBanner/DismissableBanner.tsx +++ b/packages/core/src/components/DismissableBanner/DismissableBanner.tsx @@ -14,7 +14,7 @@ * limitations under the License. */ -import React, { FC, ReactNode, useState, useEffect } from 'react'; +import React, { ReactNode, useState, useEffect } from 'react'; import { useApi, storageApiRef } from '@backstage/core-api'; import { useObservable } from 'react-use'; import classNames from 'classnames'; @@ -27,12 +27,17 @@ import Close from '@material-ui/icons/Close'; const useStyles = makeStyles((theme: BackstageTheme) => ({ root: { - position: 'relative', padding: theme.spacing(0), - marginBottom: theme.spacing(6), - marginTop: -theme.spacing(3), + marginBottom: theme.spacing(0), + marginTop: theme.spacing(0), display: 'flex', flexFlow: 'row nowrap', + }, + // showing on top + topPosition: { + position: 'relative', + marginBottom: theme.spacing(6), + marginTop: -theme.spacing(3), zIndex: 'unset', }, icon: { @@ -45,6 +50,10 @@ const useStyles = makeStyles((theme: BackstageTheme) => ({ message: { display: 'flex', alignItems: 'center', + color: theme.palette.banner.text, + '& a': { + color: theme.palette.banner.link, + }, }, info: { backgroundColor: theme.palette.banner.info, @@ -58,9 +67,15 @@ type Props = { variant: 'info' | 'error'; message: ReactNode; id: string; + fixed?: boolean; }; -export const DismissableBanner: FC = ({ variant, message, id }) => { +export const DismissableBanner = ({ + variant, + message, + id, + fixed = false, +}: Props) => { const classes = useStyles(); const storageApi = useApi(storageApiRef); const notificationsStore = storageApi.forBucket('notifications'); @@ -88,9 +103,15 @@ export const DismissableBanner: FC = ({ variant, message, id }) => { return ( ( +
+ +
+); + +export const Info = () => ( +
+ +
+); + +export const Content = () => ( +
+ +
+); + +export const Data = () => ( +
+ +
+); + +export const WithAction = () => ( +
+ {}} variant="contained"> + DOCS + + } + /> +
+); + +export const MissingAnnotation = () => ( +
+ +
+); diff --git a/packages/core/src/components/EmptyState/EmptyState.test.tsx b/packages/core/src/components/EmptyState/EmptyState.test.tsx new file mode 100644 index 0000000000..c5bc7a9876 --- /dev/null +++ b/packages/core/src/components/EmptyState/EmptyState.test.tsx @@ -0,0 +1,39 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { EmptyState } from './EmptyState'; +import { renderWithEffects, wrapInTestApp } from '@backstage/test-utils'; +import { Button } from '@material-ui/core'; + +describe('', () => { + it('render EmptyState component with type annotaion is missing', async () => { + const rendered = await renderWithEffects( + wrapInTestApp( + DOCS} + />, + ), + ); + expect( + rendered.getByText('Your plugin is missing an annotation'), + ).toBeInTheDocument(); + expect(rendered.getByLabelText('button')).toBeInTheDocument(); + expect(rendered.getByTestId('missingAnnotation')).toBeInTheDocument(); + }); +}); diff --git a/packages/core/src/components/EmptyState/EmptyState.tsx b/packages/core/src/components/EmptyState/EmptyState.tsx new file mode 100644 index 0000000000..4469c3ce86 --- /dev/null +++ b/packages/core/src/components/EmptyState/EmptyState.tsx @@ -0,0 +1,78 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { makeStyles, Typography, Grid } from '@material-ui/core'; +import { EmptyStateImage } from './EmptyStateImage'; +import Background from './assets/Background.svg'; + +const useStyles = makeStyles(theme => ({ + root: { + backgroundColor: theme.palette.background.default, + padding: theme.spacing(2, 0, 0, 0), + }, + action: { + marginTop: theme.spacing(2), + }, + imageContainer: { + position: 'relative', + }, + backgroundImage: { + position: 'absolute', + width: '100%', + }, +})); + +type Props = { + title: string; + description?: string; + missing: 'field' | 'info' | 'content' | 'data'; + action?: JSX.Element; +}; + +export const EmptyState = ({ title, description, missing, action }: Props) => { + const classes = useStyles(); + return ( + + + + {title} + + + {description} + + + {action} + + + + background + + + + ); +}; diff --git a/packages/core/src/components/EmptyState/EmptyStateImage.tsx b/packages/core/src/components/EmptyState/EmptyStateImage.tsx new file mode 100644 index 0000000000..49598ae6db --- /dev/null +++ b/packages/core/src/components/EmptyState/EmptyStateImage.tsx @@ -0,0 +1,74 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import missingAnnotation from './assets/missingAnnotation.svg'; +import noInformation from './assets/noInformation.svg'; +import createComponent from './assets/createComponent.svg'; +import noBuild from './assets/noBuild.svg'; +import { makeStyles } from '@material-ui/core'; + +type Props = { + missing: 'field' | 'info' | 'content' | 'data'; +}; + +const useStyles = makeStyles({ + generalImg: { + width: '75%', + zIndex: 2, + position: 'absolute', + left: '50%', + top: '50%', + transform: 'translate(-50%, 15%)', + }, +}); + +export const EmptyStateImage = ({ missing }: Props) => { + const classes = useStyles(); + switch (missing) { + case 'field': + return ( + annotation is missing + ); + case 'info': + return ( + no Information + ); + case 'content': + return ( + create Component + ); + case 'data': + return ( + no Build + ); + default: + return null; + } +}; diff --git a/packages/core/src/components/EmptyState/MissingAnnotationEmptyState.tsx b/packages/core/src/components/EmptyState/MissingAnnotationEmptyState.tsx new file mode 100644 index 0000000000..d8847fdf47 --- /dev/null +++ b/packages/core/src/components/EmptyState/MissingAnnotationEmptyState.tsx @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Button, makeStyles, Typography } from '@material-ui/core'; +import { BackstageTheme } from '@backstage/theme'; +import { EmptyState } from './EmptyState'; +import { CodeSnippet } from '../CodeSnippet'; + +const COMPONENT_YAML = `# Example +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: example + description: example.com + annotations: + ANNOTATION: value +spec: + type: website + lifecycle: production + owner: guest +`; + +type Props = { + annotation: string; +}; + +const useStyles = makeStyles(theme => ({ + code: { + borderRadius: 6, + margin: `${theme.spacing(2)}px 0px`, + background: theme.palette.type === 'dark' ? '#444' : '#fff', + }, +})); + +export const MissingAnnotationEmptyState = ({ annotation }: Props) => { + const classes = useStyles(); + return ( + + + Add the annotation to your component YAML as shown in the + highlighted example below: + +
+ +
+ + + } + /> + ); +}; diff --git a/packages/core/src/components/EmptyState/assets/Background.svg b/packages/core/src/components/EmptyState/assets/Background.svg new file mode 100644 index 0000000000..e2fa538f7f --- /dev/null +++ b/packages/core/src/components/EmptyState/assets/Background.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/packages/core/src/components/EmptyState/assets/createComponent.svg b/packages/core/src/components/EmptyState/assets/createComponent.svg new file mode 100644 index 0000000000..af2ddd5678 --- /dev/null +++ b/packages/core/src/components/EmptyState/assets/createComponent.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/core/src/components/EmptyState/assets/missingAnnotation.svg b/packages/core/src/components/EmptyState/assets/missingAnnotation.svg new file mode 100644 index 0000000000..475cda9699 --- /dev/null +++ b/packages/core/src/components/EmptyState/assets/missingAnnotation.svg @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/core/src/components/EmptyState/assets/noBuild.svg b/packages/core/src/components/EmptyState/assets/noBuild.svg new file mode 100644 index 0000000000..76a41749b9 --- /dev/null +++ b/packages/core/src/components/EmptyState/assets/noBuild.svg @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/core/src/components/EmptyState/assets/noInformation.svg b/packages/core/src/components/EmptyState/assets/noInformation.svg new file mode 100644 index 0000000000..e41cf94645 --- /dev/null +++ b/packages/core/src/components/EmptyState/assets/noInformation.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/core/src/components/EmptyState/index.ts b/packages/core/src/components/EmptyState/index.ts new file mode 100644 index 0000000000..2e2a88be94 --- /dev/null +++ b/packages/core/src/components/EmptyState/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { EmptyState } from './EmptyState'; +export { MissingAnnotationEmptyState } from './MissingAnnotationEmptyState'; diff --git a/packages/core/src/components/ProgressBars/GaugeProgress.stories.tsx b/packages/core/src/components/ProgressBars/GaugeProgress.stories.tsx new file mode 100644 index 0000000000..48f4cb673e --- /dev/null +++ b/packages/core/src/components/ProgressBars/GaugeProgress.stories.tsx @@ -0,0 +1,55 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { GaugeProgress } from './GaugeProgress'; + +const containerStyle = { width: 300 }; + +export default { + title: 'GaugeProgress', + component: GaugeProgress, +}; + +export const Default = () => ( +
+ +
+); + +export const MediumProgress = () => ( +
+ +
+); + +export const LowProgress = () => ( +
+ +
+); + +export const InverseLowProgress = () => ( +
+ +
+); + +export const AbsoluteProgress = () => ( +
+ +
+); diff --git a/packages/core/src/components/StructuredMetadataTable/MetadataTable.tsx b/packages/core/src/components/StructuredMetadataTable/MetadataTable.tsx index 1d863db764..b34e535a00 100644 --- a/packages/core/src/components/StructuredMetadataTable/MetadataTable.tsx +++ b/packages/core/src/components/StructuredMetadataTable/MetadataTable.tsx @@ -71,13 +71,7 @@ export const MetadataTable = ({ dense?: boolean; children: React.ReactNode; }) => ( - - {!dense && ( - - - - - )} +
{children}
); diff --git a/packages/core/src/components/StructuredMetadataTable/README.md b/packages/core/src/components/StructuredMetadataTable/README.md index 452d32490f..60952e5e34 100644 --- a/packages/core/src/components/StructuredMetadataTable/README.md +++ b/packages/core/src/components/StructuredMetadataTable/README.md @@ -23,7 +23,7 @@ The component itself only handles the display area, so you can use standard JS t This will step through each of the keys and based on their types display them in a logical way. -### Primatives +### Primitives Any non complex value will be displayed using `{value}` which will just output the value as text. diff --git a/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.stories.tsx b/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.stories.tsx index bdf0f65375..9db7385872 100644 --- a/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.stories.tsx +++ b/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.stories.tsx @@ -56,3 +56,16 @@ export const Default = () => ( ); + +export const NotDenseTable = () => ( + + +
+ +
+
+
+); diff --git a/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx b/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx index f966bd570f..52ad9a320a 100644 --- a/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx +++ b/packages/core/src/components/StructuredMetadataTable/StructuredMetadataTable.tsx @@ -14,7 +14,7 @@ * limitations under the License. */ -import React, { Component, Fragment, ReactElement } from 'react'; +import React, { Fragment, ReactElement } from 'react'; import { withStyles, createStyles, WithStyles, Theme } from '@material-ui/core'; import startCase from 'lodash/startCase'; @@ -142,17 +142,17 @@ const TableItem = ({ ); }; -interface ComponentProps { +type Props = { metadata: { [key: string]: any }; dense?: boolean; options?: any; -} +}; -export class StructuredMetadataTable extends Component { - render() { - const { metadata, dense, options } = this.props; - const metadataItems = mapToItems(metadata, options || {}); - - return {metadataItems}; - } -} +export const StructuredMetadataTable = ({ + metadata, + dense = true, + options, +}: Props) => { + const metadataItems = mapToItems(metadata, options || {}); + return {metadataItems}; +}; diff --git a/packages/core/src/components/index.ts b/packages/core/src/components/index.ts index 6c070366c7..4f085ffd6a 100644 --- a/packages/core/src/components/index.ts +++ b/packages/core/src/components/index.ts @@ -34,3 +34,4 @@ export * from './Table'; export * from './Tabs'; export * from './TrendLine'; export * from './WarningPanel'; +export * from './EmptyState'; diff --git a/packages/core/src/layout/HomepageTimer/HomepageTimer.tsx b/packages/core/src/layout/HomepageTimer/HomepageTimer.tsx index 7ea4dd508f..59b7f3fb3d 100644 --- a/packages/core/src/layout/HomepageTimer/HomepageTimer.tsx +++ b/packages/core/src/layout/HomepageTimer/HomepageTimer.tsx @@ -14,59 +14,76 @@ * limitations under the License. */ -import React, { FC } from 'react'; +import React from 'react'; import { HeaderLabel } from '../HeaderLabel'; +import { ConfigApi, useApi, configApiRef } from '@backstage/core-api'; const timeFormat = { hour: '2-digit', minute: '2-digit' }; -const utcOptions = { timeZone: 'UTC', ...timeFormat }; -const nycOptions = { timeZone: 'America/New_York', ...timeFormat }; -const tyoOptions = { timeZone: 'Asia/Tokyo', ...timeFormat }; -const stoOptions = { timeZone: 'Europe/Stockholm', ...timeFormat }; -const defaultTimes = { - timeNY: '', - timeUTC: '', - timeTYO: '', - timeSTO: '', +type TimeObj = { + time: string; + label: string; }; -function getTimes() { +function getTimes(configApi: ConfigApi) { const d = new Date(); const lang = window.navigator.language; - // Using the browser native toLocaleTimeString instead of huge moment-tz - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString - const timeNY = d.toLocaleTimeString(lang, nycOptions); - const timeUTC = d.toLocaleTimeString(lang, utcOptions); - const timeTYO = d.toLocaleTimeString(lang, tyoOptions); - const timeSTO = d.toLocaleTimeString(lang, stoOptions); + const clocks: TimeObj[] = []; - return { timeNY, timeUTC, timeTYO, timeSTO }; + if (!configApi.has('homepage.clocks')) { + return clocks; + } + + const clockConfigs = configApi.getConfigArray('homepage.clocks'); + + for (const clock of clockConfigs) { + if (clock.has('label') && clock.has('timezone')) { + const options = { + timeZone: clock.getString('timezone'), + ...timeFormat, + }; + + const time = d.toLocaleTimeString(lang, options); + const label = clock.getString('label'); + + clocks.push({ time, label }); + } + } + + return clocks; } -export const HomepageTimer: FC<{}> = () => { - const [{ timeNY, timeUTC, timeTYO, timeSTO }, setTimes] = React.useState( - defaultTimes, - ); +export const HomepageTimer = () => { + const configApi = useApi(configApiRef); + + const defaultTimes: TimeObj[] = []; + const [clocks, setTimes] = React.useState(defaultTimes); React.useEffect(() => { - setTimes(getTimes()); + setTimes(getTimes(configApi)); const intervalId = setInterval(() => { - setTimes(getTimes()); + setTimes(getTimes(configApi)); }, 1000); return () => { clearInterval(intervalId); }; - }, []); + }, [configApi]); - return ( - <> - - - - - - ); + if (clocks.length !== 0) { + return ( + <> + {clocks.map(clock => ( + + ))} + + ); + } + return null; }; diff --git a/packages/core/src/layout/Sidebar/DefaultProviderSettings.tsx b/packages/core/src/layout/Sidebar/DefaultProviderSettings.tsx index f96c6adb2f..99c5225c83 100644 --- a/packages/core/src/layout/Sidebar/DefaultProviderSettings.tsx +++ b/packages/core/src/layout/Sidebar/DefaultProviderSettings.tsx @@ -21,6 +21,7 @@ import { oauth2ApiRef, oktaAuthApiRef, microsoftAuthApiRef, + samlAuthApiRef, useApi, } from '@backstage/core-api'; import Star from '@material-ui/icons/Star'; @@ -69,6 +70,13 @@ export const DefaultProviderSettings = () => { icon={Star} /> )} + {providers.includes('saml') && ( + + )} {providers.includes('oauth2') && ( { app: { title: 'Test' }, backend: { baseUrl: 'http://localhost:7000' }, techdocs: { - storageUrl: 'http://localhost:7000/techdocs/static/docs', + storageUrl: 'http://localhost:7000/api/techdocs/static/docs', }, }, context: 'test', diff --git a/packages/create-app/templates/default-app/packages/app/src/apis.ts b/packages/create-app/templates/default-app/packages/app/src/apis.ts index e0503e504f..24b22a83bc 100644 --- a/packages/create-app/templates/default-app/packages/app/src/apis.ts +++ b/packages/create-app/templates/default-app/packages/app/src/apis.ts @@ -1,17 +1 @@ -import { - discoveryApiRef, - UrlPatternDiscovery, - createApiFactory, - configApiRef, -} from '@backstage/core'; - -export const apis = [ - createApiFactory({ - api: discoveryApiRef, - deps: { configApi: configApiRef }, - factory: ({ configApi }) => - UrlPatternDiscovery.compile( - `${configApi.getString('backend.baseUrl')}/{{ pluginId }}`, - ), - }), -]; +export const apis = []; diff --git a/packages/create-app/templates/default-app/packages/backend/Dockerfile b/packages/create-app/templates/default-app/packages/backend/Dockerfile index a7bd814b19..93929ceb86 100644 --- a/packages/create-app/templates/default-app/packages/backend/Dockerfile +++ b/packages/create-app/templates/default-app/packages/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM node:12 +FROM node:12-buster WORKDIR /usr/src/app diff --git a/packages/create-app/templates/default-app/packages/backend/package.json.hbs b/packages/create-app/templates/default-app/packages/backend/package.json.hbs index adde81e830..7f811e3739 100644 --- a/packages/create-app/templates/default-app/packages/backend/package.json.hbs +++ b/packages/create-app/templates/default-app/packages/backend/package.json.hbs @@ -5,7 +5,7 @@ "types": "src/index.ts", "private": true, "engines": { - "node": "12" + "node": "12 || 14" }, "scripts": { "build": "backstage-cli backend:build", @@ -22,7 +22,6 @@ "@backstage/config": "^{{version}}", "@backstage/plugin-auth-backend": "^{{version}}", "@backstage/plugin-catalog-backend": "^{{version}}", - "@backstage/plugin-identity-backend": "^{{version}}", "@backstage/plugin-proxy-backend": "^{{version}}", "@backstage/plugin-rollbar-backend": "^{{version}}", "@backstage/plugin-scaffolder-backend": "^{{version}}", @@ -31,6 +30,7 @@ "@gitbeaker/node": "^23.5.0", "dockerode": "^3.2.0", "express": "^4.17.1", + "express-promise-router": "^3.0.3", "knex": "^0.21.1", {{#if dbTypePG}} "pg": "^8.3.0", diff --git a/packages/create-app/templates/default-app/packages/backend/src/index.ts b/packages/create-app/templates/default-app/packages/backend/src/index.ts index 6a014727e9..684db8aab8 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/index.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/index.ts @@ -6,17 +6,21 @@ * Happy hacking! */ +import Router from 'express-promise-router'; import { + ensureDatabaseExists, createDatabaseClient, createServiceBuilder, loadBackendConfig, getRootLogger, useHotMemoize, + notFoundHandler, + SingleHostDiscovery, + UrlReaders, } from '@backstage/backend-common'; import { ConfigReader, AppConfig } from '@backstage/config'; import auth from './plugins/auth'; import catalog from './plugins/catalog'; -import identity from './plugins/identity'; import scaffolder from './plugins/scaffolder'; import proxy from './plugins/proxy'; import techdocs from './plugins/techdocs'; @@ -24,9 +28,14 @@ import { PluginEnvironment } from './types'; function makeCreateEnv(loadedConfigs: AppConfig[]) { const config = ConfigReader.fromConfigs(loadedConfigs); + const root = getRootLogger(); + const reader = UrlReaders.default({ logger: root, config }); + const discovery = SingleHostDiscovery.fromConfig(config); + + root.info(`Created UrlReader ${reader}`); return (plugin: string): PluginEnvironment => { - const logger = getRootLogger().child({ type: 'plugin', plugin }); + const logger = root.child({ type: 'plugin', plugin }); const database = createDatabaseClient( config.getConfig('backend.database'), { @@ -35,7 +44,7 @@ function makeCreateEnv(loadedConfigs: AppConfig[]) { }, }, ); - return { logger, database, config }; + return { logger, database, config, reader, discovery }; }; } @@ -43,22 +52,29 @@ async function main() { const configs = await loadBackendConfig(); const configReader = ConfigReader.fromConfigs(configs); const createEnv = makeCreateEnv(configs); + await ensureDatabaseExists( + configReader.getConfig('backend.database'), + 'backstage_plugin_catalog', + 'backstage_plugin_auth', + ); const catalogEnv = useHotMemoize(module, () => createEnv('catalog')); const scaffolderEnv = useHotMemoize(module, () => createEnv('scaffolder')); const authEnv = useHotMemoize(module, () => createEnv('auth')); - const identityEnv = useHotMemoize(module, () => createEnv('identity')); const proxyEnv = useHotMemoize(module, () => createEnv('proxy')); const techdocsEnv = useHotMemoize(module, () => createEnv('techdocs')); + const apiRouter = Router(); + apiRouter.use('/catalog', await catalog(catalogEnv)) + apiRouter.use('/scaffolder', await scaffolder(scaffolderEnv)) + apiRouter.use('/auth', await auth(authEnv)) + apiRouter.use('/techdocs', await techdocs(techdocsEnv)) + apiRouter.use('/proxy', await proxy(proxyEnv)) + apiRouter.use(notFoundHandler()); + const service = createServiceBuilder(module) .loadConfig(configReader) - .addRouter('/catalog', await catalog(catalogEnv)) - .addRouter('/scaffolder', await scaffolder(scaffolderEnv)) - .addRouter('/auth', await auth(authEnv)) - .addRouter('/identity', await identity(identityEnv)) - .addRouter('/techdocs', await techdocs(techdocsEnv)) - .addRouter('/proxy', await proxy(proxyEnv, '/proxy')); + .addRouter('/api', apiRouter) await service.start().catch(err => { console.log(err); diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/auth.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/auth.ts index 61af87cce0..fe19855d5d 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/auth.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/auth.ts @@ -5,6 +5,7 @@ export default async function createPlugin({ logger, database, config, + discovery, }: PluginEnvironment) { - return await createRouter({ logger, config, database }); + return await createRouter({ logger, config, database, discovery }); } diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/catalog.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/catalog.ts index aa0538a6d8..345ac4c23d 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/catalog.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/catalog.ts @@ -13,9 +13,10 @@ import { useHotCleanup } from '@backstage/backend-common'; export default async function createPlugin({ logger, config, + reader, database, }: PluginEnvironment) { - const locationReader = new LocationReaders({ logger, config }); + const locationReader = new LocationReaders({ logger, reader, config }); const db = await DatabaseManager.createDatabase(database, { logger }); const entitiesCatalog = new DatabaseEntitiesCatalog(db); diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/identity.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/identity.ts deleted file mode 100644 index f82090eec9..0000000000 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/identity.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { createRouter } from '@backstage/plugin-identity-backend'; -import { PluginEnvironment } from '../types'; - -export default async function createPlugin({ logger }: PluginEnvironment) { - return await createRouter({ logger }); -} diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/proxy.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/proxy.ts index b20265c2cd..388d3fc446 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/proxy.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/proxy.ts @@ -2,9 +2,10 @@ import { createRouter } from '@backstage/plugin-proxy-backend'; import { PluginEnvironment } from '../types'; -export default async function createPlugin( - { logger, config }: PluginEnvironment, - pathPrefix: string, -) { - return await createRouter({ logger, config, pathPrefix }); +export default async function createPlugin({ + logger, + config, + discovery, +}: PluginEnvironment) { + return await createRouter({ logger, config, discovery }); } diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/scaffolder.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/scaffolder.ts index cfdfbb0a78..ed16d766f1 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/scaffolder.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/scaffolder.ts @@ -18,8 +18,8 @@ import type { PluginEnvironment } from '../types'; import Docker from 'dockerode'; export default async function createPlugin({ - logger, - config, + logger, + config, }: PluginEnvironment) { const cookiecutterTemplater = new CookieCutter(); const craTemplater = new CreateReactAppTemplater(); @@ -39,31 +39,60 @@ export default async function createPlugin({ const publishers = new Publishers(); - const githubToken = config.getString('scaffolder.github.token'); - const repoVisibility = config.getString( - 'scaffolder.github.visibility', - ) as RepoVisibilityOptions; + const githubConfig = config.getOptionalConfig('scaffolder.github'); - const githubClient = new Octokit({ auth: githubToken }); - const githubPublisher = new GithubPublisher({ - client: githubClient, - token: githubToken, - repoVisibility, - }); - publishers.register('file', githubPublisher); - publishers.register('github', githubPublisher); + if (githubConfig) { + try { + const repoVisibility = githubConfig.getString( + 'visibility', + ) as RepoVisibilityOptions; + + const githubToken = githubConfig.getString('token'); + const githubClient = new Octokit({ auth: githubToken }); + const githubPublisher = new GithubPublisher({ + client: githubClient, + token: githubToken, + repoVisibility, + }); + publishers.register('file', githubPublisher); + publishers.register('github', githubPublisher); + } catch (e) { + const providerName = 'github'; + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, + ); + } + + logger.warn( + `Skipping ${providerName} scaffolding provider, ${e.message}`, + ); + } + } const gitLabConfig = config.getOptionalConfig('scaffolder.gitlab.api'); - if (gitLabConfig) { - const gitLabToken = gitLabConfig.getString('token'); - const gitLabClient = new Gitlab({ - host: gitLabConfig.getOptionalString('baseUrl'), - token: gitLabToken, - }); - const gitLabPublisher = new GitlabPublisher(gitLabClient, gitLabToken); - publishers.register('gitlab', gitLabPublisher); - publishers.register('gitlab/api', gitLabPublisher); + try { + const gitLabToken = gitLabConfig.getString('token'); + const gitLabClient = new Gitlab({ + host: gitLabConfig.getOptionalString('baseUrl'), + token: gitLabToken, + }); + const gitLabPublisher = new GitlabPublisher(gitLabClient, gitLabToken); + publishers.register('gitlab', gitLabPublisher); + publishers.register('gitlab/api', gitLabPublisher); + } catch (e) { + const providerName = 'gitlab'; + if (process.env.NODE_ENV !== 'development') { + throw new Error( + `Failed to initialize ${providerName} scaffolding provider, ${e.message}`, + ); + } + + logger.warn( + `Skipping ${providerName} scaffolding provider, ${e.message}`, + ); + } } const dockerClient = new Docker(); diff --git a/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts b/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts index 9c7de3512b..b522992a75 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/plugins/techdocs.ts @@ -13,6 +13,7 @@ import Docker from 'dockerode'; export default async function createPlugin({ logger, config, + discovery, }: PluginEnvironment) { const generators = new Generators(); const techdocsGenerator = new TechdocsGenerator(logger, config); @@ -37,5 +38,6 @@ export default async function createPlugin({ dockerClient, logger, config, + discovery, }); } diff --git a/packages/create-app/templates/default-app/packages/backend/src/types.ts b/packages/create-app/templates/default-app/packages/backend/src/types.ts index 570a5fcdb1..aa003f63a5 100644 --- a/packages/create-app/templates/default-app/packages/backend/src/types.ts +++ b/packages/create-app/templates/default-app/packages/backend/src/types.ts @@ -1,9 +1,12 @@ import Knex from 'knex'; import { Logger } from 'winston'; import { Config } from '@backstage/config'; +import { PluginEndpointDiscovery, UrlReader } from '@backstage/backend-common'; export type PluginEnvironment = { logger: Logger; database: Knex; config: Config; + reader: UrlReader + discovery: PluginEndpointDiscovery; }; diff --git a/packages/e2e-test/src/e2e-test.ts b/packages/e2e-test/src/e2e-test.ts index 969a77cb2a..c7f6137ff1 100644 --- a/packages/e2e-test/src/e2e-test.ts +++ b/packages/e2e-test/src/e2e-test.ts @@ -55,6 +55,9 @@ async function main() { print('Creating a Backstage Plugin'); const pluginName = await createPlugin('test-plugin', appDir); + print('Creating a Backstage Backend Plugin'); + await createPlugin('test-backend-plugin', appDir, ['--backend']); + print('Starting the app'); await testAppServe(pluginName, appDir); @@ -238,8 +241,12 @@ async function overrideModuleResolutions(appDir: string, workspaceDir: string) { /** * Uses create-plugin command to create a new plugin in the app */ -async function createPlugin(pluginName: string, appDir: string) { - const child = spawnPiped(['yarn', 'create-plugin'], { +async function createPlugin( + pluginName: string, + appDir: string, + options: string[] = [], +) { + const child = spawnPiped(['yarn', 'create-plugin', ...options], { cwd: appDir, }); @@ -384,7 +391,7 @@ async function testBackendStart(appDir: string, isPostgres: boolean) { print('Try to fetch entities from the backend'); // Try fetch entities, should be ok - await fetch('http://localhost:7000/catalog/entities').then(res => + await fetch('http://localhost:7000/api/catalog/entities').then(res => res.json(), ); print('Entities fetched successfully'); diff --git a/packages/techdocs-container/mock-docs/docs/index.md b/packages/techdocs-container/mock-docs/docs/index.md index 3c323d6fc1..94a53acfa3 100644 --- a/packages/techdocs-container/mock-docs/docs/index.md +++ b/packages/techdocs-container/mock-docs/docs/index.md @@ -1,7 +1,7 @@ ## hello mock docs !!! test -Testing somethin +Testing something Abbreviations: Some text about MOCDOC diff --git a/packages/techdocs-container/techdocs-core/README.md b/packages/techdocs-container/techdocs-core/README.md index 49b9fce4e4..7f34722e81 100644 --- a/packages/techdocs-container/techdocs-core/README.md +++ b/packages/techdocs-container/techdocs-core/README.md @@ -82,6 +82,10 @@ Extensions: ## Changelog +### 0.0.9 + +- Change development status to 3 - Alpha + ### 0.0.8 - Superfences and Codehilite doesn't work very well together (squidfunk/mkdocs-material#1604) so therefore the codehilite extension is replaced by pymdownx.highlight diff --git a/packages/techdocs-container/techdocs-core/setup.py b/packages/techdocs-container/techdocs-core/setup.py index e5a8206150..4385bc2e38 100644 --- a/packages/techdocs-container/techdocs-core/setup.py +++ b/packages/techdocs-container/techdocs-core/setup.py @@ -14,13 +14,19 @@ See the License for the specific language governing permissions and limitations under the License. """ from setuptools import setup, find_packages +from os import path +# read the contents of the README file in the current directory +this_dir = path.abspath(path.dirname(__file__)) +with open(path.join(this_dir, "README.md"), encoding="utf-8") as file: + long_description = file.read() setup( name="mkdocs-techdocs-core", - version="0.0.8", + version="0.0.9", description="A Mkdocs package that contains TechDocs defaults", - long_description="", + long_description=long_description, + long_description_content_type="text/markdown", keywords="mkdocs", url="https://github.com/spotify/backstage", author="TechDocs Core", @@ -37,7 +43,7 @@ setup( "pymdown-extensions==7.1", ], classifiers=[ - "Development Status :: 1 - Planning", + "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "License :: OSI Approved :: Apache Software License", diff --git a/packages/theme/src/themes.ts b/packages/theme/src/themes.ts index 73d6c13859..0ec3304ac5 100644 --- a/packages/theme/src/themes.ts +++ b/packages/theme/src/themes.ts @@ -44,6 +44,8 @@ export const lightTheme = createTheme({ banner: { info: '#2E77D0', error: '#E22134', + text: '#FFFFFF', + link: '#000000', }, border: '#E6E6E6', textContrast: '#000000', @@ -80,12 +82,12 @@ export const darkTheme = createTheme({ default: '#333333', }, status: { - ok: '#1DB954', - warning: '#FF9800', - error: '#E22134', - running: '#2E77D0', - pending: '#FFED51', - aborted: '#757575', + ok: '#71CF88', + warning: '#FFB84D', + error: '#F84C55', + running: '#3488E3', + pending: '#FEF071', + aborted: '#9E9E9E', }, bursts: { fontColor: '#FEFEFE', @@ -100,11 +102,13 @@ export const darkTheme = createTheme({ banner: { info: '#2E77D0', error: '#E22134', + text: '#FFFFFF', + link: '#000000', }, border: '#E6E6E6', textContrast: '#FFFFFF', - textVerySubtle: '#DDD', - textSubtle: '#EEEEEE', + textVerySubtle: '#727272', + textSubtle: '#CCCCCC', highlight: '#FFFBCC', errorBackground: '#FFEBEE', warningBackground: '#F59B23', diff --git a/packages/theme/src/types.ts b/packages/theme/src/types.ts index 66bfb4c6fd..1d244f8cd4 100644 --- a/packages/theme/src/types.ts +++ b/packages/theme/src/types.ts @@ -64,6 +64,8 @@ type PaletteAdditions = { banner: { info: string; error: string; + text: string; + link: string; }; }; diff --git a/plugins/README.md b/plugins/README.md index 91ad94b883..d56758b8f0 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -2,7 +2,7 @@ Backstage is a single-page application composed of a set of plugins. -Our goal for the plugin ecosystem is that the definition of a plugin is flexible enough to allow you to expose pretty much any kind of infrastructure or software development tool as a plugin in Backstage. By following strong [design guidelines](https://github.com/spotify/backstage/blob/master/docs/dls/design.md) we ensure the the overall user experience stays consistent between plugins. +Our goal for the plugin ecosystem is that the definition of a plugin is flexible enough to allow you to expose pretty much any kind of infrastructure or software development tool as a plugin in Backstage. By following strong [design guidelines](https://github.com/spotify/backstage/blob/master/docs/dls/design.md) we ensure the overall user experience stays consistent between plugins. ![plugin](../docs/assets/my-plugin_screenshot.png) @@ -12,6 +12,6 @@ To create a plugin, follow the steps outlined [here](https://github.com/spotify/ ## Suggesting a plugin -If you start developing a plugin that you aim to release as open source, we suggest that you create a new [new Issue](https://github.com/spotify/backstage/issues/new?template=plugin_template.md). This helps the community know what plugins are in development. +If you start developing a plugin that you aim to release as open source, we suggest that you create a [new Issue](https://github.com/spotify/backstage/issues/new?template=plugin_template.md). This helps the community know what plugins are in development. You can also use this process if you have an idea for a good plugin but you hope that someone else will pick up the work. diff --git a/plugins/api-docs/README.md b/plugins/api-docs/README.md index 17f354e997..ecc0e5a560 100644 --- a/plugins/api-docs/README.md +++ b/plugins/api-docs/README.md @@ -18,7 +18,7 @@ Right now, the following API formats are supported: - [AsyncAPI](https://www.asyncapi.com/docs/specifications/latest/) - [GraphQL](https://graphql.org/learn/schema/) -Other formats are displayed as plain text, but this can easily be extented. +Other formats are displayed as plain text, but this can easily be extended. To fill the catalog with APIs, [provide entities of kind API](https://backstage.io/docs/features/software-catalog/descriptor-format#kind-api). To link that an component implements an API, see [`implementsApis` property on components](https://backstage.io/docs/features/software-catalog/descriptor-format#specimplementsapis-optional). diff --git a/plugins/api-docs/package.json b/plugins/api-docs/package.json index bc384bf796..f47a5e0ef4 100644 --- a/plugins/api-docs/package.json +++ b/plugins/api-docs/package.json @@ -24,7 +24,7 @@ "@backstage/core": "^0.1.1-alpha.23", "@backstage/plugin-catalog": "^0.1.1-alpha.23", "@backstage/theme": "^0.1.1-alpha.23", - "@kyma-project/asyncapi-react": "^0.11.0", + "@kyma-project/asyncapi-react": "^0.13.1", "@material-icons/font": "^1.0.2", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", @@ -49,7 +49,9 @@ "@types/node": "^12.0.0", "@types/react": "^16.9", "@types/swagger-ui-react": "^3.23.3", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx index ac5dedfd9c..86f524d099 100644 --- a/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx +++ b/plugins/api-docs/src/components/AsyncApiDefinitionWidget/AsyncApiDefinitionWidget.tsx @@ -96,10 +96,10 @@ const useStyles = makeStyles(theme => ({ content: '"🔗"', 'font-family': 'inherit', }, - '& .asyncapi__info, .asyncapi__channel, .asyncapi__channels > div, .asyncapi__schema, .asyncapi__message, .asyncapi__server, .asyncapi__servers > div, .asyncapi__messages > div, .asyncapi__schemas > div': { + '& .asyncapi__info, .asyncapi__channel, .asyncapi__channels > div, .asyncapi__schema, .asyncapi__channel-operations-list .asyncapi__messages-list-item .asyncapi__message, .asyncapi__message, .asyncapi__server, .asyncapi__servers > div, .asyncapi__messages > div, .asyncapi__schemas > div': { 'background-color': 'inherit', }, - '& .asyncapi__channel-parameters-header, .asyncapi__channel-operations-header': { + '& .asyncapi__channel-parameters-header, .asyncapi__channel-operations-header, .asyncapi__channel-operation-oneOf-subscribe-header, .asyncapi__channel-operation-oneOf-publish-header': { 'background-color': 'inherit', color: theme.palette.text.primary, }, diff --git a/plugins/app-backend/package.json b/plugins/app-backend/package.json index 8d7fb67171..d403580f86 100644 --- a/plugins/app-backend/package.json +++ b/plugins/app-backend/package.json @@ -32,7 +32,7 @@ "devDependencies": { "@backstage/cli": "^0.1.1-alpha.23", "@types/supertest": "^2.0.8", - "msw": "^0.19.5", + "msw": "^0.20.5", "supertest": "^4.0.2" }, "files": [ diff --git a/plugins/auth-backend/README.md b/plugins/auth-backend/README.md index 9af90df3f2..355fcc1536 100644 --- a/plugins/auth-backend/README.md +++ b/plugins/auth-backend/README.md @@ -34,8 +34,8 @@ Follow this link, [Create new OAuth App](https://github.com/settings/application 1. Set Application Name to `backstage-dev` or something along those lines. 1. You can set the Homepage URL to whatever you want to. 1. The Authorization Callback URL should match the redirect URI set in Backstage. - 1. Set this to `http://localhost:7000/auth/github` for local development. - 1. Set this to `http://{APP_FQDN}:{APP_BACKEND_PORT}/auth/github` for non-local deployments. + 1. Set this to `http://localhost:7000/api/auth/github` for local development. + 1. Set this to `http://{APP_FQDN}:{APP_BACKEND_PORT}/api/auth/github` for non-local deployments. ```bash export AUTH_GITHUB_CLIENT_ID=x @@ -78,14 +78,14 @@ export AUTH_AUTH0_CLIENT_SECRET=x #### Creating an Azure AD App Registration -An Azure AD App Registration is required to be able to sign in using Azure AD and the Microsoft Graph API. +An Azure AD App Registration is required to be able to sign in using Azure AD and the Microsoft Graph API. Click [here](https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps) to create a new one. - Click on the `New Registration` button. - Give the app a name. e.g. `backstage-dev` - Select `Accounts in this organizational directory only` under supported account types. - Enter the callback URL for your backstage backend instance: - - For local development, this is likely `http://localhost:7000/auth/microsoft/handler/frame` + - For local development, this is likely `http://localhost:7000/api/auth/microsoft/handler/frame` - For non-local deployments, this will be `https://{APP_FQDN}:{APP_BACKEND_PORT}/auth/microsoft/handler/frame` - Click `Register`. diff --git a/plugins/auth-backend/package.json b/plugins/auth-backend/package.json index d1c563229c..d8fe00ff31 100644 --- a/plugins/auth-backend/package.json +++ b/plugins/auth-backend/package.json @@ -21,6 +21,7 @@ }, "dependencies": { "@backstage/backend-common": "^0.1.1-alpha.23", + "@backstage/catalog-model": "^0.1.1-alpha.23", "@backstage/config": "^0.1.1-alpha.23", "@types/express": "^4.17.6", "compression": "^1.7.4", @@ -36,6 +37,7 @@ "knex": "^0.21.1", "moment": "^2.26.0", "morgan": "^1.10.0", + "node-fetch": "^2.6.1", "passport": "^0.4.1", "passport-github2": "^0.1.12", "passport-gitlab2": "^5.0.0", @@ -53,12 +55,14 @@ "@types/body-parser": "^1.19.0", "@types/cookie-parser": "^1.4.2", "@types/jwt-decode": "2.2.1", + "@types/node-fetch": "^2.5.7", "@types/passport": "^1.0.3", "@types/passport-github2": "^1.2.4", "@types/passport-google-oauth20": "^2.0.3", "@types/passport-microsoft": "^0.0.0", "@types/passport-saml": "^1.1.2", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5" }, "files": [ "dist", diff --git a/plugins/auth-backend/scripts/start-saml-idp.sh b/plugins/auth-backend/scripts/start-saml-idp.sh index 33217f7978..b312a4b85e 100755 --- a/plugins/auth-backend/scripts/start-saml-idp.sh +++ b/plugins/auth-backend/scripts/start-saml-idp.sh @@ -18,4 +18,4 @@ fi echo "Downloading and starting SAML-IdP" export NPM_CONFIG_REGISTRY=https://registry.npmjs.org -exec npx saml-idp --acsUrl "http://localhost:7000/auth/saml/handler/frame" --audience "http://localhost:7000" --port 7001 +exec npx saml-idp --acsUrl "http://localhost:7000/api/auth/saml/handler/frame" --audience "http://localhost:7000" --port 7001 diff --git a/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts new file mode 100644 index 0000000000..2c1d66e1f8 --- /dev/null +++ b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.ts @@ -0,0 +1,74 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import fetch from 'node-fetch'; +import { UserEntity } from '@backstage/catalog-model'; +import { + ConflictError, + NotFoundError, + PluginEndpointDiscovery, +} from '@backstage/backend-common'; + +type UserQuery = { + annotations: Record; +}; + +/** + * A catalog client tailored for reading out identity data from the catalog. + */ +export class CatalogIdentityClient { + private readonly discovery: PluginEndpointDiscovery; + + constructor(options: { discovery: PluginEndpointDiscovery }) { + this.discovery = options.discovery; + } + + /** + * Looks up a single user using a query. + * + * Throws a NotFoundError or ConflictError if 0 or multiple users are found. + */ + async findUser(query: UserQuery): Promise { + const params = new URLSearchParams(); + params.append('kind', 'User'); + + for (const [key, value] of Object.entries(query.annotations)) { + params.append(`metadata.annotations.${key}`, value); + } + + const baseUrl = await this.discovery.getBaseUrl('catalog'); + const response = await fetch(`${baseUrl}/entities?${params}`); + + if (!response.ok) { + const text = await response.text(); + throw new Error( + `Request failed with ${response.status} ${response.statusText}, ${text}`, + ); + } + + const users: UserEntity[] = await response.json(); + + if (users.length !== 1) { + if (users.length > 1) { + throw new ConflictError('User lookup resulted in multiple matches'); + } else { + throw new NotFoundError('User not found'); + } + } + + return users[0]; + } +} diff --git a/plugins/auth-backend/src/lib/catalog/index.ts b/plugins/auth-backend/src/lib/catalog/index.ts new file mode 100644 index 0000000000..f15469668f --- /dev/null +++ b/plugins/auth-backend/src/lib/catalog/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { CatalogIdentityClient } from './CatalogIdentityClient'; diff --git a/plugins/auth-backend/src/providers/factories.ts b/plugins/auth-backend/src/providers/factories.ts index 6c83dffda3..37761c2305 100644 --- a/plugins/auth-backend/src/providers/factories.ts +++ b/plugins/auth-backend/src/providers/factories.ts @@ -14,9 +14,6 @@ * limitations under the License. */ -import Router from 'express-promise-router'; -import { Logger } from 'winston'; -import { TokenIssuer } from '../identity'; import { createGithubProvider } from './github'; import { createGitlabProvider } from './gitlab'; import { createGoogleProvider } from './google'; @@ -25,8 +22,7 @@ import { createOktaProvider } from './okta'; import { createSamlProvider } from './saml'; import { createAuth0Provider } from './auth0'; import { createMicrosoftProvider } from './microsoft'; -import { AuthProviderConfig, AuthProviderFactory } from './types'; -import { Config } from '@backstage/config'; +import { AuthProviderFactory, AuthProviderFactoryOptions } from './types'; const factories: { [providerId: string]: AuthProviderFactory } = { google: createGoogleProvider, @@ -39,31 +35,14 @@ const factories: { [providerId: string]: AuthProviderFactory } = { oauth2: createOAuth2Provider, }; -export const createAuthProviderRouter = ( +export function createAuthProvider( providerId: string, - globalConfig: AuthProviderConfig, - config: Config, - logger: Logger, - tokenIssuer: TokenIssuer, -) => { + options: AuthProviderFactoryOptions, +) { const factory = factories[providerId]; if (!factory) { throw Error(`No auth provider available for '${providerId}'`); } - const router = Router(); - - const handler = factory({ globalConfig, config, logger, tokenIssuer }); - - router.get('/start', handler.start.bind(handler)); - router.get('/handler/frame', handler.frameHandler.bind(handler)); - router.post('/handler/frame', handler.frameHandler.bind(handler)); - if (handler.logout) { - router.post('/logout', handler.logout.bind(handler)); - } - if (handler.refresh) { - router.get('/refresh', handler.refresh.bind(handler)); - } - - return router; -}; + return factory(options); +} diff --git a/plugins/auth-backend/src/providers/google/provider.ts b/plugins/auth-backend/src/providers/google/provider.ts index 3cc585605c..80143ca201 100644 --- a/plugins/auth-backend/src/providers/google/provider.ts +++ b/plugins/auth-backend/src/providers/google/provider.ts @@ -15,6 +15,7 @@ */ import express from 'express'; +import { Logger } from 'winston'; import { Strategy as GoogleStrategy } from 'passport-google-oauth20'; import { executeFrameHandlerStrategy, @@ -36,15 +37,25 @@ import { OAuthRefreshRequest, } from '../../lib/oauth'; import passport from 'passport'; +import { CatalogIdentityClient } from '../../lib/catalog'; type PrivateInfo = { refreshToken: string; }; +export type GoogleAuthProviderOptions = OAuthProviderOptions & { + logger: Logger; + identityClient: CatalogIdentityClient; +}; + export class GoogleAuthProvider implements OAuthHandlers { private readonly _strategy: GoogleStrategy; + private readonly logger: Logger; + private readonly identityClient: CatalogIdentityClient; - constructor(options: OAuthProviderOptions) { + constructor(options: GoogleAuthProviderOptions) { + this.logger = options.logger; + this.identityClient = options.identityClient; // TODO: throw error if env variables not set? this._strategy = new GoogleStrategy( { @@ -138,17 +149,37 @@ export class GoogleAuthProvider implements OAuthHandlers { throw new Error('Google profile contained no email'); } - // TODO(Rugvip): Hardcoded to the local part of the email for now - const id = profile.email.split('@')[0]; + try { + const user = await this.identityClient.findUser({ + annotations: { + 'google.com/email': profile.email, + }, + }); - return { ...response, backstageIdentity: { id } }; + return { + ...response, + backstageIdentity: { + id: user.metadata.name, + }, + }; + } catch (error) { + this.logger.warn( + `Failed to look up user, ${error}, falling back to allowing login based on email pattern, this will probably break in the future`, + ); + return { + ...response, + backstageIdentity: { id: profile.email.split('@')[0] }, + }; + } } } export const createGoogleProvider: AuthProviderFactory = ({ globalConfig, config, + logger, tokenIssuer, + discovery, }) => OAuthEnvironmentHandler.mapConfig(config, envConfig => { const providerId = 'google'; @@ -160,6 +191,8 @@ export const createGoogleProvider: AuthProviderFactory = ({ clientId, clientSecret, callbackUrl, + logger, + identityClient: new CatalogIdentityClient({ discovery }), }); return OAuthAdapter.fromConfig(globalConfig, provider, { diff --git a/plugins/auth-backend/src/providers/index.ts b/plugins/auth-backend/src/providers/index.ts index d210bfd1bb..99348438be 100644 --- a/plugins/auth-backend/src/providers/index.ts +++ b/plugins/auth-backend/src/providers/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export { createAuthProviderRouter } from './factories'; +export { createAuthProvider } from './factories'; diff --git a/plugins/auth-backend/src/providers/saml/provider.ts b/plugins/auth-backend/src/providers/saml/provider.ts index 2bd8ed0bf3..a90f3e3053 100644 --- a/plugins/auth-backend/src/providers/saml/provider.ts +++ b/plugins/auth-backend/src/providers/saml/provider.ts @@ -54,7 +54,7 @@ export class SamlAuthProvider implements AuthProviderRouteHandlers { // TODO: This flow doesn't issue an identity token that can be used to validate // the identity of the user in other backends, which we need in some form. done(undefined, { - userId: profile.ID!, + userId: profile.nameID!, profile: { email: profile.email!, displayName: profile.displayName as string, diff --git a/plugins/auth-backend/src/providers/types.ts b/plugins/auth-backend/src/providers/types.ts index 5c05b02739..6776095f99 100644 --- a/plugins/auth-backend/src/providers/types.ts +++ b/plugins/auth-backend/src/providers/types.ts @@ -18,6 +18,7 @@ import express from 'express'; import { Logger } from 'winston'; import { TokenIssuer } from '../identity'; import { Config } from '@backstage/config'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; export type AuthProviderConfig = { /** @@ -115,6 +116,7 @@ export type AuthProviderFactoryOptions = { config: Config; logger: Logger; tokenIssuer: TokenIssuer; + discovery: PluginEndpointDiscovery; }; export type AuthProviderFactory = ( diff --git a/plugins/auth-backend/src/service/router.ts b/plugins/auth-backend/src/service/router.ts index 19a74d47c5..bcd1fc1794 100644 --- a/plugins/auth-backend/src/service/router.ts +++ b/plugins/auth-backend/src/service/router.ts @@ -19,32 +19,35 @@ import Router from 'express-promise-router'; import cookieParser from 'cookie-parser'; import Knex from 'knex'; import { Logger } from 'winston'; -import { createAuthProviderRouter } from '../providers'; +import { createAuthProvider } from '../providers'; import { Config } from '@backstage/config'; import { DatabaseKeyStore, TokenFactory, createOidcRouter } from '../identity'; -import { NotFoundError } from '@backstage/backend-common'; +import { + NotFoundError, + PluginEndpointDiscovery, +} from '@backstage/backend-common'; export interface RouterOptions { logger: Logger; database: Knex; config: Config; + discovery: PluginEndpointDiscovery; } -export async function createRouter( - options: RouterOptions, -): Promise { +export async function createRouter({ + logger, + config, + discovery, + database, +}: RouterOptions): Promise { const router = Router(); - const logger = options.logger.child({ plugin: 'auth' }); - const appUrl = options.config.getString('app.baseUrl'); - const backendUrl = options.config.getString('backend.baseUrl'); - const authUrl = `${backendUrl}/auth`; + const appUrl = config.getString('app.baseUrl'); + const authUrl = await discovery.getExternalBaseUrl('auth'); const keyDurationSeconds = 3600; - const keyStore = await DatabaseKeyStore.create({ - database: options.database, - }); + const keyStore = await DatabaseKeyStore.create({ database }); const tokenIssuer = new TokenFactory({ issuer: authUrl, keyStore, @@ -56,21 +59,33 @@ export async function createRouter( router.use(express.urlencoded({ extended: false })); router.use(express.json()); - const providersConfig = options.config.getConfig('auth.providers'); + const providersConfig = config.getConfig('auth.providers'); const providers = providersConfig.keys(); for (const providerId of providers) { logger.info(`Configuring provider, ${providerId}`); try { - const providerConfig = providersConfig.getConfig(providerId); - const providerRouter = createAuthProviderRouter( - providerId, - { baseUrl: authUrl, appUrl }, - providerConfig, + const provider = createAuthProvider(providerId, { + globalConfig: { baseUrl: authUrl, appUrl }, + config: providersConfig.getConfig(providerId), logger, tokenIssuer, - ); - router.use(`/${providerId}`, providerRouter); + discovery, + }); + + const r = Router(); + + r.get('/start', provider.start.bind(provider)); + r.get('/handler/frame', provider.frameHandler.bind(provider)); + r.post('/handler/frame', provider.frameHandler.bind(provider)); + if (provider.logout) { + r.post('/logout', provider.logout.bind(provider)); + } + if (provider.refresh) { + r.get('/refresh', provider.refresh.bind(provider)); + } + + router.use(`/${providerId}`, r); } catch (e) { if (process.env.NODE_ENV !== 'development') { throw new Error( diff --git a/plugins/auth-backend/src/service/standaloneServer.ts b/plugins/auth-backend/src/service/standaloneServer.ts index dc91c92631..71771340a5 100644 --- a/plugins/auth-backend/src/service/standaloneServer.ts +++ b/plugins/auth-backend/src/service/standaloneServer.ts @@ -23,6 +23,7 @@ import { createServiceBuilder, useHotMemoize, loadBackendConfig, + SingleHostDiscovery, } from '@backstage/backend-common'; export interface ServerOptions { @@ -34,6 +35,7 @@ export async function startStandaloneServer( ): Promise { const logger = options.logger.child({ service: 'auth-backend' }); const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const discovery = SingleHostDiscovery.fromConfig(config); const database = useHotMemoize(module, () => { const knex = Knex({ @@ -52,6 +54,7 @@ export async function startStandaloneServer( logger, config, database, + discovery, }); const service = createServiceBuilder(module) diff --git a/plugins/catalog-backend/migrations/20200923104503_case_insensitivity.js b/plugins/catalog-backend/migrations/20200923104503_case_insensitivity.js new file mode 100644 index 0000000000..eeec950d7f --- /dev/null +++ b/plugins/catalog-backend/migrations/20200923104503_case_insensitivity.js @@ -0,0 +1,32 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// @ts-check + +/** + * @param {import('knex')} knex + */ +exports.up = async function up(knex) { + await knex('entities') + .where({ namespace: null }) + .update({ namespace: 'default' }); + await knex('entities_search').update({ + key: knex.raw('LOWER(key)'), + value: knex.raw('LOWER(value)'), + }); +}; + +exports.down = async function down() {}; diff --git a/plugins/catalog-backend/package.json b/plugins/catalog-backend/package.json index 7e3134a012..4eb437b871 100644 --- a/plugins/catalog-backend/package.json +++ b/plugins/catalog-backend/package.json @@ -23,7 +23,11 @@ "@backstage/backend-common": "^0.1.1-alpha.23", "@backstage/catalog-model": "^0.1.1-alpha.23", "@backstage/config": "^0.1.1-alpha.23", + "@octokit/graphql": "^4.5.6", "@types/express": "^4.17.6", + "@types/node-fetch": "^2.5.7", + "codeowners-utils": "^1.0.2", + "core-js": "^3.6.5", "express": "^4.17.1", "express-promise-router": "^3.0.3", "fs-extra": "^9.0.0", @@ -32,7 +36,7 @@ "lodash": "^4.17.15", "morgan": "^1.10.0", "node-fetch": "^2.6.0", - "sqlite3": "^4.2.0", + "sqlite3": "^5.0.0", "uuid": "^8.0.0", "winston": "^3.2.1", "yaml": "^1.9.2", @@ -41,9 +45,9 @@ }, "devDependencies": { "@backstage/cli": "^0.1.1-alpha.23", + "@types/core-js": "^2.5.4", "@types/git-url-parse": "^9.0.0", "@types/lodash": "^4.14.151", - "@types/node-fetch": "^2.5.7", "@types/supertest": "^2.0.8", "@types/uuid": "^8.0.0", "@types/yup": "^0.28.2", diff --git a/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.test.ts b/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.test.ts index bcd1248a66..1cfea23e43 100644 --- a/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.test.ts +++ b/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Entity } from '@backstage/catalog-model'; +import { Entity, ENTITY_DEFAULT_NAMESPACE } from '@backstage/catalog-model'; import { Logger } from 'winston'; import { CoalescedEntitiesCatalog } from './CoalescedEntitiesCatalog'; import { EntitiesCatalog } from './types'; @@ -115,9 +115,13 @@ describe('CoalescedEntitiesCatalog', () => { c1.entityByName.mockResolvedValueOnce(undefined); c2.entityByName.mockResolvedValueOnce(e2); const catalog = new CoalescedEntitiesCatalog([c1, c2], logger); - await expect(catalog.entityByName('k', undefined, 'n2')).resolves.toBe( - e2, - ); + await expect( + catalog.entityByName({ + kind: 'k', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'n2', + }), + ).resolves.toBe(e2); expect(c1.entityByName).toBeCalledTimes(1); expect(c2.entityByName).toBeCalledTimes(1); }); @@ -127,7 +131,11 @@ describe('CoalescedEntitiesCatalog', () => { c2.entityByName.mockResolvedValueOnce(undefined); const catalog = new CoalescedEntitiesCatalog([c1, c2], logger); await expect( - catalog.entityByName('k', undefined, 'n2'), + catalog.entityByName({ + kind: 'k', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'n2', + }), ).resolves.toBeUndefined(); expect(c1.entityByName).toBeCalledTimes(1); expect(c2.entityByName).toBeCalledTimes(1); @@ -137,9 +145,13 @@ describe('CoalescedEntitiesCatalog', () => { c1.entityByName.mockResolvedValueOnce(e1); c2.entityByName.mockRejectedValueOnce(new Error('boo')); const catalog = new CoalescedEntitiesCatalog([c1, c2], logger); - await expect(catalog.entityByName('k', undefined, 'n2')).resolves.toBe( - e1, - ); + await expect( + catalog.entityByName({ + kind: 'k', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'n2', + }), + ).resolves.toBe(e1); expect(c1.entityByName).toBeCalledTimes(1); expect(c2.entityByName).toBeCalledTimes(1); expect(mockLogger.warn).toBeCalledWith(expect.stringMatching(/boo/)); diff --git a/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.ts b/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.ts index 5a0922495e..7eaf1868cb 100644 --- a/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.ts +++ b/plugins/catalog-backend/src/catalog/CoalescedEntitiesCatalog.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Entity } from '@backstage/catalog-model'; +import { Entity, EntityName } from '@backstage/catalog-model'; import { Logger } from 'winston'; import { EntityFilters } from '../database'; import { EntitiesCatalog } from './types'; @@ -72,14 +72,10 @@ export class CoalescedEntitiesCatalog implements EntitiesCatalog { return results.find(Boolean); } - async entityByName( - kind: string, - namespace: string | undefined, - name: string, - ): Promise { + async entityByName(name: EntityName): Promise { const ops = this.inner.map(async catalog => { try { - return await catalog.entityByName(kind, namespace, name); + return await catalog.entityByName(name); } catch (e) { this.logger.warn(`Inner entityByName call failed, ${e}`); return undefined; diff --git a/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.test.ts b/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.test.ts index 5d35fe814e..b94365a9ba 100644 --- a/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.test.ts +++ b/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.test.ts @@ -27,7 +27,7 @@ describe('DatabaseEntitiesCatalog', () => { addEntity: jest.fn(), updateEntity: jest.fn(), entities: jest.fn(), - entity: jest.fn(), + entityByName: jest.fn(), entityByUid: jest.fn(), removeEntity: jest.fn(), addLocation: jest.fn(), @@ -61,12 +61,12 @@ describe('DatabaseEntitiesCatalog', () => { const catalog = new DatabaseEntitiesCatalog(db); const result = await catalog.addOrUpdateEntity(entity); - expect(db.entities).toHaveBeenCalledTimes(1); - expect(db.entities).toHaveBeenCalledWith(expect.anything(), [ - { key: 'kind', values: ['b'] }, - { key: 'name', values: ['c'] }, - { key: 'namespace', values: ['d'] }, - ]); + expect(db.entityByName).toHaveBeenCalledTimes(1); + expect(db.entityByName).toHaveBeenCalledWith(expect.anything(), { + kind: 'b', + namespace: 'd', + name: 'c', + }); expect(db.addEntity).toHaveBeenCalledTimes(1); expect(result).toBe(entity); }); @@ -146,18 +146,18 @@ describe('DatabaseEntitiesCatalog', () => { }, }; - db.entities.mockResolvedValue([{ entity: existing }]); + db.entityByName.mockResolvedValue({ entity: existing }); db.updateEntity.mockResolvedValue({ entity: existing }); const catalog = new DatabaseEntitiesCatalog(db); const result = await catalog.addOrUpdateEntity(added); - expect(db.entities).toHaveBeenCalledTimes(1); - expect(db.entities).toHaveBeenCalledWith(expect.anything(), [ - { key: 'kind', values: ['b'] }, - { key: 'name', values: ['c'] }, - { key: 'namespace', values: ['d'] }, - ]); + expect(db.entityByName).toHaveBeenCalledTimes(1); + expect(db.entityByName).toHaveBeenCalledWith(expect.anything(), { + kind: 'b', + namespace: 'd', + name: 'c', + }); expect(db.updateEntity).toHaveBeenCalledTimes(1); expect(db.updateEntity).toHaveBeenCalledWith( expect.anything(), diff --git a/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.ts b/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.ts index d6809e468f..f6aec0c268 100644 --- a/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.ts +++ b/plugins/catalog-backend/src/catalog/DatabaseEntitiesCatalog.ts @@ -16,7 +16,9 @@ import { NotFoundError } from '@backstage/backend-common'; import { + EntityName, generateUpdatedEntity, + getEntityName, LOCATION_ANNOTATION, } from '@backstage/catalog-model'; import type { Entity } from '@backstage/catalog-model'; @@ -34,20 +36,15 @@ export class DatabaseEntitiesCatalog implements EntitiesCatalog { } async entityByUid(uid: string): Promise { - const matches = await this.database.transaction(tx => - this.database.entities(tx, [{ key: 'uid', values: [uid] }]), + const response = await this.database.transaction(tx => + this.database.entityByUid(tx, uid), ); - - return matches.length ? matches[0].entity : undefined; + return response?.entity; } - async entityByName( - kind: string, - namespace: string | undefined, - name: string, - ): Promise { + async entityByName(name: EntityName): Promise { const response = await this.database.transaction(tx => - this.entityByNameInternal(tx, kind, name, namespace), + this.database.entityByName(tx, name), ); return response?.entity; } @@ -61,12 +58,7 @@ export class DatabaseEntitiesCatalog implements EntitiesCatalog { // entity) existing entity, to know whether to update or add const existing = entity.metadata.uid ? await this.database.entityByUid(tx, entity.metadata.uid) - : await this.entityByNameInternal( - tx, - entity.kind, - entity.metadata.name, - entity.metadata.namespace, - ); + : await this.database.entityByName(tx, getEntityName(entity)); // If it's an update, run the algorithm for annotation merging, updating // etag/generation, etc. @@ -113,25 +105,4 @@ export class DatabaseEntitiesCatalog implements EntitiesCatalog { return undefined; }); } - - private async entityByNameInternal( - tx: unknown, - kind: string, - name: string, - namespace: string | undefined, - ): Promise { - const matches = await this.database.entities(tx, [ - { key: 'kind', values: [kind] }, - { key: 'name', values: [name] }, - { - key: 'namespace', - values: - !namespace || namespace === 'default' - ? [null, 'default'] - : [namespace], - }, - ]); - - return matches.length ? matches[0] : undefined; - } } diff --git a/plugins/catalog-backend/src/catalog/StaticEntitiesCatalog.ts b/plugins/catalog-backend/src/catalog/StaticEntitiesCatalog.ts index 22bbd2e1a3..65fbfb9071 100644 --- a/plugins/catalog-backend/src/catalog/StaticEntitiesCatalog.ts +++ b/plugins/catalog-backend/src/catalog/StaticEntitiesCatalog.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import type { Entity } from '@backstage/catalog-model'; +import { Entity, EntityName, getEntityName } from '@backstage/catalog-model'; import lodash from 'lodash'; import type { EntitiesCatalog } from './types'; @@ -34,17 +34,15 @@ export class StaticEntitiesCatalog implements EntitiesCatalog { return item ? lodash.cloneDeep(item) : undefined; } - async entityByName( - kind: string, - name: string, - namespace: string | undefined, - ): Promise { - const item = this._entities.find( - e => - kind === e.kind && - name === e.metadata.name && - namespace === e.metadata.namespace, - ); + async entityByName(name: EntityName): Promise { + const item = this._entities.find(e => { + const candidate = getEntityName(e); + return ( + name.kind.toLowerCase() === candidate.kind.toLowerCase() && + name.namespace.toLowerCase() === candidate.namespace.toLowerCase() && + name.name.toLowerCase() === candidate.name.toLowerCase() + ); + }); return item ? lodash.cloneDeep(item) : undefined; } diff --git a/plugins/catalog-backend/src/catalog/types.ts b/plugins/catalog-backend/src/catalog/types.ts index b0d3dde0fb..37618a2440 100644 --- a/plugins/catalog-backend/src/catalog/types.ts +++ b/plugins/catalog-backend/src/catalog/types.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Entity, Location } from '@backstage/catalog-model'; +import { Entity, EntityName, Location } from '@backstage/catalog-model'; import type { EntityFilters } from '../database'; // @@ -24,11 +24,7 @@ import type { EntityFilters } from '../database'; export type EntitiesCatalog = { entities(filters?: EntityFilters): Promise; entityByUid(uid: string): Promise; - entityByName( - kind: string, - namespace: string | undefined, - name: string, - ): Promise; + entityByName(name: EntityName): Promise; addOrUpdateEntity(entity: Entity, locationId?: string): Promise; removeEntityByUid(uid: string): Promise; }; diff --git a/plugins/catalog-backend/src/database/CommonDatabase.test.ts b/plugins/catalog-backend/src/database/CommonDatabase.test.ts index b86b4ef959..8b8067f641 100644 --- a/plugins/catalog-backend/src/database/CommonDatabase.test.ts +++ b/plugins/catalog-backend/src/database/CommonDatabase.test.ts @@ -395,5 +395,90 @@ describe('CommonDatabase', () => { ]), ); }); + + it('can get all specific entities for matching filters case insensitively)', async () => { + const entities: Entity[] = [ + { apiVersion: 'A', kind: 'K1', metadata: { name: 'N' } }, + { + apiVersion: 'a', + kind: 'k2', + metadata: { name: 'n' }, + spec: { c: 'Some' }, + }, + { + apiVersion: 'a', + kind: 'k3', + metadata: { name: 'n' }, + spec: { c: null }, + }, + ]; + + await db.transaction(async tx => { + for (const entity of entities) { + await db.addEntity(tx, { entity }); + } + }); + + const rows = await db.transaction(async tx => + db.entities(tx, [ + { key: 'ApiVersioN', values: ['A'] }, + { key: 'spEc.C', values: [null, 'some'] }, + ]), + ); + + expect(rows.length).toEqual(3); + expect(rows).toEqual( + expect.arrayContaining([ + { + locationId: undefined, + entity: expect.objectContaining({ kind: 'K1' }), + }, + { + locationId: undefined, + entity: expect.objectContaining({ kind: 'k2' }), + }, + { + locationId: undefined, + entity: expect.objectContaining({ kind: 'k3' }), + }, + ]), + ); + }); + }); + + describe('entityByName', () => { + it('can get entities case insensitively', async () => { + const entities: Entity[] = [ + { + apiVersion: 'a', + kind: 'k1', + metadata: { name: 'n' }, + }, + { + apiVersion: 'B', + kind: 'K2', + metadata: { name: 'N', namespace: 'NS' }, + }, + ]; + + await db.transaction(async tx => { + for (const entity of entities) { + await db.addEntity(tx, { entity }); + } + }); + + const e1 = await db.transaction(async tx => + db.entityByName(tx, { kind: 'k1', namespace: 'default', name: 'n' }), + ); + expect(e1!.entity.metadata.name).toEqual('n'); + const e2 = await db.transaction(async tx => + db.entityByName(tx, { kind: 'k2', namespace: 'nS', name: 'n' }), + ); + expect(e2!.entity.metadata.name).toEqual('N'); + const e3 = await db.transaction(async tx => + db.entityByName(tx, { kind: 'unknown', namespace: 'nS', name: 'n' }), + ); + expect(e3).toBeUndefined(); + }); }); }); diff --git a/plugins/catalog-backend/src/database/CommonDatabase.ts b/plugins/catalog-backend/src/database/CommonDatabase.ts index 4ad5362fb6..9ac1fff951 100644 --- a/plugins/catalog-backend/src/database/CommonDatabase.ts +++ b/plugins/catalog-backend/src/database/CommonDatabase.ts @@ -22,9 +22,12 @@ import { import { Entity, EntityMeta, - entityMetaGeneratedFields, + EntityName, + ENTITY_DEFAULT_NAMESPACE, + ENTITY_META_GENERATED_FIELDS, generateEntityEtag, generateEntityUid, + getEntityName, Location, } from '@backstage/catalog-model'; import Knex from 'knex'; @@ -172,7 +175,7 @@ export class CommonDatabase implements Database { let builder = tx('entities'); for (const [indexU, filter] of (filters ?? []).entries()) { const index = Number(indexU); - const key = filter.key.replace('*', '%'); + const key = filter.key.toLowerCase().replace('*', '%'); const keyOp = filter.key.includes('*') ? 'like' : '='; let matchNulls = false; @@ -183,9 +186,9 @@ export class CommonDatabase implements Database { if (!value) { matchNulls = true; } else if (value.includes('*')) { - matchLike.push(value.replace('*', '%')); + matchLike.push(value.toLowerCase().replace('*', '%')); } else { - matchIn.push(value); + matchIn.push(value.toLowerCase()); } } @@ -219,16 +222,19 @@ export class CommonDatabase implements Database { return rows.map(row => this.toEntityResponse(row)); } - async entity( + async entityByName( txOpaque: unknown, - kind: string, - name: string, - namespace?: string, + name: EntityName, ): Promise { const tx = txOpaque as Knex.Transaction; const rows = await tx('entities') - .where({ kind, name, namespace: namespace || null }) + .whereRaw( + tx.raw( + 'LOWER(kind) = LOWER(?) AND LOWER(namespace) = LOWER(?) AND LOWER(name) = LOWER(?)', + [name.kind, name.namespace, name.name], + ), + ) .select(); if (rows.length !== 1) { @@ -240,11 +246,13 @@ export class CommonDatabase implements Database { async entityByUid( txOpaque: unknown, - id: string, + uid: string, ): Promise { const tx = txOpaque as Knex.Transaction; - const rows = await tx('entities').where({ id }).select(); + const rows = await tx('entities') + .where({ id: uid }) + .select(); if (rows.length !== 1) { return undefined; @@ -381,36 +389,40 @@ export class CommonDatabase implements Database { tx: Knex.Transaction, data: Entity, ): Promise { - const newKind = data.kind; - const newName = data.metadata.name; - const newNamespace = data.metadata.namespace; + const { + kind: newKind, + namespace: newNamespace, + name: newName, + } = getEntityName(data); const newKindNorm = this.normalize(newKind); + const newNamespaceNorm = this.normalize(newNamespace); const newNameNorm = this.normalize(newName); - const newNamespaceNorm = this.normalize(newNamespace || ''); for (const item of await this.entities(tx)) { if (data.metadata.uid === item.entity.metadata.uid) { continue; } - const oldKind = item.entity.kind; - const oldName = item.entity.metadata.name; - const oldNamespace = item.entity.metadata.namespace; + const { + kind: oldKind, + namespace: oldNamespace, + name: oldName, + } = getEntityName(item.entity); const oldKindNorm = this.normalize(oldKind); + const oldNamespaceNorm = this.normalize(oldNamespace); const oldNameNorm = this.normalize(oldName); - const oldNamespaceNorm = this.normalize(oldNamespace || ''); if ( oldKindNorm === newKindNorm && - oldNameNorm === newNameNorm && - oldNamespaceNorm === newNamespaceNorm + oldNamespaceNorm === newNamespaceNorm && + oldNameNorm === newNameNorm ) { // Only throw if things were actually different - for completely equal // things, we let the database handle the conflict if ( oldKind !== newKind || - oldName !== newName || - oldNamespace !== newNamespace + oldNamespace !== newNamespace || + oldName !== newName ) { const message = `Kind, namespace, name are too similar to an existing entity`; throw new ConflictError(message); @@ -431,9 +443,9 @@ export class CommonDatabase implements Database { api_version: entity.apiVersion, kind: entity.kind, name: entity.metadata.name, - namespace: entity.metadata.namespace || null, + namespace: entity.metadata.namespace || ENTITY_DEFAULT_NAMESPACE, metadata: JSON.stringify( - lodash.omit(entity.metadata, ...entityMetaGeneratedFields), + lodash.omit(entity.metadata, ...ENTITY_META_GENERATED_FIELDS), ), spec: entity.spec ? JSON.stringify(entity.spec) : null, }; diff --git a/plugins/catalog-backend/src/database/search.test.ts b/plugins/catalog-backend/src/database/search.test.ts index 38a2d40e74..6da87f9150 100644 --- a/plugins/catalog-backend/src/database/search.test.ts +++ b/plugins/catalog-backend/src/database/search.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import type { Entity } from '@backstage/catalog-model'; +import { ENTITY_DEFAULT_NAMESPACE, Entity } from '@backstage/catalog-model'; import { buildEntitySearch, visitEntityPart } from './search'; import type { DbEntitiesSearchRow } from './types'; @@ -95,6 +95,16 @@ describe('search', () => { { entity_id: 'eid', key: 'root.list.a', value: '2' }, ]); }); + + it('emits lowercase version of keys and values', () => { + const input = { theRoot: { listItems: [{ a: 'One' }, { a: 2 }] } }; + const output: DbEntitiesSearchRow[] = []; + visitEntityPart('eid', '', input, output); + expect(output).toEqual([ + { entity_id: 'eid', key: 'theroot.listitems.a', value: 'one' }, + { entity_id: 'eid', key: 'theroot.listitems.a', value: '2' }, + ]); + }); }); describe('buildEntitySearch', () => { @@ -108,11 +118,17 @@ describe('search', () => { { entity_id: 'eid', key: 'metadata.name', value: 'n' }, { entity_id: 'eid', key: 'metadata.namespace', value: null }, { entity_id: 'eid', key: 'metadata.uid', value: null }, - { entity_id: 'eid', key: 'apiVersion', value: 'a' }, + { + entity_id: 'eid', + key: 'metadata.namespace', + value: ENTITY_DEFAULT_NAMESPACE, + }, + { entity_id: 'eid', key: 'apiversion', value: 'a' }, { entity_id: 'eid', key: 'kind', value: 'b' }, { entity_id: 'eid', key: 'name', value: 'n' }, { entity_id: 'eid', key: 'namespace', value: null }, { entity_id: 'eid', key: 'uid', value: null }, + { entity_id: 'eid', key: 'namespace', value: ENTITY_DEFAULT_NAMESPACE }, ]); }); diff --git a/plugins/catalog-backend/src/database/search.ts b/plugins/catalog-backend/src/database/search.ts index c14acb6661..cbcd01a5d0 100644 --- a/plugins/catalog-backend/src/database/search.ts +++ b/plugins/catalog-backend/src/database/search.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import type { Entity } from '@backstage/catalog-model'; +import { Entity, ENTITY_DEFAULT_NAMESPACE } from '@backstage/catalog-model'; import type { DbEntitiesSearchRow } from './types'; // Search entries that start with these prefixes, also get a shorthand without @@ -26,7 +26,7 @@ const SHORTHAND_KEY_PREFIXES = [ 'spec.', ]; -// These are exluded in the generic loop, either because they do not make sense +// These are excluded in the generic loop, either because they do not make sense // to index, or because they are special-case always inserted whether they are // null or not const SPECIAL_KEYS = [ @@ -42,7 +42,7 @@ function toValue(current: any): string | null { return null; } - return String(current); + return String(current).toLowerCase(); } // Helper for iterating through a nested structure and outputting a list of @@ -106,7 +106,12 @@ export function visitEntityPart( // object for (const [key, value] of Object.entries(current)) { - visitEntityPart(entityId, path ? `${path}.${key}` : key, value, output); + visitEntityPart( + entityId, + (path ? `${path}.${key}` : key).toLowerCase(), + value, + output, + ); } } @@ -141,6 +146,16 @@ export function buildEntitySearch( }, ]; + // Namespace not specified has the default value "default", so we want to + // match on that as well + if (!entity.metadata.namespace) { + result.push({ + entity_id: entityId, + key: 'metadata.namespace', + value: toValue(ENTITY_DEFAULT_NAMESPACE), + }); + } + // Visit the entire structure recursively visitEntityPart(entityId, '', entity, result); diff --git a/plugins/catalog-backend/src/database/types.ts b/plugins/catalog-backend/src/database/types.ts index 0537b87800..8aaf212583 100644 --- a/plugins/catalog-backend/src/database/types.ts +++ b/plugins/catalog-backend/src/database/types.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import type { Entity, Location } from '@backstage/catalog-model'; +import type { Entity, EntityName, Location } from '@backstage/catalog-model'; export type DbEntitiesRow = { id: string; @@ -129,11 +129,9 @@ export type Database = { entities(tx: unknown, filters?: EntityFilters): Promise; - entity( + entityByName( tx: unknown, - kind: string, - name: string, - namespace?: string, + name: EntityName, ): Promise; entityByUid(tx: unknown, uid: string): Promise; diff --git a/plugins/catalog-backend/src/ingestion/CatalogRules.ts b/plugins/catalog-backend/src/ingestion/CatalogRules.ts index e964524bc7..e82699f526 100644 --- a/plugins/catalog-backend/src/ingestion/CatalogRules.ts +++ b/plugins/catalog-backend/src/ingestion/CatalogRules.ts @@ -74,11 +74,11 @@ export class CatalogRulesEnforcer { * - allow: [Component, API] * * locations: - * - type: github + * - type: url * target: https://github.com/org/repo/blob/master/users.yaml * rules: * - allow: [User, Group] - * - type: github + * - type: url * target: https://github.com/org/repo/blob/master/systems.yaml * rules: * - allow: [System] diff --git a/plugins/catalog-backend/src/ingestion/HigherOrderOperations.test.ts b/plugins/catalog-backend/src/ingestion/HigherOrderOperations.test.ts index de68a16e9c..32fcc27909 100644 --- a/plugins/catalog-backend/src/ingestion/HigherOrderOperations.test.ts +++ b/plugins/catalog-backend/src/ingestion/HigherOrderOperations.test.ts @@ -15,7 +15,12 @@ */ import { getVoidLogger } from '@backstage/backend-common'; -import { Entity, Location, LocationSpec } from '@backstage/catalog-model'; +import { + Entity, + ENTITY_DEFAULT_NAMESPACE, + Location, + LocationSpec, +} from '@backstage/catalog-model'; import { EntitiesCatalog, LocationsCatalog } from '../catalog'; import { LocationUpdateStatus } from '../catalog/types'; import { DatabaseLocationUpdateLogStatus } from '../database/types'; @@ -200,12 +205,11 @@ describe('HigherOrderOperations', () => { target: 'thing', }); expect(entitiesCatalog.entityByName).toHaveBeenCalledTimes(1); - expect(entitiesCatalog.entityByName).toHaveBeenNthCalledWith( - 1, - 'Component', - undefined, - 'c1', - ); + expect(entitiesCatalog.entityByName).toHaveBeenNthCalledWith(1, { + kind: 'Component', + namespace: ENTITY_DEFAULT_NAMESPACE, + name: 'c1', + }); expect(entitiesCatalog.addOrUpdateEntity).toHaveBeenCalledTimes(1); expect(entitiesCatalog.addOrUpdateEntity).toHaveBeenNthCalledWith( 1, diff --git a/plugins/catalog-backend/src/ingestion/HigherOrderOperations.ts b/plugins/catalog-backend/src/ingestion/HigherOrderOperations.ts index 0224dc7f1d..1b60666c8e 100644 --- a/plugins/catalog-backend/src/ingestion/HigherOrderOperations.ts +++ b/plugins/catalog-backend/src/ingestion/HigherOrderOperations.ts @@ -18,6 +18,7 @@ import { InputError } from '@backstage/backend-common'; import { Entity, entityHasChanges, + getEntityName, Location, LocationSpec, } from '@backstage/catalog-model'; @@ -162,16 +163,14 @@ export class HigherOrderOperations implements HigherOrderOperation { const { entity } = item; this.logger.debug( - `Read entity kind="${entity.kind}" name="${ - entity.metadata.name - }" namespace="${entity.metadata.namespace || ''}"`, + `Read entity kind="${entity.kind}" namespace="${ + entity.metadata.namespace || '' + }" name="${entity.metadata.name}"`, ); try { const previous = await this.entitiesCatalog.entityByName( - entity.kind, - entity.metadata.namespace, - entity.metadata.name, + getEntityName(entity), ); if (!previous) { diff --git a/plugins/catalog-backend/src/ingestion/LocationReaders.ts b/plugins/catalog-backend/src/ingestion/LocationReaders.ts index 8da6e20ab3..96ffaf398c 100644 --- a/plugins/catalog-backend/src/ingestion/LocationReaders.ts +++ b/plugins/catalog-backend/src/ingestion/LocationReaders.ts @@ -14,27 +14,32 @@ * limitations under the License. */ -import { getVoidLogger } from '@backstage/backend-common'; -import { Config, ConfigReader } from '@backstage/config'; +import { getVoidLogger, UrlReader } from '@backstage/backend-common'; import { Entity, EntityPolicies, EntityPolicy, + ENTITY_DEFAULT_NAMESPACE, LocationSpec, } from '@backstage/catalog-model'; +import { Config, ConfigReader } from '@backstage/config'; import { Logger } from 'winston'; +import { CatalogRulesEnforcer } from './CatalogRules'; import { AnnotateLocationEntityProcessor } from './processors/AnnotateLocationEntityProcessor'; +import { ApiDefinitionAtLocationProcessor } from './processors/ApiDefinitionAtLocationProcessor'; +import { AzureApiReaderProcessor } from './processors/AzureApiReaderProcessor'; +import { BitbucketApiReaderProcessor } from './processors/BitbucketApiReaderProcessor'; import { EntityPolicyProcessor } from './processors/EntityPolicyProcessor'; import { FileReaderProcessor } from './processors/FileReaderProcessor'; +import { GithubOrgReaderProcessor } from './processors/GithubOrgReaderProcessor'; import { GithubReaderProcessor } from './processors/GithubReaderProcessor'; import { GitlabApiReaderProcessor } from './processors/GitlabApiReaderProcessor'; import { GitlabReaderProcessor } from './processors/GitlabReaderProcessor'; -import { BitbucketApiReaderProcessor } from './processors/BitbucketApiReaderProcessor'; -import { AzureApiReaderProcessor } from './processors/AzureApiReaderProcessor'; -import { UrlReaderProcessor } from './processors/UrlReaderProcessor'; import { LocationRefProcessor } from './processors/LocationEntityProcessor'; -import { StaticLocationProcessor } from './processors/StaticLocationProcessor'; +import { PlaceholderProcessor } from './processors/PlaceholderProcessor'; +import { CodeOwnersProcessor } from './processors/CodeOwnersProcessor'; import * as result from './processors/results'; +import { StaticLocationProcessor } from './processors/StaticLocationProcessor'; import { LocationProcessor, LocationProcessorDataResult, @@ -44,14 +49,15 @@ import { LocationProcessorLocationResult, LocationProcessorResult, } from './processors/types'; +import { UrlReaderProcessor } from './processors/UrlReaderProcessor'; import { YamlProcessor } from './processors/YamlProcessor'; import { LocationReader, ReadLocationResult } from './types'; -import { CatalogRulesEnforcer } from './CatalogRules'; // The max amount of nesting depth of generated work items const MAX_DEPTH = 10; type Options = { + reader: UrlReader; logger?: Logger; config?: Config; processors?: LocationProcessor[]; @@ -67,6 +73,7 @@ export class LocationReaders implements LocationReader { static defaultProcessors(options: { logger: Logger; + reader: UrlReader; config?: Config; entityPolicy?: EntityPolicy; }): LocationProcessor[] { @@ -75,16 +82,50 @@ export class LocationReaders implements LocationReader { config = new ConfigReader({}, 'missing-config'), entityPolicy = new EntityPolicies(), } = options; + + // TODO(Rugvip): These are added for backwards compatibility if config exists + // The idea is to have everyone migrate from using the old processors to the new + // integration config driven UrlReaders. In an upcoming release we can then completely + // remove support for the old processors, but still keep handling the deprecated location + // types for a while, but with a warning. + const oldProcessors = []; + const pc = config.getOptionalConfig('catalog.processors'); + if (pc?.has('github')) { + logger.warn( + `Using deprecated configuration for catalog.processors.github, move to using integrations.github instead`, + ); + oldProcessors.push(GithubReaderProcessor.fromConfig(config, logger)); + } + if (pc?.has('gitlabApi')) { + logger.warn( + `Using deprecated configuration for catalog.processors.gitlabApi, move to using integrations.gitlab instead`, + ); + oldProcessors.push(new GitlabApiReaderProcessor(config)); + oldProcessors.push(new GitlabReaderProcessor()); + } + if (pc?.has('bitbucketApi')) { + logger.warn( + `Using deprecated configuration for catalog.processors.bitbucketApi, move to using integrations.bitbucket instead`, + ); + oldProcessors.push(new BitbucketApiReaderProcessor(config)); + } + if (pc?.has('azureApi')) { + logger.warn( + `Using deprecated configuration for catalog.processors.azureApi, move to using integrations.azure instead`, + ); + oldProcessors.push(new AzureApiReaderProcessor(config)); + } + return [ StaticLocationProcessor.fromConfig(config), new FileReaderProcessor(), - GithubReaderProcessor.fromConfig(config, logger), - new GitlabApiReaderProcessor(config), - new GitlabReaderProcessor(), - new BitbucketApiReaderProcessor(config), - new AzureApiReaderProcessor(config), - new UrlReaderProcessor(), + ...oldProcessors, + GithubOrgReaderProcessor.fromConfig(config), + new UrlReaderProcessor(options), new YamlProcessor(), + PlaceholderProcessor.default(), + new CodeOwnersProcessor(), + new ApiDefinitionAtLocationProcessor(), new EntityPolicyProcessor(entityPolicy), new LocationRefProcessor(), new AnnotateLocationEntityProcessor(), @@ -94,7 +135,8 @@ export class LocationReaders implements LocationReader { constructor({ logger = getVoidLogger(), config, - processors = LocationReaders.defaultProcessors({ logger, config }), + reader, + processors = LocationReaders.defaultProcessors({ logger, reader, config }), }: Options) { this.logger = logger; this.processors = processors; @@ -172,12 +214,14 @@ export class LocationReaders implements LocationReader { } catch (e) { const message = `Processor ${processor.constructor.name} threw an error while reading location ${item.location.type} ${item.location.target}, ${e}`; emit(result.generalError(item.location, message)); + this.logger.warn(message); } } } const message = `No processor was able to read location ${item.location.type} ${item.location.target}`; emit(result.inputError(item.location, message)); + this.logger.warn(message); } private async handleData( @@ -197,6 +241,7 @@ export class LocationReaders implements LocationReader { } catch (e) { const message = `Processor ${processor.constructor.name} threw an error while parsing ${item.location.type} ${item.location.target}, ${e}`; emit(result.generalError(item.location, message)); + this.logger.warn(message); } } } @@ -218,10 +263,22 @@ export class LocationReaders implements LocationReader { for (const processor of this.processors) { if (processor.processEntity) { try { - current = await processor.processEntity(current, item.location, emit); + current = await processor.processEntity( + current, + item.location, + emit, + this.readLocation.bind(this), + ); } catch (e) { - const message = `Processor ${processor.constructor.name} threw an error while processing entity at ${item.location.type} ${item.location.target}, ${e}`; + // Construct the name carefully, if we got validation errors we do + // not want to crash here due to missing metadata or so + const namespace = !current.metadata + ? '' + : current.metadata.namespace ?? ENTITY_DEFAULT_NAMESPACE; + const name = !current.metadata ? '' : current.metadata.name; + const message = `Processor ${processor.constructor.name} threw an error while processing entity ${current.kind}:${namespace}/${name} at ${item.location.type} ${item.location.target}, ${e}`; emit(result.generalError(item.location, message)); + this.logger.warn(message); } } } @@ -244,8 +301,45 @@ export class LocationReaders implements LocationReader { } catch (e) { const message = `Processor ${processor.constructor.name} threw an error while handling another error at ${item.location.type} ${item.location.target}, ${e}`; emit(result.generalError(item.location, message)); + this.logger.warn(message); } } } } + + private async readLocation(location: LocationSpec): Promise { + let data: Buffer | undefined = undefined; + let error: Error | undefined = undefined; + + await this.handleLocation( + { + type: 'location', + location, + optional: false, + }, + output => { + if (output.type === 'error' && !error) { + error = output.error; + } else if (output.type === 'data') { + if (data) { + if (!error) { + error = new Error( + 'More than one piece of data loaded unexpectedly', + ); + } + } else { + data = output.data; + } + } + }, + ); + + if (error) { + throw error; + } else if (!data) { + throw new Error('No data loaded'); + } + + return data; + } } diff --git a/plugins/catalog-backend/src/ingestion/processors/ApiDefinitionAtLocationProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/ApiDefinitionAtLocationProcessor.test.ts new file mode 100644 index 0000000000..6ae6562339 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/ApiDefinitionAtLocationProcessor.test.ts @@ -0,0 +1,93 @@ +import { ApiEntity, Entity, LocationSpec } from '@backstage/catalog-model'; +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ApiDefinitionAtLocationProcessor } from './ApiDefinitionAtLocationProcessor'; + +describe('ApiDefinitionAtLocationProcessor', () => { + let processor: ApiDefinitionAtLocationProcessor; + let entity: Entity; + let location: LocationSpec; + + beforeEach(() => { + processor = new ApiDefinitionAtLocationProcessor(); + entity = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'API', + metadata: { + name: 'test', + }, + spec: { + lifecycle: 'production', + owner: 'info@example.com', + type: 'openapi', + definition: 'Hello', + }, + }; + location = { + type: 'url', + target: `http://example.com/api.yaml`, + }; + }); + + it('should skip entities without annotation', async () => { + const read = jest.fn().mockRejectedValue(new Error('boo')); + + const generated = (await processor.processEntity( + entity, + location, + () => {}, + read, + )) as ApiEntity; + + expect(generated.spec.definition).toBe('Hello'); + }); + + it('should load from location', async () => { + entity.metadata.annotations = { + 'backstage.io/definition-at-location': + 'url:http://example.com/openapi.yaml', + }; + + const read = jest.fn().mockResolvedValue(Buffer.from('Hello')); + + const generated = (await processor.processEntity( + entity, + location, + () => {}, + read, + )) as ApiEntity; + + expect(generated.spec.definition).toBe('Hello'); + expect(read.mock.calls[0][0]).toStrictEqual({ + type: 'url', + target: 'http://example.com/openapi.yaml', + }); + }); + + it('should throw errors while loading', async () => { + entity.metadata.annotations = { + 'backstage.io/definition-at-location': 'missing', + }; + + const read = jest + .fn() + .mockRejectedValue(new Error('Failed to load location')); + + await expect( + processor.processEntity(entity, location, () => {}, read), + ).rejects.toThrow('Failed to load location'); + }); +}); diff --git a/plugins/catalog-backend/src/ingestion/processors/ApiDefinitionAtLocationProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/ApiDefinitionAtLocationProcessor.ts new file mode 100644 index 0000000000..e64d112e9c --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/ApiDefinitionAtLocationProcessor.ts @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ApiEntity, Entity, LocationSpec } from '@backstage/catalog-model'; +import { + LocationProcessor, + LocationProcessorEmit, + LocationProcessorRead, +} from './types'; + +const DEFINITION_AT_LOCATION_ANNOTATION = 'backstage.io/definition-at-location'; + +export class ApiDefinitionAtLocationProcessor implements LocationProcessor { + async processEntity( + entity: Entity, + _location: LocationSpec, + _emit: LocationProcessorEmit, + read: LocationProcessorRead, + ): Promise { + if ( + entity.kind !== 'API' || + !entity.metadata.annotations || + !entity.metadata.annotations[DEFINITION_AT_LOCATION_ANNOTATION] + ) { + return entity; + } + + const reference = + entity.metadata.annotations[DEFINITION_AT_LOCATION_ANNOTATION]; + const { type, target } = extractReference(reference); + const data = await read({ type, target }); + const definition = data.toString(); + const apiEntity = entity as ApiEntity; + apiEntity.spec.definition = definition; + + return entity; + } +} + +function extractReference(reference: string): { type: string; target: string } { + const delimiterIndex = reference.indexOf(':'); + const type = reference.slice(0, delimiterIndex); + const target = reference.slice(delimiterIndex + 1); + + return { type, target }; +} diff --git a/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.test.ts deleted file mode 100644 index 9b234e3e75..0000000000 --- a/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { AzureApiReaderProcessor } from './AzureApiReaderProcessor'; -import { ConfigReader } from '@backstage/config'; - -describe('AzureApiReaderProcessor', () => { - const createConfig = (token: string | undefined) => - ConfigReader.fromConfigs([ - { - context: '', - data: { - catalog: { - processors: { - azureApi: { - privateToken: token, - }, - }, - }, - }, - }, - ]); - - it('should build raw api', () => { - const processor = new AzureApiReaderProcessor(createConfig(undefined)); - const tests = [ - { - target: - 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml&version=GBmaster', - url: new URL( - 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml&version=master', - ), - err: undefined, - }, - { - target: - 'https://dev.azure.com/org-name/project-name/_git/repo-name?path=my-template.yaml', - url: new URL( - 'https://dev.azure.com/org-name/project-name/_apis/git/repositories/repo-name/items?path=my-template.yaml', - ), - err: undefined, - }, - { - target: 'https://api.com/a/b/blob/master/path/to/c.yaml', - url: null, - err: - 'Incorrect url: https://api.com/a/b/blob/master/path/to/c.yaml, Error: Wrong Azure Devops URL or Invalid file path', - }, - { - target: 'com/a/b/blob/master/path/to/c.yaml', - url: null, - err: - 'Incorrect url: com/a/b/blob/master/path/to/c.yaml, TypeError: Invalid URL: com/a/b/blob/master/path/to/c.yaml', - }, - ]; - - for (const test of tests) { - if (test.err) { - expect(() => processor.buildRawUrl(test.target)).toThrowError(test.err); - } else if (test.url) { - expect(processor.buildRawUrl(test.target).toString()).toEqual( - test.url.toString(), - ); - } else { - throw new Error( - 'This should not have happened. Either err or url should have matched.', - ); - } - } - }); - - it('should return request options', () => { - const tests = [ - { - token: '0123456789', - expect: { - headers: { - Authorization: 'Basic OjAxMjM0NTY3ODk=', - }, - }, - }, - { - token: '', - expect: { - headers: {}, - }, - err: - "Invalid type in config for key 'catalog.processors.azureApi.privateToken' in '', got empty-string, wanted string", - }, - { - token: undefined, - expect: { - headers: {}, - }, - }, - ]; - - for (const test of tests) { - if (test.err) { - expect( - () => new AzureApiReaderProcessor(createConfig(test.token)), - ).toThrowError(test.err); - } else { - const processor = new AzureApiReaderProcessor(createConfig(test.token)); - expect(processor.getRequestOptions()).toEqual(test.expect); - } - } - }); -}); diff --git a/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.ts index 03ff30ea69..2a15c18c84 100644 --- a/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/AzureApiReaderProcessor.ts @@ -20,6 +20,11 @@ import * as result from './results'; import { LocationProcessor, LocationProcessorEmit } from './types'; import { Config } from '@backstage/config'; +// *********************************************************************** +// * NOTE: This has been replaced by packages/backend-common/src/reading * +// * Don't implement new functionality here as this file will be removed * +// *********************************************************************** + export class AzureApiReaderProcessor implements LocationProcessor { private privateToken: string; @@ -107,8 +112,7 @@ export class AzureApiReaderProcessor implements LocationProcessor { srcKeyword !== '_git' || repoName === '' || path === '' || - ref === '' || - !path.match(/\.yaml$/) + ref === '' ) { throw new Error('Wrong Azure Devops URL or Invalid file path'); } diff --git a/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.test.ts deleted file mode 100644 index 953f0703be..0000000000 --- a/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { BitbucketApiReaderProcessor } from './BitbucketApiReaderProcessor'; -import { ConfigReader } from '@backstage/config'; - -describe('BitbucketApiReaderProcessor', () => { - const createConfig = ( - username: string | undefined, - appPassword: string | undefined, - ) => - ConfigReader.fromConfigs([ - { - context: '', - data: { - catalog: { - processors: { - bitbucketApi: { - username: username, - appPassword: appPassword, - }, - }, - }, - }, - }, - ]); - - it('should build raw api', () => { - const processor = new BitbucketApiReaderProcessor( - createConfig(undefined, undefined), - ); - - const tests = [ - { - target: - 'https://bitbucket.org/org-name/repo-name/src/master/templates/my-template.yaml', - url: new URL( - 'https://api.bitbucket.org/2.0/repositories/org-name/repo-name/src/master/templates/my-template.yaml', - ), - err: undefined, - }, - { - target: 'https://api.com/a/b/blob/master/path/to/c.yaml', - url: null, - err: - 'Incorrect url: https://api.com/a/b/blob/master/path/to/c.yaml, Error: Wrong Bitbucket URL or Invalid file path', - }, - { - target: 'com/a/b/blob/master/path/to/c.yaml', - url: null, - err: - 'Incorrect url: com/a/b/blob/master/path/to/c.yaml, TypeError: Invalid URL: com/a/b/blob/master/path/to/c.yaml', - }, - ]; - - for (const test of tests) { - if (test.err) { - expect(() => processor.buildRawUrl(test.target)).toThrowError(test.err); - } else if (test.url) { - expect(processor.buildRawUrl(test.target).toString()).toEqual( - test.url.toString(), - ); - } else { - throw new Error( - 'This should not have happened. Either err or url should have matched.', - ); - } - } - }); - - it('should return request options', () => { - const tests = [ - { - username: '', - password: '', - expect: { - headers: {}, - }, - err: - "Invalid type in config for key 'catalog.processors.bitbucketApi.username' in '', got empty-string, wanted string", - }, - { - username: 'only-user-provided', - password: '', - expect: { - headers: {}, - }, - err: - "Invalid type in config for key 'catalog.processors.bitbucketApi.appPassword' in '', got empty-string, wanted string", - }, - { - username: '', - password: 'only-password-provided', - expect: { - headers: {}, - }, - err: - "Invalid type in config for key 'catalog.processors.bitbucketApi.username' in '', got empty-string, wanted string", - }, - { - username: 'some-user', - password: 'my-secret', - expect: { - headers: { - Authorization: 'Basic c29tZS11c2VyOm15LXNlY3JldA==', - }, - }, - }, - { - username: undefined, - password: undefined, - expect: { - headers: {}, - }, - }, - { - username: 'only-user-provided', - password: undefined, - expect: { - headers: {}, - }, - }, - { - username: undefined, - password: 'only-password-provided', - expect: { - headers: {}, - }, - }, - ]; - - for (const test of tests) { - if (test.err) { - expect( - () => - new BitbucketApiReaderProcessor( - createConfig(test.username, test.password), - ), - ).toThrowError(test.err); - } else { - const processor = new BitbucketApiReaderProcessor( - createConfig(test.username, test.password), - ); - expect(processor.getRequestOptions()).toEqual(test.expect); - } - } - }); -}); diff --git a/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.ts index 97ecf0cd1f..b3720a5b76 100644 --- a/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/BitbucketApiReaderProcessor.ts @@ -20,6 +20,11 @@ import * as result from './results'; import { LocationProcessor, LocationProcessorEmit } from './types'; import { Config } from '@backstage/config'; +// *********************************************************************** +// * NOTE: This has been replaced by packages/backend-common/src/reading * +// * Don't implement new functionality here as this file will be removed * +// *********************************************************************** + export class BitbucketApiReaderProcessor implements LocationProcessor { private username: string; private password: string; @@ -106,8 +111,7 @@ export class BitbucketApiReaderProcessor implements LocationProcessor { empty !== '' || userOrOrg === '' || repoName === '' || - srcKeyword !== 'src' || - !restOfPath.join('/').match(/\.yaml$/) + srcKeyword !== 'src' ) { throw new Error('Wrong Bitbucket URL or Invalid file path'); } diff --git a/plugins/catalog-backend/src/ingestion/processors/CodeOwnersProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/CodeOwnersProcessor.test.ts new file mode 100644 index 0000000000..29f94dd0d7 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/CodeOwnersProcessor.test.ts @@ -0,0 +1,279 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LocationSpec } from '@backstage/catalog-model'; +import { CodeOwnersEntry } from 'codeowners-utils'; +import { + buildCodeOwnerLocation, + buildUrl, + CodeOwnersProcessor, + findPrimaryCodeOwner, + findRawCodeOwners, + normalizeCodeOwner, + parseCodeOwners, + resolveCodeOwner, +} from './CodeOwnersProcessor'; + +describe(CodeOwnersProcessor, () => { + const mockLocation = ({ + basePath = '', + type = 'github', + } = {}): LocationSpec => ({ + type, + target: `https://github.com/spotify/backstage/blob/master/${basePath}catalog-info.yaml`, + }); + + const mockReadLocation = (basePath = '') => ({ + type: 'github', + target: `https://github.com/spotify/backstage/blob/master/${basePath}CODEOWNERS`, + }); + + const mockGitUri = (codeOwnersPath: string = '') => { + return { + source: 'github.com', + owner: 'spotify', + name: 'backstage', + codeOwnersPath, + }; + }; + + const mockCodeOwnersText = () => ` +# https://help.github.com/articles/about-codeowners/ +* @spotify/backstage-core @acme/team-foo +/plugins/techdocs @spotify/techdocs-core + `; + + const mockCodeOwners = (): CodeOwnersEntry[] => { + return [ + { + pattern: '/plugins/techdocs', + owners: ['@spotify/techdocs-core'], + }, + { pattern: '*', owners: ['@spotify/backstage-core', '@acme/team-foo'] }, + ]; + }; + + const mockReadResult = ({ + error = undefined, + data = undefined, + }: { + error?: string; + data?: string; + } = {}) => { + if (error) { + throw Error(error); + } + return data; + }; + + describe(buildUrl, () => { + it.each([['azure.com'], ['dev.azure.com']])( + 'should throw not implemented error', + source => { + expect(() => buildUrl({ ...mockGitUri(), source })).toThrow(); + }, + ); + + it('should build github.com url', () => { + expect( + buildUrl({ + ...mockGitUri(), + codeOwnersPath: '/.github/CODEOWNERS', + }), + ).toBe( + 'https://github.com/spotify/backstage/blob/master/.github/CODEOWNERS', + ); + }); + }); + + describe(buildCodeOwnerLocation, () => { + it('should builds a location spec to the codeowners', () => { + expect( + buildCodeOwnerLocation(mockLocation(), '/docs/CODEOWNERS'), + ).toEqual({ + type: 'github', + target: + 'https://github.com/spotify/backstage/blob/master/docs/CODEOWNERS', + }); + }); + + it('should handle nested paths from original location spec', () => { + expect( + buildCodeOwnerLocation( + mockLocation({ basePath: 'packages/foo/' }), + '/CODEOWNERS', + ), + ).toEqual({ + type: 'github', + target: 'https://github.com/spotify/backstage/blob/master/CODEOWNERS', + }); + }); + }); + + describe(parseCodeOwners, () => { + it('should parse the codeowners file', () => { + expect(parseCodeOwners(mockCodeOwnersText())).toEqual(mockCodeOwners()); + }); + }); + + describe(normalizeCodeOwner, () => { + it('should remove org from org/team format', () => { + expect(normalizeCodeOwner('@acme/foo')).toBe('foo'); + }); + + it('should return username from email format', () => { + expect(normalizeCodeOwner('foo@acme.com')).toBe('foo'); + }); + + it.each([['acme/foo'], ['dacme/foo']])( + 'should return string everything else', + owner => { + expect(normalizeCodeOwner(owner)).toBe(owner); + }, + ); + }); + + describe(findPrimaryCodeOwner, () => { + it('should return the primary owner', () => { + expect(findPrimaryCodeOwner(mockCodeOwners())).toBe('backstage-core'); + }); + }); + + describe(findRawCodeOwners, () => { + it('should return found codeowner', async () => { + const ownersText = mockCodeOwnersText(); + const read = jest + .fn() + .mockResolvedValue(mockReadResult({ data: ownersText })); + const result = await findRawCodeOwners(mockLocation(), read); + expect(result).toEqual(ownersText); + }); + + it('should raise error when no codeowner', async () => { + const read = jest.fn().mockRejectedValue(mockReadResult()); + + await expect( + findRawCodeOwners(mockLocation(), read), + ).rejects.toBeInstanceOf(Error); + }); + + it('should look at known codeowner locations', async () => { + const ownersText = mockCodeOwnersText(); + const read = jest + .fn() + .mockImplementationOnce(() => mockReadResult({ error: 'foo' })) + .mockImplementationOnce(() => mockReadResult({ error: 'bar' })) + .mockResolvedValue(mockReadResult({ data: ownersText })); + + const result = await findRawCodeOwners(mockLocation(), read); + + expect(read.mock.calls.length).toBe(3); + expect(read.mock.calls[0]).toEqual([mockReadLocation('.github/')]); + expect(read.mock.calls[1]).toEqual([mockReadLocation('')]); + expect(read.mock.calls[2]).toEqual([mockReadLocation('docs/')]); + expect(result).toEqual(ownersText); + }); + }); + + describe(resolveCodeOwner, () => { + it('should return found codeowner', async () => { + const read = jest + .fn() + .mockResolvedValue(mockReadResult({ data: mockCodeOwnersText() })); + const owner = await resolveCodeOwner(mockLocation(), read); + expect(owner).toBe('backstage-core'); + }); + + it('should raise an error when no codeowner', async () => { + const read = jest + .fn() + .mockImplementation(() => mockReadResult({ error: 'error: foo' })); + + await expect( + resolveCodeOwner(mockLocation(), read), + ).rejects.toBeInstanceOf(Error); + }); + }); + + describe(CodeOwnersProcessor, () => { + const setupTest = ({ kind = 'Component', spec = {} } = {}) => { + const entity = { kind, spec }; + const processor = new CodeOwnersProcessor(); + const read = jest + .fn() + .mockResolvedValue(mockReadResult({ data: mockCodeOwnersText() })); + + return { entity, processor, read }; + }; + + it('should not modify existing owner', async () => { + const { entity, processor } = setupTest({ + spec: { owner: '@acme/foo-team' }, + }); + + const result = await processor.processEntity( + entity as any, + mockLocation(), + null as any, + null as any, + ); + + expect(result).toEqual(entity); + }); + + it('should ignore url locations', async () => { + const { entity, processor } = setupTest(); + + const result = await processor.processEntity( + entity as any, + mockLocation({ type: 'url' }), + null as any, + null as any, + ); + + expect(result).toEqual(entity); + }); + + it('should ignore invalid kinds', async () => { + const { entity, processor } = setupTest({ kind: 'Group' }); + + const result = await processor.processEntity( + entity as any, + mockLocation(), + null as any, + null as any, + ); + + expect(result).toEqual(entity); + }); + + it('should set owner from codeowner', async () => { + const { entity, processor, read } = setupTest(); + + const result = await processor.processEntity( + entity as any, + mockLocation(), + null as any, + read, + ); + + expect(result).toEqual({ + ...entity, + spec: { owner: 'backstage-core' }, + }); + }); + }); +}); diff --git a/plugins/catalog-backend/src/ingestion/processors/CodeOwnersProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/CodeOwnersProcessor.ts new file mode 100644 index 0000000000..c875bdc799 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/CodeOwnersProcessor.ts @@ -0,0 +1,162 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entity, LocationSpec } from '@backstage/catalog-model'; +import { + LocationProcessor, + LocationProcessorEmit, + LocationProcessorRead, +} from './types'; +import * as codeowners from 'codeowners-utils'; +import { CodeOwnersEntry } from 'codeowners-utils'; +import parseGitUri from 'git-url-parse'; +import { filter, head, get, pipe, reverse } from 'lodash/fp'; + +// NOTE: This can be removed when ES2021 is implemented +import 'core-js/features/promise'; + +const ALLOWED_LOCATION_TYPES = [ + 'azure/api', + 'bitbucket/api', + 'github', + 'github/api', + 'gitlab', + 'gitlab/api', +]; + +export class CodeOwnersProcessor implements LocationProcessor { + async processEntity( + entity: Entity, + location: LocationSpec, + _emit: LocationProcessorEmit, + read: LocationProcessorRead, + ): Promise { + // Only continue if the owner is not set + if ( + !entity || + !['Component', 'API'].includes(entity.kind) || + !ALLOWED_LOCATION_TYPES.includes(location.type) || + (entity.spec && entity.spec.owner) + ) { + return entity; + } + + const owner = await resolveCodeOwner(location, read); + + return { + ...entity, + spec: { ...entity.spec, owner }, + }; + } +} + +export async function resolveCodeOwner( + location: LocationSpec, + read: LocationProcessorRead, +): Promise { + const ownersText = await findRawCodeOwners(location, read); + + if (!ownersText) { + throw Error(`Unable to find codeowners file for: ${location.target}`); + } + + const owners = parseCodeOwners(ownersText); + + return findPrimaryCodeOwner(owners); +} + +export async function findRawCodeOwners( + location: LocationSpec, + read: LocationProcessorRead, +): Promise { + const readOwnerLocation = async (basePath: string): Promise => { + const ownerLocation = buildCodeOwnerLocation( + location, + `${basePath}/CODEOWNERS`, + ); + + const data = await read(ownerLocation); + return data.toString(); + }; + + const gitProvider = location.type.split('/')[0]; + + return Promise.any([ + readOwnerLocation(`/.${gitProvider}`), + readOwnerLocation(''), + readOwnerLocation('/docs'), + ]); +} + +export function parseCodeOwners(ownersText: string) { + return codeowners.parse(ownersText); +} + +export function findPrimaryCodeOwner( + owners: CodeOwnersEntry[], +): string | undefined { + return pipe( + filter((e: CodeOwnersEntry) => e.pattern === '*'), + reverse, + head, + get('owners'), + head, + normalizeCodeOwner, + )(owners); +} + +export function normalizeCodeOwner(owner: string) { + if (owner.match(/^@.*\/.*/)) { + return owner.split('/')[1]; + } else if (owner.match(/^.*@.*\..*$/)) { + return owner.split('@')[0]; + } + + return owner; +} + +export function buildCodeOwnerLocation( + location: LocationSpec, + codeOwnersPath: string, +): LocationSpec { + const { type, target } = location; + + return { type, target: buildUrl({ ...parseGitUri(target), codeOwnersPath }) }; +} + +export function buildUrl({ + protocol = 'https', + source = 'github.com', + owner, + name, + ref = 'master', + codeOwnersPath = '/CODEOWNERS', +}: { + protocol?: string; + source?: string; + owner: string; + name: string; + ref?: string; + codeOwnersPath?: string; +}) { + switch (source) { + case 'dev.azure.com': + case 'azure.com': + throw Error('Azure codeowner url builder not implemented'); + default: + return `${protocol}://${source}/${owner}/${name}/blob/${ref}${codeOwnersPath}`; + } +} diff --git a/plugins/catalog-backend/src/ingestion/processors/EntityPolicyProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/EntityPolicyProcessor.ts index 7360a01a84..67da9a6705 100644 --- a/plugins/catalog-backend/src/ingestion/processors/EntityPolicyProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/EntityPolicyProcessor.ts @@ -25,6 +25,10 @@ export class EntityPolicyProcessor implements LocationProcessor { } async processEntity(entity: Entity): Promise { - return await this.policy.enforce(entity); + const output = await this.policy.enforce(entity); + if (!output) { + throw new Error(`Entity did not match any known schema`); + } + return output; } } diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.test.ts new file mode 100644 index 0000000000..e0d35f78aa --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.test.ts @@ -0,0 +1,124 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LocationSpec } from '@backstage/catalog-model'; +import { ConfigReader } from '@backstage/config'; +import { + GithubOrgReaderProcessor, + parseUrl, + readConfig, +} from './GithubOrgReaderProcessor'; + +describe('GithubOrgReaderProcessor', () => { + describe('readConfig', () => { + function config( + providers: { target: string; apiBaseUrl?: string; token?: string }[], + ) { + return ConfigReader.fromConfigs([ + { + context: '', + data: { + catalog: { processors: { githubOrg: { providers } } }, + }, + }, + ]); + } + + it('adds a default GitHub entry when missing', () => { + const output = readConfig(config([])); + expect(output).toEqual([ + { + target: 'https://github.com', + apiBaseUrl: 'https://api.github.com', + }, + ]); + }); + + it('injects the correct GitHub API base URL when missing', () => { + const output = readConfig(config([{ target: 'https://github.com' }])); + expect(output).toEqual([ + { + target: 'https://github.com', + apiBaseUrl: 'https://api.github.com', + }, + ]); + }); + + it('rejects custom targets with no base URLs', () => { + expect(() => + readConfig(config([{ target: 'https://ghe.company.com' }])), + ).toThrow( + 'Provider at https://ghe.company.com must configure an explicit apiBaseUrl', + ); + }); + + it('rejects funky configs', () => { + expect(() => readConfig(config([{ target: 7 } as any]))).toThrow( + /target/, + ); + expect(() => readConfig(config([{ noTarget: '7' } as any]))).toThrow( + /target/, + ); + expect(() => + readConfig( + config([{ target: 'https://github.com', apiBaseUrl: 7 } as any]), + ), + ).toThrow(/apiBaseUrl/); + expect(() => + readConfig(config([{ target: 'https://github.com', token: 7 } as any])), + ).toThrow(/token/); + }); + }); + + describe('parseUrl', () => { + it('only supports clean org urls, and decodes them', () => { + expect(() => parseUrl('https://github.com')).toThrow(); + expect(() => parseUrl('https://github.com/org/foo')).toThrow(); + expect(() => parseUrl('https://github.com/org/foo/teams')).toThrow(); + expect(parseUrl('https://github.com/foo%32')).toEqual({ org: 'foo2' }); + }); + }); + + describe('implementation', () => { + it('rejects unknown types', async () => { + const processor = new GithubOrgReaderProcessor([ + { target: 'https://github.com', apiBaseUrl: 'https://api.github.com' }, + ]); + const location: LocationSpec = { + type: 'not-github-org', + target: 'https://github.com', + }; + await expect( + processor.readLocation(location, false, () => {}), + ).resolves.toBeFalsy(); + }); + + it('rejects unknown targets', async () => { + const processor = new GithubOrgReaderProcessor([ + { target: 'https://github.com', apiBaseUrl: 'https://api.github.com' }, + ]); + const location: LocationSpec = { + type: 'github-org', + target: 'https://not.github.com/apa', + }; + await expect( + processor.readLocation(location, false, () => {}), + ).rejects.toThrow( + /There is no GitHub Org provider that matches https:\/\/not.github.com\/apa/, + ); + }); + }); +}); diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts new file mode 100644 index 0000000000..5084d4c16f --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/GithubOrgReaderProcessor.ts @@ -0,0 +1,160 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { LocationSpec } from '@backstage/catalog-model'; +import { Config } from '@backstage/config'; +import { graphql } from '@octokit/graphql'; +import * as results from './results'; +import { LocationProcessor, LocationProcessorEmit } from './types'; +import { getOrganizationTeams, getOrganizationUsers } from './util/github'; +import { buildOrgHierarchy } from './util/org'; + +/** + * Extracts teams and users out of a GitHub org. + */ +export class GithubOrgReaderProcessor implements LocationProcessor { + static fromConfig(config: Config) { + return new GithubOrgReaderProcessor(readConfig(config)); + } + + constructor(private readonly providers: ProviderConfig[]) {} + + async readLocation( + location: LocationSpec, + _optional: boolean, + emit: LocationProcessorEmit, + ): Promise { + if (location.type !== 'github-org') { + return false; + } + + const provider = this.providers.find(p => + location.target.startsWith(`${p.target}/`), + ); + if (!provider) { + throw new Error( + `There is no GitHub Org provider that matches ${location.target}. Please add a configuration entry for it under catalog.processors.githubOrg.providers.`, + ); + } + + const { org } = parseUrl(location.target); + const client = !provider.token + ? graphql + : graphql.defaults({ + headers: { + authorization: `token ${provider.token}`, + }, + }); + + const { users } = await getOrganizationUsers(client, org); + const { groups, groupMemberUsers } = await getOrganizationTeams( + client, + org, + ); + buildOrgHierarchy(groups, users, groupMemberUsers); + + for (const group of groups) { + emit(results.entity(location, group)); + } + for (const user of users) { + emit(results.entity(location, user)); + } + + return true; + } +} + +/* + * Helpers + */ + +/** + * The configuration parameters for a single GitHub API provider. + */ +type ProviderConfig = { + /** + * The prefix of the target that this matches on, e.g. "https://github.com", + * with no trailing slash. + */ + target: string; + + /** + * The base URL of the API of this provider, e.g. "https://api.github.com", + * with no trailing slash. + * + * May be omitted specifically for GitHub; then it will be deduced. + */ + apiBaseUrl?: string; + + /** + * The authorization token to use for requests to this provider. + * + * If no token is specified, anonymous access is used. + */ + token?: string; +}; + +// TODO(freben): Break out common code and config from here and GithubReaderProcessor +export function readConfig(config: Config): ProviderConfig[] { + const providers: ProviderConfig[] = []; + + const providerConfigs = + config.getOptionalConfigArray('catalog.processors.githubOrg.providers') ?? + []; + + // First read all the explicit providers + for (const providerConfig of providerConfigs) { + const target = providerConfig.getString('target').replace(/\/+$/, ''); + let apiBaseUrl = providerConfig.getOptionalString('apiBaseUrl'); + const token = providerConfig.getOptionalString('token'); + + if (apiBaseUrl) { + apiBaseUrl = apiBaseUrl.replace(/\/+$/, ''); + } else if (target === 'https://github.com') { + apiBaseUrl = 'https://api.github.com'; + } + + if (!apiBaseUrl) { + throw new Error( + `Provider at ${target} must configure an explicit apiBaseUrl`, + ); + } + + providers.push({ target, apiBaseUrl, token }); + } + + // If no explicit github.com provider was added, put one in the list as + // a convenience + if (!providers.some(p => p.target === 'https://github.com')) { + providers.push({ + target: 'https://github.com', + apiBaseUrl: 'https://api.github.com', + }); + } + + return providers; +} + +export function parseUrl(urlString: string): { org: string } { + const path = new URL(urlString).pathname.substr(1).split('/'); + + // /spotify + if (path.length === 1 && path[0].length) { + return { org: decodeURIComponent(path[0]) }; + } + + throw new Error(`Expected a URL pointing to /`); +} diff --git a/plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.ts index 4f0c66148f..89d1f69860 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GithubReaderProcessor.ts @@ -22,6 +22,11 @@ import { Logger } from 'winston'; import * as result from './results'; import { LocationProcessor, LocationProcessorEmit } from './types'; +// *********************************************************************** +// * NOTE: This has been replaced by packages/backend-common/src/reading * +// * Don't implement new functionality here as this file will be removed * +// *********************************************************************** + /** * The configuration parameters for a single GitHub API provider. */ @@ -99,8 +104,7 @@ export function getApiUrl(target: string, provider: ProviderConfig): URL { !owner || !name || !ref || - (filepathtype !== 'blob' && filepathtype !== 'raw') || - !filepath?.match(/\.ya?ml$/) + (filepathtype !== 'blob' && filepathtype !== 'raw') ) { throw new Error('Wrong URL or invalid file path'); } @@ -125,8 +129,7 @@ export function getRawUrl(target: string, provider: ProviderConfig): URL { !owner || !name || !ref || - (filepathtype !== 'blob' && filepathtype !== 'raw') || - !filepath?.match(/\.ya?ml$/) + (filepathtype !== 'blob' && filepathtype !== 'raw') ) { throw new Error('Wrong URL or invalid file path'); } diff --git a/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.test.ts deleted file mode 100644 index 48ed270049..0000000000 --- a/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { GitlabApiReaderProcessor } from './GitlabApiReaderProcessor'; -import { ConfigReader } from '@backstage/config'; - -describe('GitlabApiReaderProcessor', () => { - const createConfig = (token: string | undefined) => - ConfigReader.fromConfigs([ - { - context: '', - data: { - catalog: { - processors: { - gitlabApi: { - privateToken: token, - }, - }, - }, - }, - }, - ]); - - it('should build raw api', () => { - const processor = new GitlabApiReaderProcessor(createConfig(undefined)); - - const tests = [ - { - target: - 'https://gitlab.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', - url: new URL( - 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', - ), - err: undefined, - }, - { - target: - 'https://gitlab.example.com/groupA/teams/teamA/subgroupA/repoA/-/blob/branch/my/path/to/file.yaml', - url: new URL( - 'https://gitlab.example.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', - ), - err: undefined, - }, - { - target: - 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path/to/file.yaml', // Repo not in subgroup - url: new URL( - 'https://gitlab.com/api/v4/projects/12345/repository/files/my%2Fpath%2Fto%2Ffile.yaml/raw?ref=branch', - ), - err: undefined, - }, - { - target: - 'https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path/', - url: null, - err: - 'Incorrect url: https://gitlab.com/groupA/teams/teamA/repoA/-/blob/branch/my/path/, Error: GitLab url does not end in .ya?ml', - }, - ]; - - for (const test of tests) { - if (test.err) { - expect(() => processor.buildRawUrl(test.target, 12345)).toThrowError( - test.err, - ); - } else if (test.url) { - expect(processor.buildRawUrl(test.target, 12345).toString()).toEqual( - test.url.toString(), - ); - } else { - throw new Error( - 'This should not have happened. Either err or url should have matched.', - ); - } - } - }); - - it('should return request options', () => { - const tests = [ - { - token: '0123456789', - expect: { - headers: { - 'PRIVATE-TOKEN': '0123456789', - }, - }, - }, - { - token: '', - err: - "Invalid type in config for key 'catalog.processors.gitlabApi.privateToken' in '', got empty-string, wanted string", - expect: { - headers: { - 'PRIVATE-TOKEN': '', - }, - }, - }, - { - token: undefined, - expect: { - headers: { - 'PRIVATE-TOKEN': '', - }, - }, - }, - ]; - - for (const test of tests) { - if (test.err) { - expect( - () => new GitlabApiReaderProcessor(createConfig(test.token)), - ).toThrowError(test.err); - } else { - const processor = new GitlabApiReaderProcessor( - createConfig(test.token), - ); - expect(processor.getRequestOptions()).toEqual(test.expect); - } - } - }); -}); diff --git a/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.ts index 067edba3d9..aeba7a7ebe 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GitlabApiReaderProcessor.ts @@ -20,6 +20,11 @@ import * as result from './results'; import { LocationProcessor, LocationProcessorEmit } from './types'; import { Config } from '@backstage/config'; +// *********************************************************************** +// * NOTE: This has been replaced by packages/backend-common/src/reading * +// * Don't implement new functionality here as this file will be removed * +// *********************************************************************** + export class GitlabApiReaderProcessor implements LocationProcessor { private privateToken: string; @@ -83,10 +88,6 @@ export class GitlabApiReaderProcessor implements LocationProcessor { const branchAndfilePath = url.pathname.split('/-/blob/')[1]; - if (!branchAndfilePath.match(/\.ya?ml$/)) { - throw new Error('GitLab url does not end in .ya?ml'); - } - const [branch, ...filePath] = branchAndfilePath.split('/'); url.pathname = [ diff --git a/plugins/catalog-backend/src/ingestion/processors/GitlabReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/GitlabReaderProcessor.ts index 9f308ee184..b51bf85a8e 100644 --- a/plugins/catalog-backend/src/ingestion/processors/GitlabReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/GitlabReaderProcessor.ts @@ -19,6 +19,11 @@ import fetch from 'node-fetch'; import * as result from './results'; import { LocationProcessor, LocationProcessorEmit } from './types'; +// *********************************************************************** +// * NOTE: This has been replaced by packages/backend-common/src/reading * +// * Don't implement new functionality here as this file will be removed * +// *********************************************************************** + export class GitlabReaderProcessor implements LocationProcessor { async readLocation( location: LocationSpec, @@ -62,19 +67,15 @@ export class GitlabReaderProcessor implements LocationProcessor { try { const url = new URL(target); - const [ - empty, - userOrOrg, - repoName, - blobKeyword, - ...restOfPath - ] = url.pathname.split('/'); + const [empty, userOrOrg, repoName, , ...restOfPath] = url.pathname + .split('/') + // for the common case https://gitlab.example.com/a/b/-/blob/master/c.yaml + .filter(path => path !== '-'); if ( empty !== '' || userOrOrg === '' || repoName === '' || - blobKeyword !== 'blob' || !restOfPath.join('/').match(/\.yaml$/) ) { throw new Error('Wrong GitLab URL'); diff --git a/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.test.ts new file mode 100644 index 0000000000..6893cae0e7 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.test.ts @@ -0,0 +1,421 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entity } from '@backstage/catalog-model'; +import { + jsonPlaceholderResolver, + PlaceholderProcessor, + PlaceholderResolver, + ResolverParams, + yamlPlaceholderResolver, +} from './PlaceholderProcessor'; +import { LocationProcessorEmit, LocationProcessorRead } from './types'; + +describe('PlaceholderProcessor', () => { + const emit: LocationProcessorEmit = jest.fn(); + const read: jest.MockedFunction = jest.fn(); + + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('returns placeholder-free data unchanged', async () => { + const input: Entity = { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + }; + const processor = new PlaceholderProcessor({ + foo: async () => 'replaced', + }); + await expect( + processor.processEntity(input, { type: 't', target: 'l' }, emit, read), + ).resolves.toBe(input); + }); + + it('replaces placeholders deep in the data', async () => { + const upperResolver: PlaceholderResolver = jest.fn(async ({ value }) => + value!.toString().toUpperCase(), + ); + const processor = new PlaceholderProcessor({ + upper: upperResolver, + }); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { a: [{ b: { $upper: 'text' } }] }, + }, + { type: 'fake', target: 'http://example.com' }, + emit, + read, + ), + ).resolves.toEqual({ + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { a: [{ b: 'TEXT' }] }, + }); + + expect(emit).not.toBeCalled(); + expect(read).not.toBeCalled(); + expect(upperResolver).toBeCalledWith({ + key: 'upper', + value: 'text', + location: { type: 'fake', target: 'http://example.com' }, + read, + }); + }); + + it('rejects multiple placeholders', async () => { + const processor = new PlaceholderProcessor({ + foo: jest.fn(), + bar: jest.fn(), + }); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n', x: { $foo: 'a', $bar: 'b' } }, + }, + { type: 'a', target: 'b' }, + emit, + read, + ), + ).rejects.toThrow( + 'Placeholders have to be on the form of a single $-prefixed key in an object', + ); + + expect(emit).not.toBeCalled(); + expect(read).not.toBeCalled(); + }); + + it('rejects unknown placeholders', async () => { + const processor = new PlaceholderProcessor({ + bar: jest.fn(), + }); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n', x: { $foo: 'a' } }, + }, + { type: 'a', target: 'b' }, + emit, + read, + ), + ).rejects.toThrow('Encountered unknown placeholder $foo'); + + expect(emit).not.toBeCalled(); + expect(read).not.toBeCalled(); + }); + + it('has builtin text support', async () => { + read.mockResolvedValue(Buffer.from('TEXT', 'utf-8')); + const processor = PlaceholderProcessor.default(); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: { $text: '../file.txt' } }, + }, + { + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/catalog-info.yaml', + }, + emit, + read, + ), + ).resolves.toEqual({ + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: 'TEXT' }, + }); + + expect(emit).not.toBeCalled(); + expect(read).toBeCalledWith({ + type: 'github', + target: 'https://github.com/spotify/backstage/a/file.txt', + }); + }); + + it('has builtin json support', async () => { + read.mockResolvedValue( + Buffer.from(JSON.stringify({ a: ['b', 7] }), 'utf-8'), + ); + const processor = PlaceholderProcessor.default(); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: { $json: './file.json' } }, + }, + { + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/catalog-info.yaml', + }, + emit, + read, + ), + ).resolves.toEqual({ + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: { a: ['b', 7] } }, + }); + + expect(emit).not.toBeCalled(); + expect(read).toBeCalledWith({ + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/file.json', + }); + }); + + it('has builtin yaml support', async () => { + read.mockResolvedValue(Buffer.from('foo:\n - bar: 7', 'utf-8')); + const processor = PlaceholderProcessor.default(); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: { $yaml: '../file.yaml' } }, + }, + { + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/catalog-info.yaml', + }, + emit, + read, + ), + ).resolves.toEqual({ + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: { foo: [{ bar: 7 }] } }, + }); + + expect(emit).not.toBeCalled(); + expect(read).toBeCalledWith({ + type: 'github', + target: 'https://github.com/spotify/backstage/a/file.yaml', + }); + }); + + it('resolves absolute path for absolute location', async () => { + read.mockResolvedValue(Buffer.from('TEXT', 'utf-8')); + const processor = PlaceholderProcessor.default(); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { + data: { + $text: 'https://github.com/spotify/backstage/catalog-info.yaml', + }, + }, + }, + { + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/catalog-info.yaml', + }, + emit, + read, + ), + ).resolves.toEqual({ + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: 'TEXT' }, + }); + + expect(emit).not.toBeCalled(); + expect(read).toBeCalledWith({ + type: 'github', + target: 'https://github.com/spotify/backstage/catalog-info.yaml', + }); + }); + + it('resolves absolute path for relative file location', async () => { + read.mockResolvedValue(Buffer.from('TEXT', 'utf-8')); + const processor = PlaceholderProcessor.default(); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { + data: { + $text: 'https://github.com/spotify/backstage/catalog-info.yaml', + }, + }, + }, + { + type: 'github', + target: './a/b/catalog-info.yaml', + }, + emit, + read, + ), + ).resolves.toEqual({ + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { data: 'TEXT' }, + }); + + expect(emit).not.toBeCalled(); + expect(read).toBeCalledWith({ + type: 'github', + target: 'https://github.com/spotify/backstage/catalog-info.yaml', + }); + }); + + it('not resolves relative file path for relative file location', async () => { + // We explicitly don't support this case, as it would allow for file system + // traversel attacks. If we want to implement this, we need to have additional + // security measures in place! + read.mockResolvedValue(Buffer.from('TEXT', 'utf-8')); + const processor = PlaceholderProcessor.default(); + + await expect( + processor.processEntity( + { + apiVersion: 'a', + kind: 'k', + metadata: { name: 'n' }, + spec: { + data: { + $text: '../c/catalog-info.yaml', + }, + }, + }, + { + type: 'github', + target: './a/b/catalog-info.yaml', + }, + emit, + read, + ), + ).rejects.toThrow( + 'Placeholder $text could not form an URL out of ./a/b/catalog-info.yaml and ../c/catalog-info.yaml', + ); + + expect(emit).not.toBeCalled(); + expect(read).not.toBeCalled(); + }); +}); + +describe('yamlPlaceholderResolver', () => { + const read: jest.MockedFunction = jest.fn(); + const params: ResolverParams = { + key: 'a', + value: './file.yaml', + location: { + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/catalog-info.yaml', + }, + read, + }; + + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('parses valid yaml', async () => { + read.mockResolvedValue(Buffer.from('foo:\n - bar: 7', 'utf-8')); + await expect(yamlPlaceholderResolver(params)).resolves.toEqual({ + foo: [{ bar: 7 }], + }); + }); + + it('rejects invalid yaml', async () => { + read.mockResolvedValue(Buffer.from('a: 1\n----\n', 'utf-8')); + await expect(yamlPlaceholderResolver(params)).rejects.toThrow( + 'Placeholder $a found an error in the data at ./file.yaml, YAMLSemanticError: Implicit map keys need to be followed by map values', + ); + }); + + it('rejects multi-document yaml', async () => { + read.mockResolvedValue(Buffer.from('foo: 1\n---\nbar: 2\n', 'utf-8')); + await expect(yamlPlaceholderResolver(params)).rejects.toThrow( + 'Placeholder $a expected to find exactly one document of data at ./file.yaml, found 2', + ); + }); + + it('parses valid json', async () => { + read.mockResolvedValue( + Buffer.from(JSON.stringify({ a: ['b', 7] }), 'utf-8'), + ); + await expect(yamlPlaceholderResolver(params)).resolves.toEqual({ + a: ['b', 7], + }); + }); +}); + +describe('jsonPlaceholderResolver', () => { + const read: jest.MockedFunction = jest.fn(); + const params: ResolverParams = { + key: 'a', + value: './file.json', + location: { + type: 'github', + target: 'https://github.com/spotify/backstage/a/b/catalog-info.yaml', + }, + read, + }; + + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('parses valid json', async () => { + read.mockResolvedValue( + Buffer.from(JSON.stringify({ a: ['b', 7] }), 'utf-8'), + ); + await expect(jsonPlaceholderResolver(params)).resolves.toEqual({ + a: ['b', 7], + }); + }); + + it('rejects invalid json', async () => { + read.mockResolvedValue(Buffer.from('}', 'utf-8')); + await expect(jsonPlaceholderResolver(params)).rejects.toThrow( + 'Placeholder $a failed to parse JSON data at ./file.json, SyntaxError: Unexpected token } in JSON at position 0', + ); + }); +}); diff --git a/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.ts new file mode 100644 index 0000000000..b811d217d5 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.ts @@ -0,0 +1,220 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entity, LocationSpec } from '@backstage/catalog-model'; +import { JsonValue } from '@backstage/config'; +import yaml from 'yaml'; +import { + LocationProcessor, + LocationProcessorEmit, + LocationProcessorRead, +} from './types'; + +export type ResolverParams = { + key: string; + value: JsonValue; + location: LocationSpec; + read: LocationProcessorRead; +}; + +export type PlaceholderResolver = ( + params: ResolverParams, +) => Promise; + +/** + * Traverses raw entity JSON looking for occurrences of $-prefixed placeholders + * that it then fills in with actual data. + */ +export class PlaceholderProcessor implements LocationProcessor { + static default() { + return new PlaceholderProcessor({ + json: jsonPlaceholderResolver, + yaml: yamlPlaceholderResolver, + text: textPlaceholderResolver, + }); + } + + constructor( + private readonly resolvers: Record, + ) {} + + async processEntity( + entity: Entity, + location: LocationSpec, + _emit: LocationProcessorEmit, + read: LocationProcessorRead, + ): Promise { + const process = async (data: any): Promise<[any, boolean]> => { + if (!data || !(data instanceof Object)) { + // Scalars can't have placeholders + return [data, false]; + } + + if (Array.isArray(data)) { + // We're an array - process all entries recursively + const items = await Promise.all(data.map(item => process(item))); + return items.every(([, changed]) => !changed) + ? [data, false] + : [items.map(([item]) => item), true]; + } + + const keys = Object.keys(data); + if (!keys.some(k => k.startsWith('$'))) { + // We're an object but no placeholders at this level - process all + // entries recursively + const entries = await Promise.all( + Object.entries(data).map(([k, v]) => + process(v).then(vp => [k, vp] as const), + ), + ); + return entries.every(([, [, changed]]) => !changed) + ? [data, false] + : [Object.fromEntries(entries.map(([k, [v]]) => [k, v])), true]; + } else if (keys.length !== 1) { + throw new Error( + 'Placeholders have to be on the form of a single $-prefixed key in an object', + ); + } + + const resolverKey = keys[0].substr(1); + const resolver = this.resolvers[resolverKey]; + if (!resolver) { + throw new Error(`Encountered unknown placeholder \$${resolverKey}`); + } + + return [ + await resolver({ + key: resolverKey, + value: data[keys[0]], + location, + read, + }), + true, + ]; + }; + + const [result] = await process(entity); + return result; + } +} + +/* + * Resolvers + */ + +export async function yamlPlaceholderResolver( + params: ResolverParams, +): Promise { + const text = await readTextLocation(params); + + let documents: yaml.Document.Parsed[]; + try { + documents = yaml.parseAllDocuments(text).filter(d => d); + } catch (e) { + throw new Error( + `Placeholder \$${params.key} failed to parse YAML data at ${params.value}, ${e}`, + ); + } + + if (documents.length !== 1) { + throw new Error( + `Placeholder \$${params.key} expected to find exactly one document of data at ${params.value}, found ${documents.length}`, + ); + } + + const document = documents[0]; + + if (document.errors?.length) { + throw new Error( + `Placeholder \$${params.key} found an error in the data at ${params.value}, ${document.errors[0]}`, + ); + } + + return document.toJSON(); +} + +export async function jsonPlaceholderResolver( + params: ResolverParams, +): Promise { + const text = await readTextLocation(params); + + try { + return JSON.parse(text); + } catch (e) { + throw new Error( + `Placeholder \$${params.key} failed to parse JSON data at ${params.value}, ${e}`, + ); + } +} + +export async function textPlaceholderResolver( + params: ResolverParams, +): Promise { + return await readTextLocation(params); +} + +/* + * Helpers + */ + +async function readTextLocation(params: ResolverParams): Promise { + const newLocation = relativeLocation(params); + + try { + const data = await params.read(newLocation); + return data.toString('utf-8'); + } catch (e) { + throw new Error( + `Placeholder \$${params.key} could not read location ${params.value}, ${e}`, + ); + } +} + +function relativeLocation({ + key, + value, + location, +}: ResolverParams): LocationSpec { + if (typeof value !== 'string') { + throw new Error( + `Placeholder \$${key} expected a string value parameter, in the form of an absolute URL or a relative path`, + ); + } + + let url: URL; + try { + // The two-value form of the URL constructor handles relative paths for us + url = new URL(value, location.target); + } catch { + try { + // Check whether value is a valid absolute URL on it's own, if not fail. + url = new URL(value); + } catch { + // The only remaining case that isn't support is a relative file path that should be + // resolved using a relative file location. Accessing local file paths can lead to + // path traversal attacks and access to any file on the host system. Implementing this + // would require additional security measures. + throw new Error( + `Placeholder \$${key} could not form an URL out of ${location.target} and ${value}`, + ); + } + } + + return { + type: location.type, + target: url.toString(), + }; +} diff --git a/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.test.ts index e30b320bf4..009872cda3 100644 --- a/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.test.ts +++ b/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.test.ts @@ -22,17 +22,21 @@ import { } from './types'; import { setupServer } from 'msw/node'; import { rest } from 'msw'; +import { getVoidLogger, UrlReaders } from '@backstage/backend-common'; +import { ConfigReader } from '@backstage/config'; describe('UrlReaderProcessor', () => { const mockApiOrigin = 'http://localhost:23000'; const server = setupServer(); - beforeAll(() => server.listen()); + beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); it('should load from url', async () => { - const processor = new UrlReaderProcessor(); + const logger = getVoidLogger(); + const reader = UrlReaders.default({ logger, config: new ConfigReader({}) }); + const processor = new UrlReaderProcessor({ reader, logger }); const spec = { type: 'url', target: `${mockApiOrigin}/component.yaml`, @@ -54,7 +58,9 @@ describe('UrlReaderProcessor', () => { }); it('should fail load from url with error', async () => { - const processor = new UrlReaderProcessor(); + const logger = getVoidLogger(); + const reader = UrlReaders.default({ logger, config: new ConfigReader({}) }); + const processor = new UrlReaderProcessor({ reader, logger }); const spec = { type: 'url', target: `${mockApiOrigin}/component-notfound.yaml`, @@ -74,7 +80,7 @@ describe('UrlReaderProcessor', () => { expect(generated.location).toBe(spec); expect(generated.error.name).toBe('NotFoundError'); expect(generated.error.message).toBe( - `${mockApiOrigin}/component-notfound.yaml could not be read, 404 Not Found`, + `Unable to read url, NotFoundError: could not read ${mockApiOrigin}/component-notfound.yaml, 404 Not Found`, ); }); }); diff --git a/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.ts b/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.ts index 0c879ea70c..2bc05bf1cb 100644 --- a/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.ts +++ b/plugins/catalog-backend/src/ingestion/processors/UrlReaderProcessor.ts @@ -14,40 +14,58 @@ * limitations under the License. */ +import { Logger } from 'winston'; +import { UrlReader } from '@backstage/backend-common'; import { LocationSpec } from '@backstage/catalog-model'; -import fetch from 'node-fetch'; import * as result from './results'; import { LocationProcessor, LocationProcessorEmit } from './types'; +// TODO(Rugvip): Added for backwards compatibility when moving to UrlReader, this +// can be removed in a bit +const deprecatedTypes = [ + 'github', + 'github/api', + 'bitbucket/api', + 'gitlab/api', + 'azure/api', +]; + +type Options = { + reader: UrlReader; + logger: Logger; +}; + export class UrlReaderProcessor implements LocationProcessor { + constructor(private readonly options: Options) {} + async readLocation( location: LocationSpec, optional: boolean, emit: LocationProcessorEmit, ): Promise { - if (location.type !== 'url') { + if (deprecatedTypes.includes(location.type)) { + // TODO(Rugvip): Let's not enable this warning yet, as we want to move over the example YAMLs + // in this repo to use the 'url' type first. + // this.options.logger.warn( + // `Using deprecated location type '${location.type}' for '${location.target}', use 'url' instead`, + // ); + } else if (location.type !== 'url') { return false; } try { - const response = await fetch(location.target); + const data = await this.options.reader.read(location.target); + emit(result.data(location, data)); + } catch (error) { + const message = `Unable to read ${location.type}, ${error}`; - if (response.ok) { - const data = await response.buffer(); - emit(result.data(location, data)); - } else { - const message = `${location.target} could not be read, ${response.status} ${response.statusText}`; - if (response.status === 404) { - if (!optional) { - emit(result.notFoundError(location, message)); - } - } else { - emit(result.generalError(location, message)); + if (error.name === 'NotFoundError') { + if (!optional) { + emit(result.notFoundError(location, message)); } + } else { + emit(result.generalError(location, message)); } - } catch (e) { - const message = `Unable to read ${location.type} ${location.target}, ${e}`; - emit(result.generalError(location, message)); } return true; diff --git a/plugins/catalog-backend/src/ingestion/processors/index.ts b/plugins/catalog-backend/src/ingestion/processors/index.ts index ed5dc3bf8e..0ce7f11a5f 100644 --- a/plugins/catalog-backend/src/ingestion/processors/index.ts +++ b/plugins/catalog-backend/src/ingestion/processors/index.ts @@ -18,3 +18,20 @@ import * as results from './results'; export { results }; export * from './types'; + +export { AnnotateLocationEntityProcessor } from './AnnotateLocationEntityProcessor'; +export { ApiDefinitionAtLocationProcessor } from './ApiDefinitionAtLocationProcessor'; +export { AzureApiReaderProcessor } from './AzureApiReaderProcessor'; +export { BitbucketApiReaderProcessor } from './BitbucketApiReaderProcessor'; +export { CodeOwnersProcessor } from './CodeOwnersProcessor'; +export { EntityPolicyProcessor } from './EntityPolicyProcessor'; +export { FileReaderProcessor } from './FileReaderProcessor'; +export { GithubOrgReaderProcessor } from './GithubOrgReaderProcessor'; +export { GithubReaderProcessor } from './GithubReaderProcessor'; +export { GitlabApiReaderProcessor } from './GitlabApiReaderProcessor'; +export { GitlabReaderProcessor } from './GitlabReaderProcessor'; +export { LocationRefProcessor } from './LocationEntityProcessor'; +export { PlaceholderProcessor } from './PlaceholderProcessor'; +export { StaticLocationProcessor } from './StaticLocationProcessor'; +export { UrlReaderProcessor } from './UrlReaderProcessor'; +export { YamlProcessor } from './YamlProcessor'; diff --git a/plugins/catalog-backend/src/ingestion/processors/types.ts b/plugins/catalog-backend/src/ingestion/processors/types.ts index c8f3f6f482..66359b328b 100644 --- a/plugins/catalog-backend/src/ingestion/processors/types.ts +++ b/plugins/catalog-backend/src/ingestion/processors/types.ts @@ -50,13 +50,15 @@ export type LocationProcessor = { * * @param entity The entity to process * @param location The location that the entity came from + * @param read Reads the contents of a location * @param emit A sink for auxiliary items resulting from the processing - * @returns The same entity or a modifid version of it + * @returns The same entity or a modified version of it */ processEntity?( entity: Entity, location: LocationSpec, emit: LocationProcessorEmit, + read: LocationProcessorRead, ): Promise; /** @@ -64,7 +66,7 @@ export type LocationProcessor = { * * @param error The error * @param location The location where the error occurred - * @param emit A sink for items resulting from this handilng + * @param emit A sink for items resulting from this handling * @returns Nothing */ handleError?( @@ -107,3 +109,5 @@ export type LocationProcessorResult = | LocationProcessorDataResult | LocationProcessorEntityResult | LocationProcessorErrorResult; + +export type LocationProcessorRead = (location: LocationSpec) => Promise; diff --git a/plugins/catalog-backend/src/ingestion/processors/util/github.test.ts b/plugins/catalog-backend/src/ingestion/processors/util/github.test.ts new file mode 100644 index 0000000000..25a37e0546 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/util/github.test.ts @@ -0,0 +1,147 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { graphql } from '@octokit/graphql'; +import { graphql as graphqlMsw } from 'msw'; +import { setupServer } from 'msw/node'; +import { + getOrganizationTeams, + getOrganizationUsers, + getTeamMembers, + QueryResponse, +} from './github'; + +describe('github', () => { + const server = setupServer(); + beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); + afterEach(() => server.resetHandlers()); + afterAll(() => server.close()); + + describe('getOrganizationUsers', () => { + it('reads members', async () => { + const input: QueryResponse = { + organization: { + membersWithRole: { + pageInfo: { hasNextPage: false }, + nodes: [ + { + login: 'a', + name: 'b', + bio: 'c', + email: 'd', + avatarUrl: 'e', + }, + ], + }, + }, + }; + + const output = { + users: [ + expect.objectContaining({ + metadata: expect.objectContaining({ name: 'a', description: 'c' }), + spec: { + profile: { displayName: 'b', email: 'd', picture: 'e' }, + memberOf: [], + }, + }), + ], + }; + + server.use( + graphqlMsw.query('users', (_req, res, ctx) => res(ctx.data(input))), + ); + + await expect(getOrganizationUsers(graphql, 'a')).resolves.toEqual(output); + }); + }); + + describe('getOrganizationTeams', () => { + it('reads teams', async () => { + const input: QueryResponse = { + organization: { + teams: { + pageInfo: { hasNextPage: false }, + nodes: [ + { + slug: 'team', + combinedSlug: 'blah/team', + parentTeam: { + slug: 'parent', + combinedSlug: '', + members: { pageInfo: { hasNextPage: false }, nodes: [] }, + }, + members: { + pageInfo: { hasNextPage: false }, + nodes: [{ login: 'user' }], + }, + }, + ], + }, + }, + }; + + const output = { + groups: [ + expect.objectContaining({ + metadata: expect.objectContaining({ name: 'team' }), + spec: { + type: 'team', + parent: 'parent', + ancestors: [], + children: [], + descendants: [], + }, + }), + ], + groupMemberUsers: new Map([['team', ['user']]]), + }; + + server.use( + graphqlMsw.query('teams', (_req, res, ctx) => res(ctx.data(input))), + ); + + await expect(getOrganizationTeams(graphql, 'a')).resolves.toEqual(output); + }); + }); + + describe('getTeamMembers', () => { + it('reads team members', async () => { + const input: QueryResponse = { + organization: { + team: { + slug: '', + combinedSlug: '', + members: { + pageInfo: { hasNextPage: false }, + nodes: [{ login: 'user' }], + }, + }, + }, + }; + + const output = { + members: ['user'], + }; + + server.use( + graphqlMsw.query('members', (_req, res, ctx) => res(ctx.data(input))), + ); + + await expect(getTeamMembers(graphql, 'a', 'b')).resolves.toEqual(output); + }); + }); +}); diff --git a/plugins/catalog-backend/src/ingestion/processors/util/github.ts b/plugins/catalog-backend/src/ingestion/processors/util/github.ts new file mode 100644 index 0000000000..96cf4a7668 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/util/github.ts @@ -0,0 +1,297 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { GroupEntity, UserEntity } from '@backstage/catalog-model'; +import { graphql } from '@octokit/graphql'; + +// Graphql types + +export type QueryResponse = { + organization: Organization; +}; + +export type Organization = { + membersWithRole?: Connection; + team?: Team; + teams?: Connection; +}; + +export type PageInfo = { + hasNextPage: boolean; + endCursor?: string; +}; + +export type User = { + login: string; + bio?: string; + avatarUrl?: string; + email?: string; + name?: string; +}; + +export type Team = { + slug: string; + combinedSlug: string; + description?: string; + parentTeam?: Team; + members: Connection; +}; + +export type Connection = { + pageInfo: PageInfo; + nodes: T[]; +}; + +/** + * Gets all the users out of a GitHub organization. + * + * Note that the users will not have their memberships filled in. + * + * @param client An octokit graphql client + * @param org The slug of the org to read + */ +export async function getOrganizationUsers( + client: typeof graphql, + org: string, +): Promise<{ users: UserEntity[] }> { + const query = ` + query users($org: String!, $cursor: String) { + organization(login: $org) { + membersWithRole(first: 100, after: $cursor) { + pageInfo { hasNextPage, endCursor } + nodes { avatarUrl, bio, email, login, name } + } + } + }`; + + // There is no user -> teams edge, so we leave the memberships empty for + // now and let the team iteration handle it instead + const mapper = (user: User) => { + const entity: UserEntity = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'User', + metadata: { + name: user.login, + annotations: { + 'github.com/user-login': user.login, + }, + }, + spec: { + profile: {}, + memberOf: [], + }, + }; + + if (user.bio) entity.metadata.description = user.bio; + if (user.name) entity.spec.profile!.displayName = user.name; + if (user.email) entity.spec.profile!.email = user.email; + if (user.avatarUrl) entity.spec.profile!.picture = user.avatarUrl; + + return entity; + }; + + const users = await queryWithPaging( + client, + query, + r => r.organization?.membersWithRole, + mapper, + { org }, + ); + + return { users }; +} + +/** + * Gets all the teams out of a GitHub organization. + * + * Note that the teams will not have any relations apart from parent filled in. + * + * @param client An octokit graphql client + * @param org The slug of the org to read + */ +export async function getOrganizationTeams( + client: typeof graphql, + org: string, +): Promise<{ + groups: GroupEntity[]; + groupMemberUsers: Map; +}> { + const query = ` + query teams($org: String!, $cursor: String) { + organization(login: $org) { + teams(first: 100, after: $cursor) { + pageInfo { hasNextPage, endCursor } + nodes { + slug + combinedSlug + parentTeam { slug } + members(first: 100, membership: IMMEDIATE) { + pageInfo { hasNextPage } + nodes { login } + } + } + } + } + }`; + + // Gets populated inside the mapper below + const groupMemberUsers = new Map(); + + const mapper = async (team: Team) => { + const entity: GroupEntity = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Group', + metadata: { + name: team.slug, + annotations: { + 'github.com/team-slug': team.combinedSlug, + }, + }, + spec: { + type: 'team', + ancestors: [], + children: [], + descendants: [], + }, + }; + + if (team.description) entity.metadata.description = team.description; + if (team.parentTeam) entity.spec.parent = team.parentTeam.slug; + + const memberNames: string[] = []; + groupMemberUsers.set(team.slug, memberNames); + + if (!team.members.pageInfo.hasNextPage) { + // We got all the members in one go, run the fast path + for (const user of team.members.nodes) { + memberNames.push(user.login); + } + } else { + // There were more than a hundred immediate members - run the slow + // path of fetching them explicitly + const { members } = await getTeamMembers(client, org, team.slug); + for (const userLogin of members) { + memberNames.push(userLogin); + } + } + + return entity; + }; + + const groups = await queryWithPaging( + client, + query, + r => r.organization?.teams, + mapper, + { org }, + ); + + return { groups, groupMemberUsers }; +} + +/** + * Gets all the users out of a GitHub organization. + * + * Note that the users will not have their memberships filled in. + * + * @param client An octokit graphql client + * @param org The slug of the org to read + * @param teamSlug The slug of the team to read + */ +export async function getTeamMembers( + client: typeof graphql, + org: string, + teamSlug: string, +): Promise<{ members: string[] }> { + const query = ` + query members($org: String!, $teamSlug: String!, $cursor: String) { + organization(login: $org) { + team(slug: $teamSlug) { + members(first: 100, after: $cursor, membership: IMMEDIATE) { + pageInfo { hasNextPage, endCursor } + nodes { login } + } + } + } + }`; + + const members = await queryWithPaging( + client, + query, + r => r.organization?.team?.members, + user => user.login, + { org, teamSlug }, + ); + + return { members }; +} + +// +// Helpers +// + +/** + * Assists in repeatedly executing a query with a paged response. + * + * Requires that the query accepts a $cursor variable. + * + * @param client The octokit client + * @param query The query to execute + * @param connection A function that, given the response, picks out the actual + * Connection object that's being iterated + * @param mapper A function that, given one of the nodes in the Connection, + * returns the model mapped form of it + * @param variables The variable values that the query needs, minus the cursor + */ +export async function queryWithPaging< + GraphqlType, + OutputType, + Variables extends {}, + Response = QueryResponse +>( + client: typeof graphql, + query: string, + connection: (response: Response) => Connection | undefined, + mapper: (item: GraphqlType) => Promise | OutputType, + variables: Variables, +): Promise { + const result: OutputType[] = []; + + let cursor: string | undefined = undefined; + for (let j = 0; j < 1000 /* just for sanity */; ++j) { + const response: Response = await client(query, { + ...variables, + cursor, + }); + + const conn = connection(response); + if (!conn) { + throw new Error(`Found no match for ${JSON.stringify(variables)}`); + } + + for (const node of conn.nodes) { + result.push(await mapper(node)); + } + + if (!conn.pageInfo.hasNextPage) { + break; + } else { + cursor = conn.pageInfo.endCursor; + } + } + + return result; +} diff --git a/plugins/catalog-backend/src/ingestion/processors/util/org.test.ts b/plugins/catalog-backend/src/ingestion/processors/util/org.test.ts new file mode 100644 index 0000000000..e0120735fe --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/util/org.test.ts @@ -0,0 +1,92 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { GroupEntity, UserEntity } from '@backstage/catalog-model'; +import { buildOrgHierarchy } from './org'; + +function u(name: string): UserEntity { + return { + apiVersion: 'backstage.io/v1alpha1', + kind: 'User', + metadata: { name }, + spec: { memberOf: [] }, + }; +} + +function g( + name: string, + parent: string | undefined, + children: string[], +): GroupEntity { + return { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Group', + metadata: { name }, + spec: { type: 'team', parent, children, ancestors: [], descendants: [] }, + }; +} + +describe('buildOrgHierarchy', () => { + it('puts users in the respective groups', () => { + const a = g('a', undefined, []); + const b = g('b', undefined, []); + const x = u('x'); + const y = u('y'); + const groupMemberUsers: Map = new Map([ + ['a', ['x', 'y']], + ['b', ['y']], + ]); + buildOrgHierarchy([a, b], [x, y], groupMemberUsers); + expect(x.spec.memberOf).toEqual(['a']); + expect(y.spec.memberOf).toEqual(['a', 'b']); + }); + + it('adds groups to their parent.children', () => { + const a = g('a', undefined, []); + const b = g('b', 'a', []); + const c = g('c', 'b', []); + const d = g('d', 'a', []); + buildOrgHierarchy([a, b, c, d], [], new Map()); + expect(a.spec.children).toEqual(expect.arrayContaining(['b', 'd'])); + expect(b.spec.children).toEqual(expect.arrayContaining(['c'])); + expect(c.spec.children).toEqual([]); + expect(d.spec.children).toEqual([]); + }); + + it('fills out descendants', () => { + const a = g('a', undefined, []); + const b = g('b', 'a', []); + const c = g('c', 'b', []); + const d = g('d', 'a', []); + buildOrgHierarchy([a, b, c, d], [], new Map()); + expect(a.spec.descendants).toEqual(expect.arrayContaining(['b', 'c', 'd'])); + expect(b.spec.descendants).toEqual(expect.arrayContaining(['c'])); + expect(c.spec.descendants).toEqual([]); + expect(d.spec.descendants).toEqual([]); + }); + + it('fills out ancestors', () => { + const a = g('a', undefined, []); + const b = g('b', 'a', []); + const c = g('c', 'b', []); + const d = g('d', 'a', []); + buildOrgHierarchy([a, b, c, d], [], new Map()); + expect(a.spec.ancestors).toEqual([]); + expect(b.spec.ancestors).toEqual(expect.arrayContaining(['a'])); + expect(c.spec.ancestors).toEqual(expect.arrayContaining(['a', 'b'])); + expect(d.spec.ancestors).toEqual(expect.arrayContaining(['a'])); + }); +}); diff --git a/plugins/catalog-backend/src/ingestion/processors/util/org.ts b/plugins/catalog-backend/src/ingestion/processors/util/org.ts new file mode 100644 index 0000000000..bcc4c7b5e6 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/util/org.ts @@ -0,0 +1,113 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { GroupEntity, UserEntity } from '@backstage/catalog-model'; + +export function buildOrgHierarchy( + groups: GroupEntity[], + users: UserEntity[], + groupMemberUsers: Map, +) { + const groupsByName = new Map(groups.map(g => [g.metadata.name, g])); + const usersByName = new Map(users.map(u => [u.metadata.name, u])); + + // + // Make sure that u.memberOf contain all g + // + + for (const [groupName, userNames] of groupMemberUsers.entries()) { + for (const userName of userNames) { + const user = usersByName.get(userName); + if (user && !user.spec.memberOf.includes(groupName)) { + user.spec.memberOf.push(groupName); + } + } + } + + // + // Make sure that g.parent.children contain g + // + + for (const group of groups) { + const selfName = group.metadata.name; + const parentName = group.spec.parent; + if (parentName) { + const parent = groupsByName.get(parentName); + if (parent && !parent.spec.children.includes(selfName)) { + parent.spec.children.push(selfName); + } + } + } + + // + // Make sure that g.descendants is complete + // + + function visitDescendants(current: GroupEntity): string[] { + if (current.spec.descendants.length) { + return current.spec.descendants; + } + + const accumulator = new Set(); + for (const childName of current.spec.children) { + accumulator.add(childName); + const child = groupsByName.get(childName); + if (child) { + for (const d of visitDescendants(child)) { + accumulator.add(d); + } + } + } + + const descendants = Array.from(accumulator); + current.spec.descendants = descendants; + return descendants; + } + + for (const group of groups) { + visitDescendants(group); + } + + // + // Make sure that g.ancestors is complete + // + + function visitAncestors(current: GroupEntity): string[] { + if (current.spec.ancestors.length) { + return current.spec.ancestors; + } + + let ancestors: string[]; + const parentName = current.spec.parent; + if (!parentName) { + ancestors = []; + } else { + const parent = groupsByName.get(parentName); + if (parent) { + ancestors = [parentName, ...visitAncestors(parent)]; + } else { + ancestors = [parentName]; + } + } + + current.spec.ancestors = ancestors; + return ancestors; + } + + for (const group of groups) { + visitAncestors(group); + } +} diff --git a/plugins/catalog-backend/src/service/router.test.ts b/plugins/catalog-backend/src/service/router.test.ts index 29b3f7ce04..32d7b6aa63 100644 --- a/plugins/catalog-backend/src/service/router.test.ts +++ b/plugins/catalog-backend/src/service/router.test.ts @@ -136,7 +136,11 @@ describe('createRouter', () => { const response = await request(app).get('/entities/by-name/k/ns/n'); expect(entitiesCatalog.entityByName).toHaveBeenCalledTimes(1); - expect(entitiesCatalog.entityByName).toHaveBeenCalledWith('k', 'ns', 'n'); + expect(entitiesCatalog.entityByName).toHaveBeenCalledWith({ + kind: 'k', + namespace: 'ns', + name: 'n', + }); expect(response.status).toEqual(200); expect(response.body).toEqual(expect.objectContaining(entity)); }); @@ -147,7 +151,11 @@ describe('createRouter', () => { const response = await request(app).get('/entities/by-name/b/d/c'); expect(entitiesCatalog.entityByName).toHaveBeenCalledTimes(1); - expect(entitiesCatalog.entityByName).toHaveBeenCalledWith('b', 'd', 'c'); + expect(entitiesCatalog.entityByName).toHaveBeenCalledWith({ + kind: 'b', + namespace: 'd', + name: 'c', + }); expect(response.status).toEqual(404); expect(response.text).toMatch(/name/); }); diff --git a/plugins/catalog-backend/src/service/router.ts b/plugins/catalog-backend/src/service/router.ts index 2919e73396..8da589c721 100644 --- a/plugins/catalog-backend/src/service/router.ts +++ b/plugins/catalog-backend/src/service/router.ts @@ -67,11 +67,11 @@ export async function createRouter( }) .get('/entities/by-name/:kind/:namespace/:name', async (req, res) => { const { kind, namespace, name } = req.params; - const entity = await entitiesCatalog.entityByName( + const entity = await entitiesCatalog.entityByName({ kind, namespace, name, - ); + }); if (!entity) { res .status(404) diff --git a/plugins/catalog-backend/src/service/standaloneServer.ts b/plugins/catalog-backend/src/service/standaloneServer.ts index 0b532d1664..5939c7eb58 100644 --- a/plugins/catalog-backend/src/service/standaloneServer.ts +++ b/plugins/catalog-backend/src/service/standaloneServer.ts @@ -17,6 +17,7 @@ import { createServiceBuilder, loadBackendConfig, + UrlReaders, } from '@backstage/backend-common'; import { ConfigReader } from '@backstage/config'; import { Server } from 'http'; @@ -39,12 +40,13 @@ export async function startStandaloneServer( ): Promise { const logger = options.logger.child({ service: 'catalog-backend' }); const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const reader = UrlReaders.default({ logger, config }); logger.debug('Creating application...'); const db = await DatabaseManager.createInMemoryDatabase({ logger }); const entitiesCatalog = new DatabaseEntitiesCatalog(db); const locationsCatalog = new DatabaseLocationsCatalog(db); - const locationReader = new LocationReaders({ logger, config }); + const locationReader = new LocationReaders({ logger, config, reader }); const higherOrderOperation = new HigherOrderOperations( entitiesCatalog, locationsCatalog, diff --git a/plugins/catalog-graphql/package.json b/plugins/catalog-graphql/package.json index 5d767c4f85..8597f3aa3c 100644 --- a/plugins/catalog-graphql/package.json +++ b/plugins/catalog-graphql/package.json @@ -39,7 +39,7 @@ "@types/express": "^4.17.7", "@types/supertest": "^2.0.8", "eslint-plugin-graphql": "^4.0.0", - "msw": "^0.19.5", + "msw": "^0.20.5", "supertest": "^4.0.2", "ts-node": "^8.10.2" }, diff --git a/plugins/catalog-graphql/src/graphql/module.test.ts b/plugins/catalog-graphql/src/graphql/module.test.ts index 09708f68f4..e3e03a9b4a 100644 --- a/plugins/catalog-graphql/src/graphql/module.test.ts +++ b/plugins/catalog-graphql/src/graphql/module.test.ts @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import { createModule } from './module'; import { execute } from 'graphql'; import { rest } from 'msw'; @@ -36,9 +37,8 @@ describe('Catalog Module', () => { }, ]); - beforeAll(() => worker.listen()); + beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); afterAll(() => worker.close()); - afterEach(() => worker.resetHandlers()); describe('Default Entity', () => { diff --git a/plugins/catalog-graphql/src/service/client.test.ts b/plugins/catalog-graphql/src/service/client.test.ts index 876059802b..d8cc59d1a8 100644 --- a/plugins/catalog-graphql/src/service/client.test.ts +++ b/plugins/catalog-graphql/src/service/client.test.ts @@ -20,9 +20,8 @@ import { setupServer } from 'msw/node'; describe('Catalog GraphQL Module', () => { const worker = setupServer(); - beforeAll(() => worker.listen()); + beforeAll(() => worker.listen({ onUnhandledRequest: 'error' })); afterAll(() => worker.close()); - afterEach(() => worker.resetHandlers()); const baseUrl = 'http://localhost:1234'; diff --git a/plugins/catalog/package.json b/plugins/catalog/package.json index ea6f2ae44d..d3241ec10d 100644 --- a/plugins/catalog/package.json +++ b/plugins/catalog/package.json @@ -53,7 +53,8 @@ "jest-fetch-mock": "^3.0.3", "msw": "^0.20.5", "react-test-renderer": "^16.13.1", - "whatwg-fetch": "^3.4.0" + "whatwg-fetch": "^3.4.0", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/catalog/src/api/CatalogClient.test.ts b/plugins/catalog/src/api/CatalogClient.test.ts index 18f062db77..832a114276 100644 --- a/plugins/catalog/src/api/CatalogClient.test.ts +++ b/plugins/catalog/src/api/CatalogClient.test.ts @@ -25,7 +25,7 @@ const mockBaseUrl = 'http://backstage:9191/i-am-a-mock-base'; const discoveryApi = UrlPatternDiscovery.compile(mockBaseUrl); describe('CatalogClient', () => { - beforeAll(() => server.listen()); + beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); diff --git a/plugins/catalog/src/components/EntityNotFound/EntityNotFound.tsx b/plugins/catalog/src/components/EntityNotFound/EntityNotFound.tsx new file mode 100644 index 0000000000..c7560c6894 --- /dev/null +++ b/plugins/catalog/src/components/EntityNotFound/EntityNotFound.tsx @@ -0,0 +1,61 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Grid, Button, Typography } from '@material-ui/core'; +import { makeStyles } from '@material-ui/core/styles'; +import { BackstageTheme } from '@backstage/theme'; + +import { Illo } from './Illo'; + +const useStyles = makeStyles(theme => ({ + container: { + paddingTop: theme.spacing(24), + paddingLeft: theme.spacing(8), + }, + title: { + paddingBottom: theme.spacing(2), + }, + body: { + paddingBottom: theme.spacing(6), + }, +})); + +export const EntityNotFound = () => { + const classes = useStyles(); + + return ( + + + + + Entity was not found + + + Want to help us build this? Check out our Getting Started + documentation. + + + + + ); +}; diff --git a/plugins/catalog/src/components/EntityNotFound/Illo.jsx b/plugins/catalog/src/components/EntityNotFound/Illo.jsx new file mode 100644 index 0000000000..36b8d84f5d --- /dev/null +++ b/plugins/catalog/src/components/EntityNotFound/Illo.jsx @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { makeStyles } from '@material-ui/core'; +import IlloSvgUrl from './illo.svg'; + +const useStyles = makeStyles({ + illo: { + maxWidth: '60%', + top: 100, + right: 20, + position: 'absolute', + }, +}); + +export const Illo = () => { + const classes = useStyles(); + return ; +}; diff --git a/plugins/catalog/src/components/EntityNotFound/illo.svg b/plugins/catalog/src/components/EntityNotFound/illo.svg new file mode 100644 index 0000000000..df97dfe063 --- /dev/null +++ b/plugins/catalog/src/components/EntityNotFound/illo.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/catalog/src/components/EntityNotFound/index.ts b/plugins/catalog/src/components/EntityNotFound/index.ts new file mode 100644 index 0000000000..613ea7b36d --- /dev/null +++ b/plugins/catalog/src/components/EntityNotFound/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { EntityNotFound } from './EntityNotFound'; diff --git a/plugins/catalog/src/components/Router.tsx b/plugins/catalog/src/components/Router.tsx index 61855f56d9..c6e706c15b 100644 --- a/plugins/catalog/src/components/Router.tsx +++ b/plugins/catalog/src/components/Router.tsx @@ -15,6 +15,7 @@ */ import React, { ComponentType } from 'react'; import { CatalogPage } from './CatalogPage'; +import { EntityNotFound } from './EntityNotFound'; import { EntityPageLayout } from './EntityPageLayout'; import { Route, Routes } from 'react-router'; import { entityRoute, rootRoute } from '../routes'; @@ -45,9 +46,10 @@ const DefaultEntityPage = () => ( ); const EntityPageSwitch = ({ EntityPage }: { EntityPage: ComponentType }) => { - const { entity } = useEntity(); + const { entity, loading, error } = useEntity(); // Loading and error states - if (!entity) return ; + if (loading) return ; + if (error || (!loading && !entity)) return ; // Otherwise EntityPage provided from the App // Note that EntityPage will include EntityPageLayout already diff --git a/plugins/catalog/src/hooks/useEntity.ts b/plugins/catalog/src/hooks/useEntity.ts index 53b1cff73a..77ea8c1569 100644 --- a/plugins/catalog/src/hooks/useEntity.ts +++ b/plugins/catalog/src/hooks/useEntity.ts @@ -20,8 +20,6 @@ import { catalogApiRef } from '../api/types'; import { useAsync } from 'react-use'; import { Entity } from '@backstage/catalog-model'; -const REDIRECT_DELAY = 2000; - type EntityLoadingStatus = { entity?: Entity; loading: boolean; @@ -47,13 +45,6 @@ export const useEntityFromUrl = (): EntityLoadingStatus => { ); useEffect(() => { - if (error || (!loading && !entity)) { - errorApi.post(new Error('Entity not found!')); - setTimeout(() => { - navigate('/'); - }, REDIRECT_DELAY); - } - if (!name) { errorApi.post(new Error('No name provided!')); navigate('/'); @@ -67,6 +58,10 @@ export const useEntityFromUrl = (): EntityLoadingStatus => { * Always going to return an entity, or throw an error if not a descendant of a EntityProvider. */ export const useEntity = () => { - const { entity } = useContext<{ entity: Entity }>(EntityContext as any); - return { entity }; + const { entity, loading, error } = useContext<{ + entity: Entity; + loading: boolean; + error: Error; + }>(EntityContext as any); + return { entity, loading, error }; }; diff --git a/plugins/circleci/README.md b/plugins/circleci/README.md index 48e1bee6cc..19c2c35899 100644 --- a/plugins/circleci/README.md +++ b/plugins/circleci/README.md @@ -55,9 +55,6 @@ import { Router as CircleCIRouter } from '@backstage/plugin-circleci'; proxy: '/circleci/api': target: https://circleci.com/api/v1.1 - changeOrigin: true - pathRewrite: - '^/proxy/circleci/api/': '/' headers: Circle-Token: $secret: diff --git a/plugins/circleci/dev/index.tsx b/plugins/circleci/dev/index.tsx index 4bf67d5cb2..812a5585d4 100644 --- a/plugins/circleci/dev/index.tsx +++ b/plugins/circleci/dev/index.tsx @@ -16,13 +16,5 @@ import { createDevApp } from '@backstage/dev-utils'; import { plugin } from '../src/plugin'; -import { circleCIApiRef, CircleCIApi } from '../src/api'; -createDevApp() - .registerPlugin(plugin) - .registerApi({ - api: circleCIApiRef, - deps: {}, - factory: () => new CircleCIApi(), - }) - .render(); +createDevApp().registerPlugin(plugin).render(); diff --git a/plugins/circleci/package.json b/plugins/circleci/package.json index ebff4b9eba..a661c2562f 100644 --- a/plugins/circleci/package.json +++ b/plugins/circleci/package.json @@ -46,7 +46,9 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/react-lazylog": "^4.5.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/circleci/src/api/index.ts b/plugins/circleci/src/api/index.ts index da4c811812..c71be6b781 100644 --- a/plugins/circleci/src/api/index.ts +++ b/plugins/circleci/src/api/index.ts @@ -26,7 +26,7 @@ import { BuildSummary, GitType, } from 'circleci-api'; -import { createApiRef } from '@backstage/core'; +import { createApiRef, DiscoveryApi } from '@backstage/core'; export { GitType }; export type { BuildWithSteps, BuildStepAction, BuildSummary }; @@ -36,15 +36,28 @@ export const circleCIApiRef = createApiRef({ description: 'Used by the CircleCI plugin to make requests', }); +const DEFAULT_PROXY_PATH = '/circleci/api'; + +type Options = { + discoveryApi: DiscoveryApi; + /** + * Path to use for requests via the proxy, defaults to /circleci/api + */ + proxyPath?: string; +}; + export class CircleCIApi { - apiUrl: string; - constructor(apiUrl: string = '/circleci/api') { - this.apiUrl = apiUrl; + private readonly discoveryApi: DiscoveryApi; + private readonly proxyPath: string; + + constructor(options: Options) { + this.discoveryApi = options.discoveryApi; + this.proxyPath = options.proxyPath ?? DEFAULT_PROXY_PATH; } async retry(buildNumber: number, options: Partial) { return postBuildActions('', buildNumber, BuildAction.RETRY, { - circleHost: this.apiUrl, + circleHost: await this.getApiUrl(), ...options.vcs, }); } @@ -59,19 +72,24 @@ export class CircleCIApi { offset, }, vcs: {}, - circleHost: this.apiUrl, + circleHost: await this.getApiUrl(), ...options, }); } async getUser(options: Partial) { - return getMe('', { circleHost: this.apiUrl, ...options }); + return getMe('', { circleHost: await this.getApiUrl(), ...options }); } async getBuild(buildNumber: number, options: Partial) { return getFullBuild('', buildNumber, { - circleHost: this.apiUrl, + circleHost: await this.getApiUrl(), ...options.vcs, }); } + + private async getApiUrl() { + const proxyUrl = await this.discoveryApi.getBaseUrl('proxy'); + return proxyUrl + this.proxyPath; + } } diff --git a/plugins/circleci/src/plugin.ts b/plugins/circleci/src/plugin.ts index f966caa383..c5bb122ed3 100644 --- a/plugins/circleci/src/plugin.ts +++ b/plugins/circleci/src/plugin.ts @@ -14,7 +14,11 @@ * limitations under the License. */ -import { createPlugin, createApiFactory, configApiRef } from '@backstage/core'; +import { + createPlugin, + createApiFactory, + discoveryApiRef, +} from '@backstage/core'; import { circleCIApiRef, CircleCIApi } from './api'; export const plugin = createPlugin({ @@ -22,11 +26,8 @@ export const plugin = createPlugin({ apis: [ createApiFactory({ api: circleCIApiRef, - deps: { configApi: configApiRef }, - factory: ({ configApi }) => - new CircleCIApi( - `${configApi.getString('backend.baseUrl')}/proxy/circleci/api`, - ), + deps: { discoveryApi: discoveryApiRef }, + factory: ({ discoveryApi }) => new CircleCIApi({ discoveryApi }), }), ], }); diff --git a/plugins/cloudbuild/.eslintrc.js b/plugins/cloudbuild/.eslintrc.js new file mode 100644 index 0000000000..13573efa9c --- /dev/null +++ b/plugins/cloudbuild/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: [require.resolve('@backstage/cli/config/eslint')], +}; diff --git a/plugins/cloudbuild/README.md b/plugins/cloudbuild/README.md new file mode 100644 index 0000000000..5f1f6519dc --- /dev/null +++ b/plugins/cloudbuild/README.md @@ -0,0 +1,13 @@ +# Google Cloud Build + +Welcome to the Google Cloud Build plugin! + +_This plugin was created through the Backstage CLI_ + +## Getting started + +Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn start` in the root directory, and then navigating to [/cloudbuild](http://localhost:3000/cloudbuild). + +You can also serve the plugin in isolation by running `yarn start` in the plugin directory. +This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads. +It is only meant for local development, and the setup for it can be found inside the [/dev](./dev) directory. diff --git a/plugins/cloudbuild/dev/index.tsx b/plugins/cloudbuild/dev/index.tsx new file mode 100644 index 0000000000..264d6f801f --- /dev/null +++ b/plugins/cloudbuild/dev/index.tsx @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createDevApp } from '@backstage/dev-utils'; +import { plugin } from '../src/plugin'; + +createDevApp().registerPlugin(plugin).render(); diff --git a/plugins/cloudbuild/package.json b/plugins/cloudbuild/package.json new file mode 100644 index 0000000000..3367bb6cca --- /dev/null +++ b/plugins/cloudbuild/package.json @@ -0,0 +1,57 @@ +{ + "name": "@backstage/plugin-cloudbuild", + "version": "0.1.1-alpha.23", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "private": true, + "publishConfig": { + "access": "public", + "main": "dist/index.esm.js", + "types": "dist/index.d.ts" + }, + "scripts": { + "build": "backstage-cli plugin:build", + "start": "backstage-cli plugin:serve", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "diff": "backstage-cli plugin:diff", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/catalog-model": "^0.1.1-alpha.23", + "@backstage/core": "^0.1.1-alpha.23", + "@backstage/plugin-catalog": "^0.1.1-alpha.23", + "@backstage/theme": "^0.1.1-alpha.23", + "@material-ui/core": "^4.11.0", + "@material-ui/icons": "^4.9.1", + "@material-ui/lab": "4.0.0-alpha.45", + "@octokit/rest": "^18.0.0", + "@octokit/types": "^5.4.1", + "moment": "^2.27.0", + "qs": "^6.9.4", + "react": "^16.13.1", + "react-dom": "^16.13.1", + "react-lazylog": "^4.5.3", + "react-router": "6.0.0-beta.0", + "react-router-dom": "6.0.0-beta.0", + "react-use": "^15.3.3" + }, + "devDependencies": { + "@backstage/cli": "^0.1.1-alpha.23", + "@backstage/dev-utils": "^0.1.1-alpha.23", + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/react": "^10.4.1", + "@testing-library/user-event": "^12.0.7", + "@types/jest": "^26.0.7", + "@types/node": "^12.0.0", + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/cloudbuild/src/api/CloudbuildApi.ts b/plugins/cloudbuild/src/api/CloudbuildApi.ts new file mode 100644 index 0000000000..5aecf970ef --- /dev/null +++ b/plugins/cloudbuild/src/api/CloudbuildApi.ts @@ -0,0 +1,53 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createApiRef } from '@backstage/core'; +import { + ActionsListWorkflowRunsForRepoResponseData, + ActionsGetWorkflowResponseData, +} from '../api/types'; + +export const cloudbuildApiRef = createApiRef({ + id: 'plugin.cloudbuild.service', + description: 'Used by the Cloudbuild plugin to make requests', +}); + +export type CloudbuildApi = { + listWorkflowRuns: (request: { + projectId: string; + }) => Promise; + getWorkflow: ({ + projectId, + id, + }: { + projectId: string; + id: string; + }) => Promise; + getWorkflowRun: ({ + projectId, + id, + }: { + projectId: string; + id: string; + }) => Promise; + reRunWorkflow: ({ + projectId, + runId, + }: { + projectId: string; + runId: string; + }) => Promise; +}; diff --git a/plugins/cloudbuild/src/api/CloudbuildClient.ts b/plugins/cloudbuild/src/api/CloudbuildClient.ts new file mode 100644 index 0000000000..0c3223aa04 --- /dev/null +++ b/plugins/cloudbuild/src/api/CloudbuildClient.ts @@ -0,0 +1,122 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { CloudbuildApi } from './CloudbuildApi'; +import { + ActionsListWorkflowRunsForRepoResponseData, + ActionsGetWorkflowResponseData, +} from '../api/types'; +import { OAuthApi } from '@backstage/core'; + +export class CloudbuildClient implements CloudbuildApi { + constructor(private readonly googleAuthApi: OAuthApi) {} + + async reRunWorkflow({ + projectId, + runId, + }: { + projectId: string; + runId: string; + }): Promise { + await fetch( + `https://cloudbuild.googleapis.com/v1/projects/${encodeURIComponent( + projectId, + )}/builds/${encodeURIComponent(runId)}:retry`, + { + headers: new Headers({ + Accept: '*/*', + Authorization: `Bearer ${await this.getToken()}`, + }), + }, + ); + } + async listWorkflowRuns({ + projectId, + }: { + projectId: string; + }): Promise { + const workflowRuns = await fetch( + `https://cloudbuild.googleapis.com/v1/projects/${encodeURIComponent( + projectId, + )}/builds`, + { + headers: new Headers({ + Accept: '*/*', + Authorization: `Bearer ${await this.getToken()}`, + }), + }, + ); + + const builds: ActionsListWorkflowRunsForRepoResponseData = await workflowRuns.json(); + + return builds; + } + async getWorkflow({ + projectId, + id, + }: { + projectId: string; + id: string; + }): Promise { + const workflow = await fetch( + `https://cloudbuild.googleapis.com/v1/projects/${encodeURIComponent( + projectId, + )}/builds/${encodeURIComponent(id)}`, + { + headers: new Headers({ + Accept: '*/*', + Authorization: `Bearer ${await this.getToken()}`, + }), + }, + ); + + const build: ActionsGetWorkflowResponseData = await workflow.json(); + + return build; + } + async getWorkflowRun({ + projectId, + id, + }: { + projectId: string; + id: string; + }): Promise { + const workflow = await fetch( + `https://cloudbuild.googleapis.com/v1/projects/${encodeURIComponent( + projectId, + )}/builds/${encodeURIComponent(id)}`, + { + headers: new Headers({ + Accept: '*/*', + Authorization: `Bearer ${await this.getToken()}`, + }), + }, + ); + const build: ActionsGetWorkflowResponseData = await workflow.json(); + + return build; + } + + async getToken(): Promise { + // NOTE(freben - gcp-projects): There's a .read-only variant of this scope that we could + // use for readonly operations, but that means we would ask the user for a + // second auth during creation and I decided to keep the wider scope for + // all ops for now + return this.googleAuthApi.getAccessToken( + 'https://www.googleapis.com/auth/cloud-platform', + ); + } +} diff --git a/plugins/cloudbuild/src/api/index.ts b/plugins/cloudbuild/src/api/index.ts new file mode 100644 index 0000000000..643eecb818 --- /dev/null +++ b/plugins/cloudbuild/src/api/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './CloudbuildApi'; +export * from './CloudbuildClient'; +export * from './types'; diff --git a/plugins/cloudbuild/src/api/types.ts b/plugins/cloudbuild/src/api/types.ts new file mode 100644 index 0000000000..7c64fb52b8 --- /dev/null +++ b/plugins/cloudbuild/src/api/types.ts @@ -0,0 +1,125 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface ActionsListWorkflowRunsForRepoResponseData { + builds: ActionsGetWorkflowResponseData[]; +} + +export type ActionsGetWorkflowResponseData = { + id: string; + status: string; + source: Source; + createTime: string; + startTime: string; + steps: Step[]; + timeout: string; + projectId: string; + logsBucket: string; + sourceProvenance: SourceProvenance; + buildTriggerId: string; + options: Options; + logUrl: string; + substitutions: Substitutions; + tags: string[]; + queueTtl: string; + name: string; + finishTime: any; + results: Results; + timing: Timing2; +}; + +export interface Step { + name: string; + args: string[]; + id: string; + waitFor: string[]; + entrypoint: string; + volumes: Volume[]; + dir: string; + timing: Timing; + status: string; + pullTiming: PullTiming; +} + +export interface Timing2 { + BUILD: BUILD; + FETCHSOURCE: FETCHSOURCE; +} + +export interface SourceProvenance { + resolvedStorageSource: {}; + fileHashes: {}; +} + +export interface Options { + machineType: string; + substitutionOption: string; + logging: string; + dynamicSubstitutions: boolean; +} + +export interface Substitutions { + COMMIT_SHA: string; + SHORT_SHA: string; + BRANCH_NAME: string; + REPO_NAME: string; + REVISION_ID: string; +} + +export interface Results { + buildStepImages: string[]; + buildStepOutputs: string[]; +} + +export interface BUILD { + startTime: string; + endTime: string; +} + +export interface FETCHSOURCE { + startTime: string; + endTime: string; +} + +export interface StorageSource { + bucket: string; + object: string; +} + +export interface Source { + storageSource: StorageSource; +} + +export interface Volume { + name: string; + path: string; +} + +export interface Timing { + startTime: string; + endTime: string; +} + +export interface PullTiming { + startTime: string; + endTime: string; +} + +export interface ResolvedStorageSource { + bucket: string; + object: string; + generation: string; +} diff --git a/plugins/cloudbuild/src/components/Cards/Cards.tsx b/plugins/cloudbuild/src/components/Cards/Cards.tsx new file mode 100644 index 0000000000..bbfb0b59c3 --- /dev/null +++ b/plugins/cloudbuild/src/components/Cards/Cards.tsx @@ -0,0 +1,116 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { useEffect } from 'react'; +import { useWorkflowRuns } from '../useWorkflowRuns'; +import { WorkflowRun, WorkflowRunsTable } from '../WorkflowRunsTable'; +import { Entity } from '@backstage/catalog-model'; +import { WorkflowRunStatus } from '../WorkflowRunStatus'; +import { Link, Theme, makeStyles, LinearProgress } from '@material-ui/core'; +import { + InfoCard, + StructuredMetadataTable, + errorApiRef, + useApi, + WarningPanel, +} from '@backstage/core'; +import ExternalLinkIcon from '@material-ui/icons/Launch'; +import { CLOUDBUILD_ANNOTATION } from '../useProjectName'; + +const useStyles = makeStyles({ + externalLinkIcon: { + fontSize: 'inherit', + verticalAlign: 'bottom', + }, +}); + +const WidgetContent = ({ + error, + loading, + lastRun, + branch, +}: { + error?: Error; + loading?: boolean; + lastRun: WorkflowRun; + branch: string; +}) => { + const classes = useStyles(); + if (error) + return Couldn't fetch latest {branch} run; + if (loading) return ; + return ( + + + + ), + message: lastRun.message, + url: ( + + See more on Google{' '} + + + ), + }} + /> + ); +}; + +export const LatestWorkflowRunCard = ({ + entity, + branch = 'master', +}: { + entity: Entity; + branch: string; +}) => { + const errorApi = useApi(errorApiRef); + const projectId = entity?.metadata.annotations?.[CLOUDBUILD_ANNOTATION] || ''; + + const [{ runs, loading, error }] = useWorkflowRuns({ + projectId, + }); + const lastRun = runs?.[0] ?? ({} as WorkflowRun); + useEffect(() => { + if (error) { + errorApi.post(error); + } + }, [error, errorApi]); + + return ( + + + + ); +}; + +export const LatestWorkflowsForBranchCard = ({ + entity, + branch = 'master', +}: { + entity: Entity; + branch: string; +}) => ( + + + +); diff --git a/plugins/cloudbuild/src/components/Cards/index.ts b/plugins/cloudbuild/src/components/Cards/index.ts new file mode 100644 index 0000000000..8c987ea1d5 --- /dev/null +++ b/plugins/cloudbuild/src/components/Cards/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { LatestWorkflowRunCard, LatestWorkflowsForBranchCard } from './Cards'; diff --git a/plugins/cloudbuild/src/components/Router.tsx b/plugins/cloudbuild/src/components/Router.tsx new file mode 100644 index 0000000000..b2653a05f2 --- /dev/null +++ b/plugins/cloudbuild/src/components/Router.tsx @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { Entity } from '@backstage/catalog-model'; +import { Routes, Route } from 'react-router'; +import { rootRouteRef, buildRouteRef } from '../plugin'; +import { WorkflowRunDetails } from './WorkflowRunDetails'; +import { WorkflowRunsTable } from './WorkflowRunsTable'; +import { CLOUDBUILD_ANNOTATION } from './useProjectName'; +import { WarningPanel } from '@backstage/core'; + +export const isPluginApplicableToEntity = (entity: Entity) => + Boolean(entity.metadata.annotations?.[CLOUDBUILD_ANNOTATION]); + +export const Router = ({ entity }: { entity: Entity }) => + // TODO(shmidt-i): move warning to a separate standardized component + !isPluginApplicableToEntity(entity) ? ( + +
{CLOUDBUILD_ANNOTATION}
annotation is missing on the entity. +
+ ) : ( + + } + /> + } + /> + ) + + ); diff --git a/plugins/cloudbuild/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx b/plugins/cloudbuild/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx new file mode 100644 index 0000000000..94c6fa4d25 --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunDetails/WorkflowRunDetails.tsx @@ -0,0 +1,148 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Entity } from '@backstage/catalog-model'; +import { Link, WarningPanel } from '@backstage/core'; +import { + Breadcrumbs, + LinearProgress, + Link as MaterialLink, + makeStyles, + Paper, + Table, + TableBody, + TableCell, + TableContainer, + TableRow, + Theme, + Typography, +} from '@material-ui/core'; +import ExternalLinkIcon from '@material-ui/icons/Launch'; +import qs from 'qs'; +import React from 'react'; +import { useProjectName } from '../useProjectName'; +import { WorkflowRunStatus } from '../WorkflowRunStatus'; +import { useWorkflowRunsDetails } from './useWorkflowRunsDetails'; + +const useStyles = makeStyles(theme => ({ + root: { + maxWidth: 720, + margin: theme.spacing(2), + }, + title: { + padding: theme.spacing(1, 0, 2, 0), + }, + table: { + padding: theme.spacing(1), + }, + accordionDetails: { + padding: 0, + }, + button: { + order: -1, + marginRight: 0, + marginLeft: '-20px', + }, + externalLinkIcon: { + fontSize: 'inherit', + verticalAlign: 'bottom', + }, +})); + +export const WorkflowRunDetails = ({ entity }: { entity: Entity }) => { + const { value: projectName, loading, error } = useProjectName(entity); + const [projectId] = (projectName ?? '/').split('/'); + + const details = useWorkflowRunsDetails(projectId); + + const classes = useStyles(); + if (error) { + return ( + + Failed to load build, {error.message}. + + ); + } else if (loading) { + return ; + } else if (details.value?.logUrl === undefined) { + return ; + } + + const serviceAccount = qs.parse(new URL(details.value?.logUrl).search, { + ignoreQueryPrefix: true, + }).project; + + return ( +
+ + Workflow runs + Workflow run details + + + + + + + Branch + + {details.value?.substitutions.BRANCH_NAME} + + + + Message + + {details.value?.substitutions.REPO_NAME} + + + + Commit ID + + {details.value?.substitutions.COMMIT_SHA} + + + + Status + + + + + + + + Service Account + + + {`${serviceAccount}`}@cloudbuild.gserviceaccount.com + + + + + Links + + + {details.value?.logUrl && ( + + Workflow runs on Google{' '} + + + )} + + + +
+
+
+ ); +}; diff --git a/plugins/cloudbuild/src/components/WorkflowRunDetails/index.ts b/plugins/cloudbuild/src/components/WorkflowRunDetails/index.ts new file mode 100644 index 0000000000..2886a26740 --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunDetails/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { WorkflowRunDetails } from './WorkflowRunDetails'; diff --git a/plugins/identity-backend/src/adapters/userGroups.ts b/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts similarity index 56% rename from plugins/identity-backend/src/adapters/userGroups.ts rename to plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts index 806ca1f43f..2150e01d98 100644 --- a/plugins/identity-backend/src/adapters/userGroups.ts +++ b/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunJobs.ts @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export const userGroups = { - groups: [ - { - name: 'engineering', - type: 'org', - children: [ - { - name: 'authentication', - type: 'team', - members: [{ name: 'kent' }, { name: 'dobbs' }], - }, - { - name: 'checkout', - type: 'team', - members: [{ name: 'don' }, { name: 'abramev' }], - }, - ], - }, - ], +import { useAsync } from 'react-use'; +import { ActionsListWorkflowRunsForRepoResponseData } from '../../api/types'; + +export const useWorkflowRunJobs = (jobsUrl?: string) => { + const jobs = useAsync(async (): Promise< + ActionsListWorkflowRunsForRepoResponseData + > => { + if (jobsUrl === undefined) { + return { + builds: [], + }; + } + + const data = await fetch(jobsUrl).then(d => d.json()); + return data; + }, [jobsUrl]); + return jobs; }; diff --git a/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunsDetails.ts b/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunsDetails.ts new file mode 100644 index 0000000000..ae5e750d15 --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunDetails/useWorkflowRunsDetails.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { useApi } from '@backstage/core'; +import { useParams } from 'react-router-dom'; +import { useAsync } from 'react-use'; +import { cloudbuildApiRef } from '../../api'; + +export const useWorkflowRunsDetails = (projectId: string) => { + const api = useApi(cloudbuildApiRef); + const { id } = useParams(); + const details = useAsync(async () => { + return projectId + ? api.getWorkflowRun({ + projectId, + id: id, + }) + : Promise.reject('No projectId provided'); + }, [projectId, id]); + return details; +}; diff --git a/plugins/cloudbuild/src/components/WorkflowRunStatus/WorkflowRunStatus.tsx b/plugins/cloudbuild/src/components/WorkflowRunStatus/WorkflowRunStatus.tsx new file mode 100644 index 0000000000..45a8fc662c --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunStatus/WorkflowRunStatus.tsx @@ -0,0 +1,70 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + StatusPending, + StatusRunning, + StatusOK, + StatusAborted, + StatusError, +} from '@backstage/core'; +import React from 'react'; + +export const WorkflowRunStatus = ({ + status, +}: { + status: string | undefined; +}) => { + if (status === undefined) return null; + switch (status.toLowerCase()) { + case 'queued': + return ( + <> + Queued + + ); + case 'working': + return ( + <> + In progress + + ); + case 'success': + return ( + <> + Completed + + ); + case 'cancelled': + return ( + <> + Cancelled + + ); + case 'failure': + return ( + <> + Failed + + ); + default: + return ( + <> + Pending + + ); + } +}; diff --git a/plugins/cloudbuild/src/components/WorkflowRunStatus/index.ts b/plugins/cloudbuild/src/components/WorkflowRunStatus/index.ts new file mode 100644 index 0000000000..8ebca32cbd --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunStatus/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { WorkflowRunStatus } from './WorkflowRunStatus'; diff --git a/plugins/cloudbuild/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx b/plugins/cloudbuild/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx new file mode 100644 index 0000000000..254e6f89ed --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunsTable/WorkflowRunsTable.tsx @@ -0,0 +1,185 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { FC } from 'react'; +import { Link, Typography, Box, IconButton, Tooltip } from '@material-ui/core'; +import RetryIcon from '@material-ui/icons/Replay'; +import GoogleIcon from '@material-ui/icons/CloudCircle'; +import { Link as RouterLink, generatePath } from 'react-router-dom'; +import { Table, TableColumn } from '@backstage/core'; +import { useWorkflowRuns } from '../useWorkflowRuns'; +import { WorkflowRunStatus } from '../WorkflowRunStatus'; +import SyncIcon from '@material-ui/icons/Sync'; +import { useProjectName } from '../useProjectName'; +import { Entity } from '@backstage/catalog-model'; +import { Substitutions } from '../../api/types'; +import { buildRouteRef } from '../../plugin'; +import moment from 'moment'; + +export type WorkflowRun = { + id: string; + message: string; + url?: string; + googleUrl?: string; + status: string; + substitutions: Substitutions; + createTime: string; + rerun: () => void; +}; + +const generatedColumns: TableColumn[] = [ + { + title: 'Status', + width: '150px', + + render: (row: Partial) => ( + + + + ), + }, + { + title: 'Build', + field: 'id', + type: 'numeric', + width: '150px', + render: (row: Partial) => ( + +

{row.id?.substring(0, 8)}

+
+ ), + }, + { + title: 'Source', + field: 'source', + highlight: true, + width: '200px', + render: (row: Partial) => ( + + {row.message} + + ), + }, + { + title: 'Ref', + render: (row: Partial) => ( + +

{row.substitutions?.BRANCH_NAME}

+
+ ), + }, + { + title: 'Commit', + render: (row: Partial) => ( + +

{row.substitutions?.SHORT_SHA}

+
+ ), + }, + { + title: 'Created', + render: (row: Partial) => ( + +

{moment(row.createTime).format('DD-MM-YYYY hh:mm:ss')}

+
+ ), + }, + { + title: 'Actions', + render: (row: Partial) => ( + + + + + + ), + width: '10%', + }, +]; + +type Props = { + loading: boolean; + retry: () => void; + runs?: WorkflowRun[]; + projectName: string; + page: number; + onChangePage: (page: number) => void; + total: number; + pageSize: number; + onChangePageSize: (pageSize: number) => void; +}; + +export const WorkflowRunsTableView: FC = ({ + projectName, + loading, + pageSize, + page, + retry, + runs, + onChangePage, + onChangePageSize, + total, +}) => { + return ( + , + tooltip: 'Reload workflow runs', + isFreeAction: true, + onClick: () => retry(), + }, + ]} + data={runs ?? []} + onChangePage={onChangePage} + onChangeRowsPerPage={onChangePageSize} + style={{ width: '100%' }} + title={ + + + + {projectName} + + } + columns={generatedColumns} + /> + ); +}; + +export const WorkflowRunsTable = ({ entity }: { entity: Entity }) => { + const { value: projectName, loading } = useProjectName(entity); + const [projectId] = (projectName ?? '/').split('/'); + + const [tableProps, { retry, setPage, setPageSize }] = useWorkflowRuns({ + projectId, + }); + + return ( + + ); +}; diff --git a/plugins/cloudbuild/src/components/WorkflowRunsTable/index.ts b/plugins/cloudbuild/src/components/WorkflowRunsTable/index.ts new file mode 100644 index 0000000000..4e21cc67c2 --- /dev/null +++ b/plugins/cloudbuild/src/components/WorkflowRunsTable/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { WorkflowRunsTable, WorkflowRunsTableView } from './WorkflowRunsTable'; +export type { WorkflowRun } from './WorkflowRunsTable'; diff --git a/plugins/cloudbuild/src/components/useProjectName.ts b/plugins/cloudbuild/src/components/useProjectName.ts new file mode 100644 index 0000000000..0c227f690d --- /dev/null +++ b/plugins/cloudbuild/src/components/useProjectName.ts @@ -0,0 +1,27 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { useAsync } from 'react-use'; +import { Entity } from '@backstage/catalog-model'; + +export const CLOUDBUILD_ANNOTATION = 'google.com/cloudbuild-project-slug'; + +export const useProjectName = (entity: Entity) => { + const { value, loading, error } = useAsync(async () => { + return entity?.metadata.annotations?.[CLOUDBUILD_ANNOTATION] ?? ''; + }); + return { value, loading, error }; +}; diff --git a/plugins/cloudbuild/src/components/useWorkflowRuns.ts b/plugins/cloudbuild/src/components/useWorkflowRuns.ts new file mode 100644 index 0000000000..b6d6c2c620 --- /dev/null +++ b/plugins/cloudbuild/src/components/useWorkflowRuns.ts @@ -0,0 +1,91 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { useState } from 'react'; +import { useAsyncRetry } from 'react-use'; +import { WorkflowRun } from './WorkflowRunsTable/WorkflowRunsTable'; +import { cloudbuildApiRef } from '../api/CloudbuildApi'; +import { useApi, errorApiRef } from '@backstage/core'; +import { ActionsListWorkflowRunsForRepoResponseData } from '../api/types'; + +export function useWorkflowRuns({ projectId }: { projectId: string }) { + const api = useApi(cloudbuildApiRef); + const errorApi = useApi(errorApiRef); + + const [total, setTotal] = useState(0); + const [page, setPage] = useState(0); + const [pageSize, setPageSize] = useState(5); + + const { loading, value: runs, retry, error } = useAsyncRetry< + WorkflowRun[] + >(async () => { + return api + .listWorkflowRuns({ + projectId, + }) + .then( + ( + workflowRunsData: ActionsListWorkflowRunsForRepoResponseData, + ): WorkflowRun[] => { + setTotal(workflowRunsData.builds.length); + // Transformation here + return workflowRunsData.builds.map(run => ({ + message: run.substitutions.REPO_NAME, + id: run.id, + rerun: async () => { + try { + await api.reRunWorkflow({ + projectId, + runId: run.id, + }); + } catch (e) { + errorApi.post(e); + } + }, + substitutions: run.substitutions, + source: { + branchName: run.substitutions.REPO_NAME, + commit: { + hash: run.substitutions.COMMIT_SHA, + url: run.substitutions.REPO_NAME, + }, + }, + status: run.status, + url: run.logUrl, + googleUrl: run.logUrl, + createTime: run.createTime, + })); + }, + ); + }, [page, pageSize, projectId]); + + return [ + { + page, + pageSize, + loading, + runs, + projectName: `${projectId}`, + total, + error, + }, + { + runs, + setPage, + setPageSize, + retry, + }, + ] as const; +} diff --git a/plugins/cloudbuild/src/index.ts b/plugins/cloudbuild/src/index.ts new file mode 100644 index 0000000000..616bb6b4e7 --- /dev/null +++ b/plugins/cloudbuild/src/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { plugin } from './plugin'; +export * from './api'; +export { Router, isPluginApplicableToEntity } from './components/Router'; +export * from './components/Cards'; +export { CLOUDBUILD_ANNOTATION } from './components/useProjectName'; diff --git a/plugins/identity-backend/src/index.test.ts b/plugins/cloudbuild/src/plugin.test.ts similarity index 81% rename from plugins/identity-backend/src/index.test.ts rename to plugins/cloudbuild/src/plugin.test.ts index 4fca4ca746..dae16f1d1b 100644 --- a/plugins/identity-backend/src/index.test.ts +++ b/plugins/cloudbuild/src/plugin.test.ts @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +import { plugin } from './plugin'; -import '@backstage/backend-common'; - -describe('test', () => { - it('unbreaks the test runner', () => { - expect(true).toBeTruthy(); +describe('cloudbuild', () => { + it('should export plugin', () => { + expect(plugin).toBeDefined(); }); }); diff --git a/plugins/cloudbuild/src/plugin.ts b/plugins/cloudbuild/src/plugin.ts new file mode 100644 index 0000000000..ee997cc7ec --- /dev/null +++ b/plugins/cloudbuild/src/plugin.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + createPlugin, + createRouteRef, + createApiFactory, + googleAuthApiRef, +} from '@backstage/core'; +import { cloudbuildApiRef, CloudbuildClient } from './api'; + +export const rootRouteRef = createRouteRef({ + path: '', + title: 'Google Cloudbuild', +}); + +export const buildRouteRef = createRouteRef({ + path: ':id', + title: 'Cloudbuild Run', +}); + +export const plugin = createPlugin({ + id: 'cloudbuild', + apis: [ + createApiFactory({ + api: cloudbuildApiRef, + deps: { googleAuthApi: googleAuthApiRef }, + factory({ googleAuthApi }) { + return new CloudbuildClient(googleAuthApi); + }, + }), + ], +}); diff --git a/plugins/cloudbuild/src/setupTests.ts b/plugins/cloudbuild/src/setupTests.ts new file mode 100644 index 0000000000..4b4cdbdaaf --- /dev/null +++ b/plugins/cloudbuild/src/setupTests.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '@testing-library/jest-dom'; + +require('jest-fetch-mock').enableMocks(); diff --git a/plugins/cost-insights/.eslintrc.js b/plugins/cost-insights/.eslintrc.js new file mode 100644 index 0000000000..13573efa9c --- /dev/null +++ b/plugins/cost-insights/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: [require.resolve('@backstage/cli/config/eslint')], +}; diff --git a/plugins/cost-insights/.npmrc b/plugins/cost-insights/.npmrc new file mode 100644 index 0000000000..214c29d139 --- /dev/null +++ b/plugins/cost-insights/.npmrc @@ -0,0 +1 @@ +registry=https://registry.npmjs.org/ diff --git a/plugins/cost-insights/README.md b/plugins/cost-insights/README.md new file mode 100644 index 0000000000..221f9f37d8 --- /dev/null +++ b/plugins/cost-insights/README.md @@ -0,0 +1,106 @@ +# Cost Insights + +Cost Insights is a plugin to help engineers visualize, understand and optimize their cloud costs. The Cost Insights page shows daily cost data for a team, trends over time, and comparisons with the business metrics you care about. + +At Spotify, we find that cloud costs are optimized organically when: + +- Engineers see cost data in their daily work (that is, in Backstage). +- It's clear when cloud costs need attention. +- The data is shown in software terms familiar to them. +- Alerts and recommendations are targeted and actionable. + +Cost Insights shows trends over time, at the granularity of your software deployments - rather than the cloud provider's concepts. It can be used to troubleshoot cost anomalies, and promote cost-saving infrastructure migrations. + +## Install + +```bash +yarn add @backstage/plugin-cost-insights +``` + +## Setup + +1. Configure `app-config.yaml`. See [Configuration](#configuration). + +2. Create a CostInsights client. Clients must implement the CostInsightsApi interface. See the [API file](https://github.com/spotify/backstage/blob/master/plugins/cost-insights/src/api/CostInsightsApi.ts) for required methods and documentation. + +```ts +// path/to/CostInsightsClient.ts +import { CostInsightsApi } from '@backstage/plugin-cost-insights'; + +export class CostInsightsClient implements CostInsightsApi { ... } +``` + +3. Import the client and the CostInsights plugin API to your Backstage instance. + +```ts +// packages/app/src/api.ts +import { createApiFactory } from '@backstage/core'; +import { costInsightsApiRef } from '@backstage/plugin-cost-insights'; +import { CostInsightsClient } from './path/to/file'; + +export const apis = [ + createApiFactory({ + api: costInsightsApiRef, + deps: {}, + factory: () => new CostInsightsClient(), + }), +]; +``` + +4. Add cost-insights to your Backstage plugins. + +```ts +// packages/app/src/plugins.ts +export { plugin as CostInsights } from '@backstage/plugin-cost-insights'; +``` + +## Configuration + +Cost Insights has only two required configuration fields: a map of cloud `products` for showing cost breakdowns and `engineerCost` - the average yearly cost of an engineer including benefits. Products must be defined as keys on the `products` field. + +You can optionally supply a product `icon` to display in Cost Insights navigation. See the [type file](https://github.com/spotify/backstage/blob/master/plugins/cost-insights/src/types/Icon.ts) for supported types and Material UI icon [mappings](https://github.com/spotify/backstage/blob/master/plugins/cost-insights/src/utils/navigation.tsx). + +**Note:** Product keys should be unique and camelCased. Backstage does not support underscores in configuration keys. + +### Basic + +```yaml +## ./app-config.yaml +costInsights: + engineerCost: 200000 + products: + productA: + name: Some Cloud Product ## required + icon: storage + productB: + name: Some Other Cloud Product + icon: data +``` + +### Metrics (Optional) + +In the `Cost Overview` panel, users can choose from a dropdown of business metrics to see costs as they relate to a metric, such as daily active users. Metrics must be defined as keys on the `metrics` field. A user-friendly name is **required**. Metrics will be provided to the `getDailyCost` and `getProjectCosts` API methods via the `metric` parameter. + +**Note:** Cost Insights displays daily cost without a metric by default. The dropdown text for this default can be overridden by assigning it a value on the `dailyCost` field. + +```yaml +## ./app-config.yaml +costInsights: + engineerCost: 200000 + products: + productA: + name: Some Cloud Product + icon: storage + productB: + name: Some Other Cloud Product + icon: data + metrics: + dailyCost: + name: Earth Rotation + metricA: + name: Metric A ## required + metricB: + name: Metric B + metricC: + name: Metric C +``` diff --git a/plugins/cost-insights/dev/index.tsx b/plugins/cost-insights/dev/index.tsx new file mode 100644 index 0000000000..812a5585d4 --- /dev/null +++ b/plugins/cost-insights/dev/index.tsx @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDevApp } from '@backstage/dev-utils'; +import { plugin } from '../src/plugin'; + +createDevApp().registerPlugin(plugin).render(); diff --git a/plugins/cost-insights/package.json b/plugins/cost-insights/package.json new file mode 100644 index 0000000000..96a74cb746 --- /dev/null +++ b/plugins/cost-insights/package.json @@ -0,0 +1,59 @@ +{ + "name": "@backstage/plugin-cost-insights", + "version": "0.1.1-alpha.23", + "main": "src/index.ts", + "types": "src/index.ts", + "license": "Apache-2.0", + "private": false, + "publishConfig": { + "access": "public", + "main": "dist/index.esm.js", + "types": "dist/index.d.ts" + }, + "scripts": { + "build": "backstage-cli plugin:build", + "start": "backstage-cli plugin:serve", + "lint": "backstage-cli lint", + "test": "backstage-cli test", + "diff": "backstage-cli plugin:diff", + "prepack": "backstage-cli prepack", + "postpack": "backstage-cli postpack", + "clean": "backstage-cli clean" + }, + "dependencies": { + "@backstage/config": "^0.1.1-alpha.23", + "@backstage/core": "^0.1.1-alpha.23", + "@backstage/test-utils": "^0.1.1-alpha.23", + "@backstage/theme": "^0.1.1-alpha.23", + "@material-ui/core": "^4.11.0", + "@material-ui/icons": "^4.9.1", + "@material-ui/lab": "4.0.0-alpha.45", + "@material-ui/styles": "^4.9.6", + "canvas": "^2.6.1", + "classnames": "^2.2.6", + "history": "^5.0.0", + "moment": "^2.27.0", + "qs": "^6.9.4", + "react": "^16.13.1", + "react-dom": "^16.13.1", + "react-router-dom": "6.0.0-beta.0", + "react-use": "^15.3.3", + "recharts": "^1.8.5" + }, + "devDependencies": { + "@backstage/cli": "^0.1.1-alpha.23", + "@backstage/dev-utils": "^0.1.1-alpha.23", + "@testing-library/jest-dom": "^5.10.1", + "@testing-library/react": "^10.4.1", + "@testing-library/user-event": "^12.0.7", + "@types/jest": "^26.0.7", + "@types/node": "^12.0.0", + "@types/recharts": "^1.8.14", + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/cost-insights/src/api/CostInsightsApi.ts b/plugins/cost-insights/src/api/CostInsightsApi.ts new file mode 100644 index 0000000000..b7628e2f9e --- /dev/null +++ b/plugins/cost-insights/src/api/CostInsightsApi.ts @@ -0,0 +1,115 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createApiRef } from '@backstage/core'; +import { Alert, Cost, Duration, Group, Project, ProductCost } from '../types'; + +export type CostInsightsApi = { + /** + * Get a list of groups the given user belongs to. These may be LDAP groups or similar + * organizational groups. Cost Insights is designed to show costs based on group membership; + * if a user has multiple groups, they are able to switch between groups to see costs for each. + * + * This method should be removed once the Backstage identity plugin provides the same concept. + */ + getUserGroups(userId: string): Promise; + + /** + * Get a list of cloud billing entities that belong to this group (projects in GCP, AWS has a + * similar concept in billing accounts). These act as filters for the displayed costs, users can + * choose whether they see all costs for a group, or those from a particular owned project. + */ + getGroupProjects(group: string): Promise; + + /** + * Get daily cost aggregations for a given group and interval timeframe. + * + * The return type includes an array of daily cost aggregations as well as statistics about the + * change in cost over the intervals. Calculating these statistics requires us to bucket costs + * into two or more time periods, hence a repeating interval format rather than just a start and + * end date. + * + * The rate of change in this comparison allows teams to reason about their cost growth (or + * reduction) and compare it to metrics important to the business. + * + * @param group The group id from getUserGroups or query parameters + * @param metric A metric from the cost-insights configuration in app-config.yaml. The backend + * should divide the actual daily cost by the corresponding metric for the same date. + * @param intervals An ISO 8601 repeating interval string, such as R2/P1M/2020-09-01 + * https://en.wikipedia.org/wiki/ISO_8601#Repeating_intervals + */ + getGroupDailyCost( + group: string, + metric: string | null, + intervals: string, + ): Promise; + + /** + * Get daily cost aggregations for a given billing entity (project in GCP, AWS has a similar + * concept in billing accounts) and interval timeframe. + * + * The return type includes an array of daily cost aggregations as well as statistics about the + * change in cost over the intervals. Calculating these statistics requires us to bucket costs + * into two or more time periods, hence a repeating interval format rather than just a start and + * end date. + * + * The rate of change in this comparison allows teams to reason about the project's cost growth + * (or reduction) and compare it to metrics important to the business. + * + * @param project The project id from getGroupProjects or query parameters + * @param metric A metric from the cost-insights configuration in app-config.yaml. The backend + * should divide the actual daily cost by the corresponding metric for the same date. + * @param intervals An ISO 8601 repeating interval string, such as R2/P1M/2020-09-01 + * https://en.wikipedia.org/wiki/ISO_8601#Repeating_intervals + */ + getProjectDailyCost( + project: string, + metric: string | null, + intervals: string, + ): Promise; + + /** + * Get cost aggregations for a particular cloud product and interval timeframe. This includes + * total cost for the product, as well as a breakdown of particular entities that incurred cost + * in this product. The type of entity depends on the product - it may be deployed services, + * storage buckets, managed database instances, etc. + * + * The time period is supplied as a Duration rather than intervals, since this is always expected + * to return data for two bucketed time period (e.g. month vs month, or quarter vs quarter). + * + * @param product The product from the cost-insights configuration in app-config.yaml + * @param group + * @param duration A time duration, such as P1M. See the Duration type for a detailed explanation + * of how the durations are interpreted in Cost Insights. + */ + getProductInsights( + product: string, + group: string, + duration: Duration, + ): Promise; + + /** + * Get current cost alerts for a given group. These show up as Action Items for the group on the + * Cost Insights page. Alerts may include cost-saving recommendations, such as infrastructure + * migrations, or cost-related warnings, such as an unexpected billing anomaly. + */ + getAlerts(group: string): Promise; +}; + +export const costInsightsApiRef = createApiRef({ + id: 'plugin.costinsights.service', + description: 'Provides cost data and alerts for the cost-insights plugin', +}); diff --git a/plugins/identity-backend/src/adapters/index.ts b/plugins/cost-insights/src/api/index.ts similarity index 94% rename from plugins/identity-backend/src/adapters/index.ts rename to plugins/cost-insights/src/api/index.ts index 357391a25b..d231570e9b 100644 --- a/plugins/identity-backend/src/adapters/index.ts +++ b/plugins/cost-insights/src/api/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './StaticJsonAdapter'; +export * from './CostInsightsApi'; diff --git a/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCard.test.tsx b/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCard.test.tsx new file mode 100644 index 0000000000..6e6f935137 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCard.test.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { renderInTestApp } from '@backstage/test-utils'; +import AlertActionCard from './AlertActionCard'; +import { AlertType, ProjectGrowthAlert } from '../../types'; +import { getAlertText } from '../../utils/alerts'; +import { MockScrollProvider } from '../../utils/tests'; + +const alert = { + id: AlertType.ProjectGrowth, + aggregation: [500000.8, 970502.8], + project: 'test-project', + periodStart: '2019-10-01', + periodEnd: '2020-03-31', + change: { ratio: 120, amount: 120000 }, + products: [], +} as ProjectGrowthAlert; + +describe('', () => { + it('Renders an alert', async () => { + const rendered = await renderInTestApp( + + , + , + ); + + expect(rendered.getByText('1')).toBeInTheDocument(); + const text = getAlertText(alert); + expect(text).toBeDefined(); + if (text) { + expect(rendered.getByText(text.title)).toBeInTheDocument(); + expect(rendered.getByText(text.subtitle)).toBeInTheDocument(); + } + }); +}); diff --git a/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCard.tsx b/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCard.tsx new file mode 100644 index 0000000000..f568f999f8 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCard.tsx @@ -0,0 +1,49 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { Avatar, Card, CardHeader } from '@material-ui/core'; +import { useScroll } from '../../hooks'; +import { Alert } from '../../types'; +import { getAlertText, getAlertNavigation } from '../../utils/alerts'; +import { + useAlertActionCardStyles as useStyles, + useAlertActionCardHeader as useHeaderStyles, +} from '../../utils/styles'; + +type AlertActionCardProps = { + alert: Alert; + number: number; +}; + +const AlertActionCard = ({ alert, number }: AlertActionCardProps) => { + const { scrollIntoView } = useScroll(getAlertNavigation(alert, number)); + const headerClasses = useHeaderStyles(); + const text = getAlertText(alert); + const classes = useStyles(); + + return ( + + {number}} + title={text?.title} + subheader={text?.subtitle} + /> + + ); +}; + +export default AlertActionCard; diff --git a/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCardList.tsx b/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCardList.tsx new file mode 100644 index 0000000000..4ddc26e040 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertActionCardList/AlertActionCardList.tsx @@ -0,0 +1,36 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { FC, Fragment } from 'react'; +import { Paper, Divider } from '@material-ui/core'; +import AlertActionCard from './AlertActionCard'; +import { Alert } from '../../types'; + +type AlertActionCardList = { + alerts: Array; +}; + +const AlertActionCardList: FC = ({ alerts }) => ( + + {alerts.map((alert, index) => ( + + + {index < alerts.length - 1 && } + + ))} + +); + +export default AlertActionCardList; diff --git a/plugins/cost-insights/src/components/AlertActionCardList/index.ts b/plugins/cost-insights/src/components/AlertActionCardList/index.ts new file mode 100644 index 0000000000..cccffd2985 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertActionCardList/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './AlertActionCardList'; diff --git a/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx b/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx new file mode 100644 index 0000000000..59dac3a758 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInsights/AlertInsights.tsx @@ -0,0 +1,51 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Grid } from '@material-ui/core'; +import AlertInsightsSection from './AlertInsightsSection'; +import AlertInsightsHeader from './AlertInsightsHeader'; +import { Alert } from '../../types'; +import { renderAlert } from '../../utils/alerts'; + +const title = "Your team's action items"; +const subtitle = + 'This section outlines suggested action items your team can address to improve cloud costs.'; + +type AlertInsightsProps = { + alerts: Array; +}; + +const AlertInsights = ({ alerts }: AlertInsightsProps) => ( + + + + + + {alerts.map((alert, index) => ( + + + + ))} + + +); + +export default AlertInsights; diff --git a/plugins/cost-insights/src/components/AlertInsights/AlertInsightsHeader.tsx b/plugins/cost-insights/src/components/AlertInsights/AlertInsightsHeader.tsx new file mode 100644 index 0000000000..b08ea01730 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInsights/AlertInsightsHeader.tsx @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography } from '@material-ui/core'; +import { useCostInsightsStyles as useStyles } from '../../utils/styles'; +import { useScroll } from '../../hooks'; +import { DefaultNavigation } from '../../utils/navigation'; + +type AlertInsightsHeaderProps = { + title: string; + subtitle: string; +}; + +const AlertInsightsHeader = ({ title, subtitle }: AlertInsightsHeaderProps) => { + const classes = useStyles(); + const { ScrollAnchor } = useScroll(DefaultNavigation.AlertInsightsHeader); + return ( + + + + {title}{' '} + + đŸŽ¯ + + + + {subtitle} + + + ); +}; + +export default AlertInsightsHeader; diff --git a/plugins/cost-insights/src/components/AlertInsights/AlertInsightsSection.tsx b/plugins/cost-insights/src/components/AlertInsights/AlertInsightsSection.tsx new file mode 100644 index 0000000000..c00d924cf2 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInsights/AlertInsightsSection.tsx @@ -0,0 +1,62 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { Box, Button } from '@material-ui/core'; +import AlertInsightsSectionHeader from './AlertInsightsSectionHeader'; +import { + getAlertButtonText, + getAlertText, + getAlertUrl, +} from '../../utils/alerts'; +import { Alert, Currency } from '../../types'; +import { useCurrency } from '../../hooks'; + +type AlertInsightsSectionProps = { + alert: Alert; + number: number; + render: (alert: Alert, currency: Currency) => JSX.Element; +}; + +const AlertInsightsSection = ({ + alert, + number, + render, +}: AlertInsightsSectionProps) => { + const [currency] = useCurrency(); + const text = getAlertText(alert); + const url = getAlertUrl(alert); + const buttonText = getAlertButtonText(alert); + + return ( + + + + + {/* */} + + {render(alert, currency)} + + ); +}; + +export default AlertInsightsSection; diff --git a/plugins/cost-insights/src/components/AlertInsights/AlertInsightsSectionHeader.tsx b/plugins/cost-insights/src/components/AlertInsights/AlertInsightsSectionHeader.tsx new file mode 100644 index 0000000000..5d5f94b9be --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInsights/AlertInsightsSectionHeader.tsx @@ -0,0 +1,55 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Avatar, Box, Typography, Grid } from '@material-ui/core'; +import { Alert } from '../../types'; +import { getAlertNavigation } from '../../utils/alerts'; +import { useAlertInsightsSectionStyles as useStyles } from '../../utils/styles'; +import { useScroll } from '../../hooks'; + +type AlertInsightsSectionHeaderProps = { + alert: Alert; + number: number; + title: string; + subtitle: string; +}; + +const AlertInsightsSectionHeader = ({ + alert, + number, + title, + subtitle, +}: AlertInsightsSectionHeaderProps) => { + const { ScrollAnchor } = useScroll(getAlertNavigation(alert, number)); + const classes = useStyles(); + return ( + + + + + {number} + + + {title} + {subtitle} + + + + ); +}; + +export default AlertInsightsSectionHeader; diff --git a/plugins/cost-insights/src/components/AlertInsights/index.ts b/plugins/cost-insights/src/components/AlertInsights/index.ts new file mode 100644 index 0000000000..5ed33f4e39 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInsights/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './AlertInsights'; diff --git a/plugins/cost-insights/src/components/AlertInstructionsLayout/AlertInstructionsLayout.tsx b/plugins/cost-insights/src/components/AlertInstructionsLayout/AlertInstructionsLayout.tsx new file mode 100644 index 0000000000..0a422c335a --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInstructionsLayout/AlertInstructionsLayout.tsx @@ -0,0 +1,61 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ReactNode } from 'react'; +import { Box, Button, Container, makeStyles } from '@material-ui/core'; +import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; +import { Header, Page, pageTheme } from '@backstage/core'; +import { CostInsightsThemeProvider } from '../CostInsightsPage/CostInsightsThemeProvider'; + +const useStyles = makeStyles(theme => ({ + root: { + gridArea: 'pageContent', + padding: theme.spacing(4), + }, +})); + +type AlertInstructionsLayoutProps = { + title: string; + children: ReactNode; +}; + +const AlertInstructionsLayout = ({ + title, + children, +}: AlertInstructionsLayoutProps) => { + const classes = useStyles(); + return ( + + +
+ + + + + {children} + + + + ); +}; + +export default AlertInstructionsLayout; diff --git a/plugins/cost-insights/src/components/AlertInstructionsLayout/index.ts b/plugins/cost-insights/src/components/AlertInstructionsLayout/index.ts new file mode 100644 index 0000000000..4063fe06d9 --- /dev/null +++ b/plugins/cost-insights/src/components/AlertInstructionsLayout/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './AlertInstructionsLayout'; diff --git a/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx b/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx new file mode 100644 index 0000000000..a39c5bafc2 --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChart.test.tsx @@ -0,0 +1,191 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { TooltipPayload } from 'recharts'; +import { fireEvent } from '@testing-library/react'; +import BarChart, { BarChartProps } from './BarChart'; +import { BarChartData, ResourceData } from '../../types'; +import { createMockEntity } from '../../utils/mockData'; +import { resourceSort } from '../../utils/sort'; +import { renderInTestApp } from '@backstage/test-utils'; +import { TooltipItemProps } from '../Tooltip'; +import { costInsightsLightTheme } from '../../utils/styles'; + +const MockEntities = [...Array(10)].map((_, index) => + createMockEntity(() => ({ + id: `test-id-${index + 1}`, + // grow resource costs linearly for testing + aggregation: [index * 1000, (index + 1) * 1000], + })), +); + +const MockBarChartData: BarChartData = { + previousFill: costInsightsLightTheme.palette.yellow, + currentFill: costInsightsLightTheme.palette.darkBlue, + previousName: 'Last Period', + currentName: 'Current Period', +}; + +const MockResources: ResourceData[] = MockEntities.map(entity => ({ + name: entity.id, + previous: entity.aggregation[0], + current: entity.aggregation[1], +})); + +const MockTooltipItem = (payload: TooltipPayload): TooltipItemProps => ({ + label: payload.name, + value: payload.value as string, + fill: payload.fill as string, +}); + +const renderWithProps = ({ + responsive = false, + displayAmount = 6, + barChartData = MockBarChartData, + getTooltipItem = MockTooltipItem, + resources = MockResources, +}: BarChartProps) => { + return renderInTestApp( + , + ); +}; + +describe('', () => { + it('Renders without exploding', async () => { + const rendered = await renderWithProps({} as BarChartProps); + expect(rendered.getByText('test-id-10')).toBeInTheDocument(); + }); + + it('Should display only 6 resources by default, sorted by cost', async () => { + const rendered = await renderWithProps({} as BarChartProps); + + MockResources.sort(resourceSort).forEach((resource, index) => { + if (index < 6) { + expect(rendered.getByText(resource.name!)).toBeInTheDocument(); + } else { + expect(rendered.queryByText(resource.name!)).not.toBeInTheDocument(); + } + }); + }); + + describe('Stepper', () => { + it('should not display stepper if displaying less than 6 resources', async () => { + const rendered = await renderWithProps({ + resources: MockResources.slice(0, 3), + } as BarChartProps); + expect( + rendered.queryByTestId('bar-chart-stepper'), + ).not.toBeInTheDocument(); + }); + + it('should display stepper if displaying more than 6 resources', async () => { + const rendered = await renderWithProps({} as BarChartProps); + expect(rendered.queryByTestId('bar-chart-stepper')).toBeInTheDocument(); + }); + + it('should display the next step button if resources are remaining', async () => { + const rendered = await renderWithProps({} as BarChartProps); + fireEvent.mouseEnter(rendered.getByTestId('bar-chart-wrapper')); + expect( + rendered.queryByTestId('bar-chart-stepper-button-back'), + ).not.toBeInTheDocument(); + expect( + rendered.queryByTestId('bar-chart-stepper-button-next'), + ).toBeInTheDocument(); + }); + + it('should display the correct amount of dots for the amount of resources', async () => { + const rendered = await renderWithProps({} as BarChartProps); + fireEvent.mouseEnter(rendered.getByTestId('bar-chart-wrapper')); + expect(rendered.queryAllByTestId('bar-chart-step').length).toEqual(2); + }); + + it('should not display the stepper or stepper buttons when the amount of resources is equal to the displayMax', async () => { + const MockEqualEntities = [...Array(5)].map(createMockEntity); + const MockEqualResources = MockEqualEntities.map(entity => ({ + name: entity.id, + previous: entity.aggregation[0], + current: entity.aggregation[1], + })); + + const rendered = await renderWithProps({ + displayAmount: 5, + resources: MockEqualResources, + } as BarChartProps); + expect( + rendered.queryByTestId('bar-chart-stepper'), + ).not.toBeInTheDocument(); + expect( + rendered.queryByTestId('bar-chart-stepper-button-back'), + ).not.toBeInTheDocument(); + expect( + rendered.queryByTestId('bar-chart-stepper-button-next'), + ).not.toBeInTheDocument(); + }); + + it('should display the correct resources while scrolling', async () => { + const rendered = await renderWithProps({ + displayAmount: 7, + } as BarChartProps); + + const sortedByCost = MockResources.sort(resourceSort); + + sortedByCost.slice(0, 7).forEach(resource => { + expect(rendered.getByText(resource.name!)).toBeInTheDocument(); + }); + + fireEvent.mouseEnter(rendered.getByTestId('bar-chart-wrapper')); + fireEvent.click(rendered.getByTestId('bar-chart-stepper-button-next')); + + sortedByCost.slice(7, 12).forEach(resource => { + expect(rendered.getByText(resource.name!)).toBeInTheDocument(); + }); + }); + + it('should display the correct amount of dots for a large amount of resources while scrolling', async () => { + const MockLargeEntities = [...Array(68)].map(createMockEntity); + const MockLargeResources = MockLargeEntities.map(entity => ({ + name: entity.id, + previous: entity.aggregation[0], + current: entity.aggregation[1], + })); + const rendered = await renderWithProps({ + resources: MockLargeResources, + } as BarChartProps); + + fireEvent.mouseEnter(rendered.getByTestId('bar-chart-wrapper')); + + const NextButton = rendered.getByTestId('bar-chart-stepper-button-next'); + + [...Array(9)].forEach(() => { + fireEvent.click(NextButton); + expect(rendered.queryAllByTestId('bar-chart-step').length).toEqual(10); + }); + + [...Array(2)].forEach(() => { + fireEvent.click(NextButton); + expect(rendered.queryAllByTestId('bar-chart-step').length).toEqual(2); + }); + }); + }); +}); diff --git a/plugins/cost-insights/src/components/BarChart/BarChart.tsx b/plugins/cost-insights/src/components/BarChart/BarChart.tsx new file mode 100644 index 0000000000..2f923304a8 --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChart.tsx @@ -0,0 +1,175 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useState, useCallback } from 'react'; +import { + Bar, + BarChart as RechartsBarChart, + CartesianGrid, + ContentRenderer, + TooltipProps, + ResponsiveContainer, + Tooltip as RechartsTooltip, + XAxis, + YAxis, + TooltipPayload, +} from 'recharts'; +import { Box, useTheme } from '@material-ui/core'; +import BarChartTick from './BarChartTick'; +import BarChartStepper from './BarChartStepper'; +import Tooltip, { TooltipItemProps } from '../Tooltip'; + +import { currencyFormatter } from '../../utils/formatters'; +import { + BarChartData, + Maybe, + notEmpty, + ResourceData, + DataKey, + CostInsightsTheme, +} from '../../types'; +import { useBarChartStyles } from '../../utils/styles'; +import { resourceSort } from '../../utils/sort'; + +export type BarChartProps = { + responsive?: boolean; + displayAmount?: number; + barChartData: BarChartData; + getTooltipItem: (payload: TooltipPayload) => Maybe; + resources: ResourceData[]; +}; + +const BarChart = ({ + responsive = true, + displayAmount = 6, + barChartData, + getTooltipItem, + resources, +}: BarChartProps) => { + const theme = useTheme(); + const styles = useBarChartStyles(theme); + const [activeChart, setActiveChart] = useState(false); + const [stepWindow, setStepWindow] = useState(() => [0, displayAmount]); + + const { previousFill, currentFill, previousName, currentName } = barChartData; + + const [stepStart, stepEnd] = stepWindow; + const steps = Math.ceil(resources.length / displayAmount); + const disableStepper = resources.length <= displayAmount; + + const sortedResources = resources + .sort(resourceSort) + .slice(stepStart, stepEnd); + + // Pin the domain to the largest value in the series. + // Intentially redundant - This could simply be derived from the first element in the already sorted list, + // but that may not be the case in the future when custom sorting is implemented. + const globalResourcesMax = resources.reduce( + (max, r: ResourceData) => Math.max(max, r.current, r.previous), + 0, + ); + + const onStepChange = useCallback( + (activeStep: number) => { + const start = activeStep * displayAmount; + const end = start + displayAmount; + if (end > resources.length) { + setStepWindow([start, resources.length]); + } else { + setStepWindow([start, end]); + } + }, + [setStepWindow, resources, displayAmount], + ); + + const handleChartEnter = () => setActiveChart(true); + + const handleChartLeave = () => setActiveChart(false); + + const renderTooltipContent: ContentRenderer = ({ + label, + payload, + }) => { + if (!(payload && typeof label === 'string')) return [null, null]; + const items = payload.map(getTooltipItem).filter(notEmpty); + return ; + }; + + return ( + + {/* Setting fixed values for height and width generates a console warning in testing but enables ResponsiveContainer to render its children. */} + + + + + + 0, globalResourcesMax]} + tick={{ fill: styles.axis.fill }} + /> + + + + + {!disableStepper && ( + + )} + + ); +}; + +export default BarChart; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx b/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx new file mode 100644 index 0000000000..3e12c18f90 --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChartLabel.tsx @@ -0,0 +1,51 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box } from '@material-ui/core'; +import { useBarChartLabelStyles } from '../../utils/styles'; + +type BarChartLabel = { + x: number; + y: number; + height: number; + width: number; + children?: React.ReactNode; +}; + +const BarChartLabel = ({ x, y, height, width, children }: BarChartLabel) => { + const classes = useBarChartLabelStyles(); + const translateX = width * -0.5; + const childArray = React.Children.toArray(children); + + return ( + + + {childArray[0]} + {childArray.slice(1)} + + + ); +}; + +export default BarChartLabel; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartStepper.tsx b/plugins/cost-insights/src/components/BarChart/BarChartStepper.tsx new file mode 100644 index 0000000000..27f7a589f3 --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChartStepper.tsx @@ -0,0 +1,115 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useEffect, useState } from 'react'; +import { Paper, Slide } from '@material-ui/core'; +import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; +import ChevronRightIcon from '@material-ui/icons/ChevronRight'; +import BarChartStepperButton from './BarChartStepperButton'; +import BarChartSteps from './BarChartSteps'; +import { useBarChartStepperStyles } from '../../utils/styles'; + +type BarChartStepperProps = { + disableScroll: boolean; + steps: number; + onChange: (activeStep: number) => void; +}; + +const BarChartStepper = ({ + steps, + disableScroll, + onChange, +}: BarChartStepperProps) => { + const classes = useBarChartStepperStyles(); + const [activeStep, setActiveStep] = useState(0); + + /* + * This calc determines how many active steps to display in the stepper. + * If the chart is displaying a large amount of resources, + * the total dots are truncated to 10. As the user clicks forward, + * eventually, there might be resources "left over" in excess of the ten dot limit. + * Once the user has reached that threshold, the difference should appear constant + * as the user clicks through the remaining resources and no extra dots should be displayed. + */ + + const diff = steps % 10; + const stepsRemaining = steps - activeStep <= diff ? diff : steps; + const displayedStep = activeStep % 10; + + useEffect(() => { + onChange(activeStep); + }, [activeStep, onChange]); + + const handleNext = () => { + setActiveStep(prevStep => prevStep + 1); + }; + + const handleBack = () => { + setActiveStep(prevStep => prevStep - 1); + }; + + const handleClick = (index: number) => { + setActiveStep(prevStep => { + const offset = index - (prevStep % 10); + return prevStep + offset; + }); + }; + + return ( + + + + + + + + + + + + + + ); +}; + +export default BarChartStepper; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartStepperButton.tsx b/plugins/cost-insights/src/components/BarChart/BarChartStepperButton.tsx new file mode 100644 index 0000000000..b668ffaa5c --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChartStepperButton.tsx @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { forwardRef, Ref } from 'react'; +import { ButtonBase, ButtonBaseProps } from '@material-ui/core'; +import { useBarChartStepperButtonStyles as useStyles } from '../../utils/styles'; + +interface BarChartStepperButtonProps extends ButtonBaseProps { + name: string; + children?: React.ReactNode; +} + +const BarChartStepperButton = forwardRef( + ( + { name, children, ...buttonBaseProps }: BarChartStepperButtonProps, + ref: Ref, + ) => { + const classes = useStyles(); + return ( + + {children} + + ); + }, +); + +export default BarChartStepperButton; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx b/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx new file mode 100644 index 0000000000..1ca0c7082a --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChartSteps.tsx @@ -0,0 +1,52 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { ButtonBase } from '@material-ui/core'; +import { useBarChartStepperStyles as useStyles } from '../../utils/styles'; + +export type BarChartSteps = { + steps: number; + activeStep: number; + onClick: (index: number) => void; +}; + +const BarChartSteps = ({ steps, activeStep, onClick }: BarChartSteps) => { + const classes = useStyles(); + const handleOnClick = (index: number) => ( + event: React.MouseEvent, + ) => { + event.preventDefault(); + onClick(index); + }; + + return ( +
+ {[...new Array(steps)].map((_, index) => ( + +
+ + ))} +
+ ); +}; + +export default BarChartSteps; diff --git a/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx b/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx new file mode 100644 index 0000000000..99158c4573 --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/BarChartTick.tsx @@ -0,0 +1,48 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import BarChartLabel from './BarChartLabel'; + +type BarChartTickProps = { + x: number; + y: number; + height: number; + width: number; + payload: { + value: any; + }; + visibleTicksCount: number; +}; + +export const BarChartTick = ({ + x, + y, + height, + width, + payload, + visibleTicksCount, +}: BarChartTickProps) => { + const gutterWidth = 5; + const labelWidth = width / visibleTicksCount - gutterWidth * 2; + return ( + + {!payload.value ? 'Unlabeled' : payload.value} + + ); +}; + +export default BarChartTick; diff --git a/plugins/cost-insights/src/components/BarChart/index.ts b/plugins/cost-insights/src/components/BarChart/index.ts new file mode 100644 index 0000000000..255bd2b3d8 --- /dev/null +++ b/plugins/cost-insights/src/components/BarChart/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './BarChart'; diff --git a/plugins/cost-insights/src/components/CopyUrlToClipboard/CopyUrlToClipboard.tsx b/plugins/cost-insights/src/components/CopyUrlToClipboard/CopyUrlToClipboard.tsx new file mode 100644 index 0000000000..c801eb86a5 --- /dev/null +++ b/plugins/cost-insights/src/components/CopyUrlToClipboard/CopyUrlToClipboard.tsx @@ -0,0 +1,70 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useEffect, useState } from 'react'; +import { useLocation } from 'react-router-dom'; +import { useCopyToClipboard } from 'react-use'; +import { Tooltip, IconButton } from '@material-ui/core'; +import AssignmentOutlinedIcon from '@material-ui/icons/AssignmentOutlined'; +import AssignmentTurnedInOutlinedIcon from '@material-ui/icons/AssignmentTurnedInOutlined'; +import SentimentVeryDissatisfiedIcon from '@material-ui/icons/SentimentVeryDissatisfied'; + +const ClipboardMessage = { + default: 'Copy URL to clipboard', + success: 'Copied!', + error: "Couldn't copy to clipboard", +}; + +const CopyUrlToClipboard = () => { + const location = useLocation(); + const [state, copyToClipboard] = useCopyToClipboard(); + const [copied, setCopied] = useState(false); + + const origin = window.location.origin; + const pathname = location.pathname; + const search = location.search; + const url = `${origin}${pathname}${search}`; + + useEffect(() => { + if (state.error) { + setCopied(false); + } else if (state.value) { + setCopied(true); + setTimeout(setCopied, 1500, false); + } + }, [state]); + + let text = ClipboardMessage.default; + let Icon = AssignmentOutlinedIcon; + + if (state.error) { + text = ClipboardMessage.error; + Icon = SentimentVeryDissatisfiedIcon; + } else if (copied) { + text = ClipboardMessage.success; + Icon = AssignmentTurnedInOutlinedIcon; + } + + return ( + + copyToClipboard(url)}> + + + + ); +}; + +export default CopyUrlToClipboard; diff --git a/plugins/cost-insights/src/components/CopyUrlToClipboard/index.ts b/plugins/cost-insights/src/components/CopyUrlToClipboard/index.ts new file mode 100644 index 0000000000..15e2318c56 --- /dev/null +++ b/plugins/cost-insights/src/components/CopyUrlToClipboard/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CopyUrlToClipboard'; diff --git a/plugins/cost-insights/src/components/CostGrowth/CostGrowth.test.tsx b/plugins/cost-insights/src/components/CostGrowth/CostGrowth.test.tsx new file mode 100644 index 0000000000..6302d9929f --- /dev/null +++ b/plugins/cost-insights/src/components/CostGrowth/CostGrowth.test.tsx @@ -0,0 +1,113 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ReactNode } from 'react'; +import { renderInTestApp } from '@backstage/test-utils'; +import CostGrowth from './CostGrowth'; +import { + defaultCurrencies, + Currency, + CurrencyType, + Duration, + findAlways, +} from '../../types'; +import { MockConfigProvider, MockCurrencyProvider } from '../../utils/tests'; + +const engineers = findAlways(defaultCurrencies, c => c.kind === null); +const usd = findAlways(defaultCurrencies, c => c.kind === CurrencyType.USD); +const carbon = findAlways( + defaultCurrencies, + c => c.kind === CurrencyType.CarbonOffsetTons, +); + +const MockContext = ({ + children, + currency, + engineerCost, +}: { + children: ReactNode; + currency: Currency; + engineerCost: number; +}) => ( + + + {children} + + +); + +describe.each` + engineerCost | ratio | amount | expected + ${200_000} | ${0} | ${0} | ${'Negligible'} + ${200_000} | ${0} | ${8_333} | ${'Negligible'} + ${200_000} | ${0.000000001} | ${8_334} | ${`0% or ~1 ${engineers.unit}`} + ${200_000} | ${-0.000000001} | ${10_000} | ${`0% or ~1 ${engineers.unit}`} + ${200_000} | ${-0.8} | ${10_000} | ${`80% or ~1 ${engineers.unit}`} + ${200_000} | ${3} | ${600_000} | ${`300% or ~36 ${engineers.unit}s`} +`('', ({ engineerCost, ratio, amount, expected }) => { + it(`formats ${engineers.unit}s correctly for ${expected}`, async () => { + const { getByText } = await renderInTestApp( + + + , + ); + expect(getByText(expected)).toBeInTheDocument(); + }); +}); + +describe.each` + engineerCost | ratio | amount | expected + ${200_000} | ${0} | ${0} | ${'Negligible'} + ${200_000} | ${0} | ${8_333} | ${'Negligible'} + ${200_000} | ${0.000000001} | ${8_334} | ${'0% or ~$8,334'} + ${200_000} | ${-0.000000001} | ${10_000} | ${'0% or ~$10,000'} + ${200_000} | ${-0.8} | ${10_000} | ${'80% or ~$10,000'} + ${200_000} | ${3} | ${600_000} | ${'300% or ~$600,000'} +`('', ({ engineerCost, ratio, amount, expected }) => { + it(`formats ${usd.unit}s correctly for ${expected}`, async () => { + const { getByText } = await renderInTestApp( + + + , + ); + expect(getByText(expected)).toBeInTheDocument(); + }); +}); + +describe.each` + engineerCost | ratio | amount | expected + ${200_000} | ${0} | ${0} | ${'Negligible'} + ${200_000} | ${0} | ${8_333} | ${'Negligible'} + ${200_000} | ${0.000000001} | ${8_334} | ${`0% or ~2,381 ${carbon.unit}s`} + ${200_000} | ${-0.000000001} | ${10_000} | ${`0% or ~2,857 ${carbon.unit}s`} + ${200_000} | ${-0.8} | ${10_000} | ${`80% or ~2,857 ${carbon.unit}s`} + ${200_000} | ${3} | ${600_000} | ${`300% or ~171,429 ${carbon.unit}s`} +`('', ({ engineerCost, ratio, amount, expected }) => { + it(`formats ${carbon.unit}s correctly for ${expected}`, async () => { + const { getByText } = await renderInTestApp( + + + , + ); + expect(getByText(expected)).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx b/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx new file mode 100644 index 0000000000..0c0db2d62c --- /dev/null +++ b/plugins/cost-insights/src/components/CostGrowth/CostGrowth.tsx @@ -0,0 +1,74 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import classnames from 'classnames'; +import { + ChangeStatistic, + CurrencyType, + Duration, + EngineerThreshold, + Growth, + growthOf, + rateOf, +} from '../../types'; +import { useCostGrowthStyles as useStyles } from '../../utils/styles'; +import { formatPercent, formatCurrency } from '../../utils/formatters'; +import { indefiniteArticleOf } from '../../utils/grammar'; +import { useConfig, useCurrency } from '../../hooks'; + +export type CostGrowthProps = { + change: ChangeStatistic; + duration: Duration; +}; + +const CostGrowth = ({ change, duration }: CostGrowthProps) => { + const styles = useStyles(); + const { engineerCost } = useConfig(); + const [currency] = useCurrency(); + + // Only display costs in absolute values + const amount = Math.abs(change.amount); + const ratio = Math.abs(change.ratio); + + const rate = rateOf(engineerCost, duration); + const engineers = amount / rate; + const converted = amount / (currency.rate ?? rate); + + // Determine if growth is significant enough to highlight + const growth = growthOf(engineers, change.ratio); + const classes = classnames({ + [styles.excess]: growth === Growth.Excess, + [styles.savings]: growth === Growth.Savings, + }); + + const percent = formatPercent(ratio); + + let cost = `${percent} or ~${formatCurrency(converted, currency.unit)}`; + // Always display the converted value but use the cost in engineers + // to determine negligibility, as costs should be time-period aware + if (engineers < EngineerThreshold) { + cost = 'Negligible'; + } else if (currency.kind === CurrencyType.USD) { + cost = `${percent} or ~${currency.prefix}${formatCurrency(converted)}`; + } else if (amount < 1) { + cost = `less than ${indefiniteArticleOf(['a', 'an'], currency.unit)}`; + } + + return {cost}; +}; + +export default CostGrowth; diff --git a/plugins/cost-insights/src/components/CostGrowth/index.ts b/plugins/cost-insights/src/components/CostGrowth/index.ts new file mode 100644 index 0000000000..3cd809ee49 --- /dev/null +++ b/plugins/cost-insights/src/components/CostGrowth/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostGrowth'; diff --git a/plugins/cost-insights/src/components/CostInsightsHeader/CostInsightsHeader.test.tsx b/plugins/cost-insights/src/components/CostInsightsHeader/CostInsightsHeader.test.tsx new file mode 100644 index 0000000000..8af5091188 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsHeader/CostInsightsHeader.test.tsx @@ -0,0 +1,95 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import CostInsightsHeader from './CostInsightsHeader'; +import { renderInTestApp } from '@backstage/test-utils'; +import { + ApiProvider, + ApiRegistry, + IdentityApi, + identityApiRef, +} from '@backstage/core'; +import React from 'react'; + +describe('', () => { + const identityApi: Partial = { + getProfile: () => ({ + email: 'test-email@example.com', + displayName: 'User 1', + }), + }; + + const apis = ApiRegistry.from([[identityApiRef, identityApi]]); + + it('Shows nothing to do when no alerts exist', async () => { + const rendered = await renderInTestApp( + + + , + ); + + expect(rendered.queryByText(/doing great/)).toBeInTheDocument(); + }); + + it('Shows work to do when alerts > 1', async () => { + const rendered = await renderInTestApp( + + + , + ); + expect(rendered.queryByText(/few things/)).toBeInTheDocument(); + }); + + it('Handles grammar with a single alert', async () => { + const rendered = await renderInTestApp( + + + , + ); + + expect(rendered.queryByText(/things/)).not.toBeInTheDocument(); + expect(rendered.queryByText(/one thing/)).toBeInTheDocument(); + }); + + it('Shows no costs when hasCostData is false', async () => { + const rendered = await renderInTestApp( + + + , + ); + expect(rendered.queryByText(/this is awkward/)).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/CostInsightsHeader/CostInsightsHeader.tsx b/plugins/cost-insights/src/components/CostInsightsHeader/CostInsightsHeader.tsx new file mode 100644 index 0000000000..57fa26b5fc --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsHeader/CostInsightsHeader.tsx @@ -0,0 +1,136 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Typography } from '@material-ui/core'; +import { identityApiRef, ProfileInfo, useApi } from '@backstage/core'; +import { useCostInsightsStyles } from '../../utils/styles'; +import { Group } from '../../types'; + +function name(profile: ProfileInfo | undefined): string { + return profile?.displayName || 'Mysterious Stranger'; +} + +type CostInsightsHeaderProps = { + owner: string; + groups: Group[]; + hasCostData: boolean; + alerts: number; +}; + +const CostInsightsHeader = (props: CostInsightsHeaderProps) => { + if (!props.hasCostData) { + return ; + } + if (props.alerts) { + return ; + } + return ; +}; + +const CostInsightsHeaderNoData = ({ + owner, + groups, +}: CostInsightsHeaderProps) => { + const profile = useApi(identityApiRef).getProfile(); + const classes = useCostInsightsStyles(); + const hasMultipleGroups = groups.length > 1; + + return ( + <> + + + đŸ˜ŗ + {' '} + Well this is awkward + + + Hey, {name(profile)}! {owner} doesn't seem to have any + cloud costs. + + {hasMultipleGroups && ( + + Maybe we picked the wrong team, choose another from the menu above? + + )} + + ); +}; + +const CostInsightsHeaderAlerts = ({ + owner, + alerts, +}: CostInsightsHeaderProps) => { + const profile = useApi(identityApiRef).getProfile(); + const classes = useCostInsightsStyles(); + + return ( + <> + + + 🔎 + {' '} + You have {alerts} thing{alerts > 1 && 's'} to look into + + + Hey, {name(profile)}! We've identified{' '} + {alerts > 1 ? 'a few things ' : 'one thing '} + {owner} should look into next. + + + ); +}; + +const CostInsightsHeaderNoAlerts = ({ owner }: CostInsightsHeaderProps) => { + const profile = useApi(identityApiRef).getProfile(); + const classes = useCostInsightsStyles(); + + return ( + <> + + + 👍 + {' '} + Your team is doing great + + + Hey, {name(profile)}! {owner} is doing well. No major + changes this month. + + + ); +}; + +export const CostInsightsHeaderNoGroups = () => { + const profile = useApi(identityApiRef).getProfile(); + const classes = useCostInsightsStyles(); + return ( + <> + + + đŸ˜ŗ + {' '} + Well this is awkward + + + Hey, {name(profile)}! It doesn't look like you belong to any + teams. + + + ); +}; + +export default CostInsightsHeader; diff --git a/plugins/cost-insights/src/components/CostInsightsHeader/index.ts b/plugins/cost-insights/src/components/CostInsightsHeader/index.ts new file mode 100644 index 0000000000..8e7ddcc9c8 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsHeader/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default, CostInsightsHeaderNoGroups } from './CostInsightsHeader'; diff --git a/plugins/cost-insights/src/components/CostInsightsLayout/CostInsightsLayout.tsx b/plugins/cost-insights/src/components/CostInsightsLayout/CostInsightsLayout.tsx new file mode 100644 index 0000000000..61bf7ac22f --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsLayout/CostInsightsLayout.tsx @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { makeStyles } from '@material-ui/core'; +import { Header, Page, pageTheme } from '@backstage/core'; +import { Group } from '../../types'; +import CostInsightsTabs from '../CostInsightsTabs'; + +const useStyles = makeStyles(theme => ({ + root: { + gridArea: 'pageContent', + }, + header: { + boxShadow: 'none', + }, + content: { + padding: theme.spacing(4), + }, +})); + +type CostInsightsLayoutProps = { + title?: string; + groups: Group[]; + children?: React.ReactNode; +}; + +const CostInsightsLayout = ({ groups, children }: CostInsightsLayoutProps) => { + const classes = useStyles(); + return ( + +
+
+ +
{children}
+
+ + ); +}; + +export default CostInsightsLayout; diff --git a/plugins/cost-insights/src/components/CostInsightsLayout/index.ts b/plugins/cost-insights/src/components/CostInsightsLayout/index.ts new file mode 100644 index 0000000000..dd35eb2855 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsLayout/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostInsightsLayout'; diff --git a/plugins/cost-insights/src/components/CostInsightsNavigation/CostInsightsNavigation.test.tsx b/plugins/cost-insights/src/components/CostInsightsNavigation/CostInsightsNavigation.test.tsx new file mode 100644 index 0000000000..3ec2828029 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsNavigation/CostInsightsNavigation.test.tsx @@ -0,0 +1,79 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { default as HappyFace } from '@material-ui/icons/SentimentSatisfiedAlt'; +import { renderInTestApp } from '@backstage/test-utils'; +import CostInsightsNavigation from './CostInsightsNavigation'; +import { defaultCurrencies, Metric, Product, Icon } from '../../types'; +import { MockConfigProvider, MockScrollProvider } from '../../utils/tests'; +import { getDefaultNavigationItems } from '../../utils/navigation'; + +const mockIcons: Icon[] = [ + { + kind: 'some-product', + component: , + }, +]; + +const mockProducts: Product[] = [ + { + kind: 'some-product', + name: 'Some Product', + }, +]; + +const mockMetrics: Metric[] = [ + { + kind: 'some-metric', + name: 'Some Metric', + }, +]; + +const renderWrapped = (children: React.ReactNode) => + renderInTestApp( + + {children} + , + ); + +describe('', () => { + it('should render each navigation item', async () => { + const { getByText } = await renderWrapped( + , + ); + getDefaultNavigationItems(3) + .map(item => item.title) + .concat(mockProducts.map(p => p.name)) + .forEach(name => expect(getByText(name)).toBeInTheDocument()); + }); + + it('should not display action items navigation if there are no action items', async () => { + const rendered = await renderWrapped(); + expect(rendered.queryByText(/Action Items/)).not.toBeInTheDocument(); + }); + + it('should display the correct amount of action items in the badge', async () => { + const rendered = await renderWrapped(); + expect(rendered.getByText(/3/)).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/CostInsightsNavigation/CostInsightsNavigation.tsx b/plugins/cost-insights/src/components/CostInsightsNavigation/CostInsightsNavigation.tsx new file mode 100644 index 0000000000..fdbabe0402 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsNavigation/CostInsightsNavigation.tsx @@ -0,0 +1,97 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { + MenuList, + MenuItem, + ListItemIcon, + ListItemText, + Typography, + Badge, +} from '@material-ui/core'; +import { useNavigationStyles } from '../../utils/styles'; +import { useConfig, useScroll } from '../../hooks'; +import { findAlways } from '../../types'; +import { + DefaultNavigation, + NavigationItem, + getDefaultNavigationItems, +} from '../../utils/navigation'; + +type CostInsightsNavigationProps = { + alerts: number; +}; + +const CostInsightsNavigation = ({ alerts }: CostInsightsNavigationProps) => { + const classes = useNavigationStyles(); + const { products, icons } = useConfig(); + + const productNavigationItems: NavigationItem[] = products.map(product => ({ + navigation: product.kind, + icon: findAlways(icons, i => i.kind === product.kind).component, + title: product.name, + })); + + const navigationItems = getDefaultNavigationItems(alerts).concat( + productNavigationItems, + ); + + return ( + + {navigationItems.map((item: NavigationItem) => ( + + {React.cloneElement(item.icon, { + className: classes.navigationIcon, + })} + + ) : ( + React.cloneElement(item.icon, { + className: classes.navigationIcon, + }) + ) + } + title={item.title} + /> + ))} + + ); +}; + +const NavigationMenuItem = ({ navigation, icon, title }: NavigationItem) => { + const classes = useNavigationStyles(); + const { scrollIntoView } = useScroll(navigation); + return ( + + {icon} + {title}} + /> + + ); +}; + +export default CostInsightsNavigation; diff --git a/plugins/cost-insights/src/components/CostInsightsNavigation/index.ts b/plugins/cost-insights/src/components/CostInsightsNavigation/index.ts new file mode 100644 index 0000000000..6c32ba7677 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsNavigation/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostInsightsNavigation'; diff --git a/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsPage.tsx b/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsPage.tsx new file mode 100644 index 0000000000..c426eff8bc --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsPage.tsx @@ -0,0 +1,249 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useCallback, useEffect, useState } from 'react'; +import { Box, Container, Divider, Grid } from '@material-ui/core'; +import { Progress, useApi, featureFlagsApiRef } from '@backstage/core'; +import { default as MaterialAlert } from '@material-ui/lab/Alert'; +import { costInsightsApiRef } from '../../api'; +import AlertActionCardList from '../AlertActionCardList'; +import AlertInsights from '../AlertInsights'; +import CostInsightsLayout from '../CostInsightsLayout'; +import CopyUrlToClipboard from '../CopyUrlToClipboard'; +import CurrencySelect from '../CurrencySelect'; +import WhyCostsMatter from '../WhyCostsMatter'; +import CostInsightsHeader, { + CostInsightsHeaderNoGroups, +} from '../CostInsightsHeader'; +import CostInsightsNavigation from '../CostInsightsNavigation'; +import CostOverviewCard from '../CostOverviewCard'; +import ProductInsights from '../ProductInsights'; +import CostInsightsSupportButton from '../CostInsightsSupportButton'; +import { + useLoading, + useFilters, + useGroups, + useCurrency, + useConfig, +} from '../../hooks'; +import { Alert, Cost, intervalsOf, Maybe, Project } from '../../types'; +import { mapLoadingToProps } from './selector'; + +const CostInsightsPage = () => { + const flags = useApi(featureFlagsApiRef).getFlags(); + // There is not currently a UI to set feature flags + // flags.set('cost-insights-currencies', FeatureFlagState.On); + const client = useApi(costInsightsApiRef); + const { currencies } = useConfig(); + const groups = useGroups(); + const [currency, setCurrency] = useCurrency(); + const [projects, setProjects] = useState>(null); + const [dailyCost, setDailyCost] = useState>(null); + const [alerts, setAlerts] = useState>(null); + const [error, setError] = useState>(null); + + const { pageFilters } = useFilters(p => p); + const { + loadingActions, + loadingGroups, + loadingInitial, + dispatchInitial, + dispatchInsights, + dispatchNone, + } = useLoading(mapLoadingToProps); + + /* eslint-disable react-hooks/exhaustive-deps */ + // The dispatchLoading functions are derived from loading state using mapLoadingToProps, to + // provide nicer props for the component. These are re-derived whenever loading state changes, + // which causes an infinite loop as product panels load and re-trigger the useEffect below. + // Since the functions don't change, we can memoize - but we trigger the same loop if we satisfy + // exhaustive-deps by including the function itself in dependencies. + + const dispatchLoadingInitial = useCallback(dispatchInitial, []); + const dispatchLoadingInsights = useCallback(dispatchInsights, []); + const dispatchLoadingNone = useCallback(dispatchNone, []); + /* eslint-enable react-hooks/exhaustive-deps */ + + useEffect(() => { + async function getInsights() { + setError(null); + try { + if (pageFilters.group) { + dispatchLoadingInsights(true); + const [ + fetchedProjects, + fetchedCosts, + fetchedAlerts, + ] = await Promise.all([ + client.getGroupProjects(pageFilters.group), + pageFilters.project + ? client.getProjectDailyCost( + pageFilters.project, + pageFilters.metric, + intervalsOf(pageFilters.duration), + ) + : client.getGroupDailyCost( + pageFilters.group, + pageFilters.metric, + intervalsOf(pageFilters.duration), + ), + client.getAlerts(pageFilters.group), + ]); + setProjects(fetchedProjects); + setDailyCost(fetchedCosts); + setAlerts(fetchedAlerts); + } else { + dispatchLoadingNone(loadingActions); + } + } catch (e) { + setError(e); + dispatchLoadingNone(loadingActions); + } finally { + dispatchLoadingInitial(false); + dispatchLoadingInsights(false); + } + } + + // Wait for user groups to finish loading + if (!loadingGroups) { + getInsights(); + } + }, [ + client, + pageFilters, + loadingGroups, + dispatchLoadingInsights, + dispatchLoadingInitial, + dispatchLoadingNone, + loadingActions, + ]); + + if (loadingInitial) { + return ; + } + + if (error) { + return {error.message}; + } + + // Loaded but no groups found for the user + if (!pageFilters.group) { + return ( + + + + + + + + + + + + + + ); + } + + // These should be defined, alerts can be an empty array but that's truthy + if (!dailyCost || !alerts) { + return ( + {`Error: Could not fetch cost insights data for team ${pageFilters.group}`} + ); + } + + return ( + + + + + + + + + + {!!flags.get('cost-insights-currencies') && ( + + + + )} + + + + + + + + + {!!alerts.length && ( + <> + + + + + + + + )} + + + {!!dailyCost.aggregation.length && ( + + )} + + + + + {!!alerts?.length && ( + + + + )} + + {!alerts.length && } + + + + + + + + + + + ); +}; + +export default CostInsightsPage; diff --git a/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsPageRoot.tsx b/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsPageRoot.tsx new file mode 100644 index 0000000000..b2276481b2 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsPageRoot.tsx @@ -0,0 +1,45 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import CostInsightsPage from './CostInsightsPage'; +import { FilterProvider } from '../../hooks/useFilters'; +import { LoadingProvider } from '../../hooks/useLoading'; +import { GroupsProvider } from '../../hooks/useGroups'; +import { CurrencyProvider } from '../../hooks/useCurrency'; +import { ScrollProvider } from '../../hooks/useScroll'; +import { ConfigProvider } from '../../hooks/useConfig'; +import { CostInsightsThemeProvider } from './CostInsightsThemeProvider'; + +const CostInsightsPageRoot = () => ( + + + + + + + + + + + + + + + +); + +export default CostInsightsPageRoot; diff --git a/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsThemeProvider.tsx b/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsThemeProvider.tsx new file mode 100644 index 0000000000..cecb076d35 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsPage/CostInsightsThemeProvider.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { createMuiTheme, ThemeProvider } from '@material-ui/core'; +import { BackstageTheme } from '@backstage/theme'; +import { + costInsightsDarkTheme, + costInsightsLightTheme, +} from '../../utils/styles'; +import { CostInsightsTheme } from '../../types'; + +interface CostInsightsThemeProviderProps { + children?: React.ReactNode; +} + +export const CostInsightsThemeProvider = ({ + children, +}: CostInsightsThemeProviderProps) => { + return ( + + createMuiTheme({ + ...theme, + palette: { + ...theme.palette, + ...(theme.palette.type === 'dark' + ? costInsightsDarkTheme.palette + : costInsightsLightTheme.palette), + }, + }) as CostInsightsTheme + } + > + {children} + + ); +}; diff --git a/plugins/cost-insights/src/components/CostInsightsPage/index.ts b/plugins/cost-insights/src/components/CostInsightsPage/index.ts new file mode 100644 index 0000000000..67d5eb5daa --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsPage/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostInsightsPageRoot'; diff --git a/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx b/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx new file mode 100644 index 0000000000..51db47c082 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsPage/selector.tsx @@ -0,0 +1,42 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MapLoadingToProps } from '../../hooks'; +import { getResetState, DefaultLoadingAction } from '../../types'; + +type CostInsightsPageLoadingProps = { + loadingActions: Array; + loadingGroups: boolean; + loadingInitial: boolean; + dispatchInitial: (isLoading: boolean) => void; + dispatchInsights: (isLoading: boolean) => void; + dispatchNone: (loadingActions: string[]) => void; +}; + +export const mapLoadingToProps: MapLoadingToProps = ({ + state, + actions, + dispatch, +}) => ({ + loadingActions: actions, + loadingGroups: state[DefaultLoadingAction.UserGroups], + loadingInitial: state[DefaultLoadingAction.CostInsightsInitial], + dispatchInitial: (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsInitial]: isLoading }), + dispatchInsights: (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.CostInsightsPage]: isLoading }), + dispatchNone: (loadingActions: string[]) => + dispatch(getResetState(loadingActions)), +}); diff --git a/plugins/cost-insights/src/components/CostInsightsSupportButton/CostInsightsSupportButton.tsx b/plugins/cost-insights/src/components/CostInsightsSupportButton/CostInsightsSupportButton.tsx new file mode 100644 index 0000000000..c8e7fdac97 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsSupportButton/CostInsightsSupportButton.tsx @@ -0,0 +1,28 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { SupportButton } from '@backstage/core'; + +const CostInsightsSupportButton = () => { + return ( + + Insights into cloud costs for your organization + + ); +}; + +export default CostInsightsSupportButton; diff --git a/plugins/cost-insights/src/components/CostInsightsSupportButton/index.ts b/plugins/cost-insights/src/components/CostInsightsSupportButton/index.ts new file mode 100644 index 0000000000..eab947c1be --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsSupportButton/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostInsightsSupportButton'; diff --git a/plugins/cost-insights/src/components/CostInsightsTabs/CostInsightsTabs.test.tsx b/plugins/cost-insights/src/components/CostInsightsTabs/CostInsightsTabs.test.tsx new file mode 100644 index 0000000000..0859ad18ce --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsTabs/CostInsightsTabs.test.tsx @@ -0,0 +1,104 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import CostInsightsTabs from './CostInsightsTabs'; +import UserEvent from '@testing-library/user-event'; +import { Group, defaultCurrencies } from '../../types'; +import { MockFilterProvider, MockConfigProvider } from '../../utils/tests'; +import { LoadingContext } from '../../hooks/useLoading'; +import { renderInTestApp } from '@backstage/test-utils'; +import { mockDefaultState } from '../../utils/mockData'; + +const mockSetPageFilters = jest.fn(); +const mockLoadingDispatch = jest.fn(); + +const mockGroups: Group[] = [ + { + id: 'test-group-1', + }, + { + id: 'test-group-2', + }, + { + id: 'test-group-3', + }, +]; + +describe('', () => { + const renderWrapped = (children: React.ReactNode) => + renderInTestApp( + + + + {children} + + + , + ); + + it('Does NOT display the tabs bar if owner belongs to less than two GROUPS', async () => { + const oneGroup: Group[] = [{ id: 'test-group-1' }]; + const rendered = await renderWrapped( + , + ); + expect( + rendered.container.querySelector('.cost-insights-tabs'), + ).not.toBeInTheDocument(); + }); + + it('Displays the correct number of groups in the groups tab', async () => { + const rendered = await renderWrapped( + , + ); + expect(rendered.getByText('3 teams')).toBeInTheDocument(); + }); + + it('Applies the correct group filter when selected', async () => { + const selectedGroup = expect.objectContaining({ group: 'test-group-1' }); + const rendered = await renderWrapped( + , + ); + UserEvent.click(rendered.getByTestId('cost-insights-groups-tab')); + UserEvent.click(rendered.getByTestId('test-group-1')); + expect(mockSetPageFilters).toHaveBeenCalledWith(selectedGroup); + }); + + it('Displays the correct group names in the menu', async () => { + const rendered = await renderWrapped( + , + ); + UserEvent.click(rendered.getByTestId('cost-insights-groups-tab')); + mockGroups.forEach(group => + expect(rendered.getByText(group.id)).toBeInTheDocument(), + ); + }); +}); diff --git a/plugins/cost-insights/src/components/CostInsightsTabs/CostInsightsTabs.tsx b/plugins/cost-insights/src/components/CostInsightsTabs/CostInsightsTabs.tsx new file mode 100644 index 0000000000..3b86aa79ef --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsTabs/CostInsightsTabs.tsx @@ -0,0 +1,111 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useState } from 'react'; +import { Menu, MenuItem, Tab, Tabs, Typography } from '@material-ui/core'; +import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; +import { mapLoadingToProps, mapFiltersToProps } from './selector'; +import { Group } from '../../types'; +import { useFilters, useLoading } from '../../hooks'; +import { useCostInsightsTabsStyles as useStyles } from '../../utils/styles'; + +export type CostInsightsTabsProps = { + groups: Group[]; +}; + +const CostInsightsTabs = ({ groups }: CostInsightsTabsProps) => { + const classes = useStyles(); + const [index] = useState(0); // index is fixed for now until other tabs are added + const [groupMenuEl, setGroupMenuEl] = useState(null); + const { group, setGroup } = useFilters(mapFiltersToProps); + const { loadingActions, dispatchReset } = useLoading(mapLoadingToProps); + + const openGroupMenu = (e: any) => setGroupMenuEl(e.currentTarget as Element); + + const closeGroupMenu = () => setGroupMenuEl(null); + + const updateGroupFilterAndCloseMenu = (g: Group) => () => { + dispatchReset(loadingActions); + closeGroupMenu(); + setGroup(g); + }; + + const renderTabLabel = () => ( +
+ + {`${groups.length} teams`} + + +
+ ); + + const hasAtLeastTwoGroups = groups.length >= 2; + + if (!hasAtLeastTwoGroups) return null; + + return ( + <> + + + + + {groups.map((g: Group) => ( + + {g.id} + + ))} + + + ); +}; + +export default CostInsightsTabs; diff --git a/plugins/cost-insights/src/components/CostInsightsTabs/index.ts b/plugins/cost-insights/src/components/CostInsightsTabs/index.ts new file mode 100644 index 0000000000..7055334c2d --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsTabs/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostInsightsTabs'; diff --git a/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts b/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts new file mode 100644 index 0000000000..3aa53cce21 --- /dev/null +++ b/plugins/cost-insights/src/components/CostInsightsTabs/selector.ts @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { MapFiltersToProps } from '../../hooks/useFilters'; +import { MapLoadingToProps } from '../../hooks/useLoading'; +import { Group, PageFilters, getResetStateWithoutInitial } from '../../types'; + +type CostInsightsTabsFilterProps = PageFilters & { + setGroup: (group: Group) => void; +}; + +type CostInsightsTabsLoadingProps = { + loadingActions: Array; + dispatchReset: (loadingActions: string[]) => void; +}; + +export const mapFiltersToProps: MapFiltersToProps = ({ + pageFilters, + setPageFilters, +}) => ({ + ...pageFilters, + setGroup: (group: Group) => + setPageFilters({ + ...pageFilters, + group: group.id, + project: null, + }), +}); + +export const mapLoadingToProps: MapLoadingToProps = ({ + actions, + dispatch, +}) => ({ + loadingActions: actions, + dispatchReset: (loadingActions: string[]) => + dispatch(getResetStateWithoutInitial(loadingActions)), +}); diff --git a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx new file mode 100644 index 0000000000..ef174132a3 --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewCard.tsx @@ -0,0 +1,93 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Card, CardContent, Divider } from '@material-ui/core'; +import CostOverviewChart from '../CostOverviewChart'; +import CostOverviewChartLegend from '../CostOverviewChartLegend'; +import CostOverviewHeader from './CostOverviewHeader'; +import CostOverviewFooter from './CostOverviewFooter'; +import MetricSelect from '../MetricSelect'; +import PeriodSelect from '../PeriodSelect'; +import ProjectSelect from '../ProjectSelect'; +import { useScroll, useFilters, useConfig } from '../../hooks'; +import { mapFiltersToProps } from './selector'; +import { DefaultNavigation } from '../../utils/navigation'; +import { + ChangeStatistic, + DateAggregation, + Project, + Trendline, + findAlways, +} from '../../types'; + +type CostOverviewCardProps = { + change: ChangeStatistic; + aggregation: Array; + trendline: Trendline; + projects: Array; +}; + +const CostOverviewCard = ({ + change, + aggregation, + trendline, + projects, +}: CostOverviewCardProps) => { + const { metrics } = useConfig(); + const { ScrollAnchor } = useScroll(DefaultNavigation.CostOverviewCard); + const { setDuration, setProject, metric, setMetric, ...filters } = useFilters( + mapFiltersToProps, + ); + + const { name } = findAlways(metrics, m => m.kind === metric); + + return ( + + + + + + + + + + + + + + + + + + ); +}; + +export default CostOverviewCard; diff --git a/plugins/techdocs/src/reader/components/TechDocsPageWrapper.tsx b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx similarity index 59% rename from plugins/techdocs/src/reader/components/TechDocsPageWrapper.tsx rename to plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx index b511fde1e7..03920887b8 100644 --- a/plugins/techdocs/src/reader/components/TechDocsPageWrapper.tsx +++ b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx @@ -13,25 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - import React from 'react'; -import { Header, Content, Page, pageTheme } from '@backstage/core'; +import { Box } from '@material-ui/core'; -type TechDocsPageWrapperProps = { - title: string; - subtitle: string; - children: any; +type CostOverviewFooterProps = { + children?: React.ReactNode; }; -export const TechDocsPageWrapper = ({ - children, - title, - subtitle, -}: TechDocsPageWrapperProps) => { - return ( - -
- {children} - - ); -}; +const CostOverviewFooter = ({ children }: CostOverviewFooterProps) => ( + + {React.Children.map(children, child => ( + {child} + ))} + +); + +export default CostOverviewFooter; diff --git a/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewHeader.tsx b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewHeader.tsx new file mode 100644 index 0000000000..5de90d155a --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewHeader.tsx @@ -0,0 +1,53 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { Box, Typography } from '@material-ui/core'; + +type CostOverviewHeaderProps = { + title: string; + subtitle?: string; + children?: React.ReactNode; +}; + +const CostOverviewHeader = ({ + title, + subtitle, + children, +}: CostOverviewHeaderProps) => ( + + + + {title} + + {!!subtitle && ( + + {subtitle} + + )} + + + {children} + + +); + +export default CostOverviewHeader; diff --git a/plugins/cost-insights/src/components/CostOverviewCard/index.ts b/plugins/cost-insights/src/components/CostOverviewCard/index.ts new file mode 100644 index 0000000000..c59fb5cc5b --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewCard/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostOverviewCard'; diff --git a/plugins/cost-insights/src/components/CostOverviewCard/selector.tsx b/plugins/cost-insights/src/components/CostOverviewCard/selector.tsx new file mode 100644 index 0000000000..ef65f38dbb --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewCard/selector.tsx @@ -0,0 +1,46 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Duration, Maybe, PageFilters } from '../../types'; +import { MapFiltersToProps } from '../../hooks/useFilters'; + +type CostOverviewFilterProps = PageFilters & { + setDuration: (duration: Duration) => void; + setProject: (project: Maybe) => void; + setMetric: (metric: Maybe) => void; +}; + +export const mapFiltersToProps: MapFiltersToProps = ({ + pageFilters, + setPageFilters, +}) => ({ + ...pageFilters, + project: pageFilters.project || 'all', + setDuration: (duration: Duration) => + setPageFilters({ + ...pageFilters, + duration, + }), + setProject: (project: Maybe) => + setPageFilters({ + ...pageFilters, + project: project === 'all' ? null : project, + }), + setMetric: (metric: Maybe) => + setPageFilters({ + ...pageFilters, + metric: metric, + }), +}); diff --git a/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewChart.test.tsx b/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewChart.test.tsx new file mode 100644 index 0000000000..e6311d147a --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewChart.test.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import CostOverviewChart from './CostOverviewChart'; +import { renderInTestApp } from '@backstage/test-utils'; +import React from 'react'; +import { DateAggregation, Trendline } from '../../types'; +import { CostInsightsThemeProvider } from '../CostInsightsPage/CostInsightsThemeProvider'; + +const mockAggregation = [ + { date: '2020-04-01', amount: 100 }, + { date: '2020-04-02', amount: 101 }, + { date: '2020-04-03', amount: 102 }, + { date: '2020-04-04', amount: 103 }, +] as Array; + +const mockTrendline = { slope: 0.3, intercept: 101.5 } as Trendline; +const mockMetric = 'mock-metric'; + +describe('', () => { + it('Renders without exploding', async () => { + const rendered = await renderInTestApp( + + + , + ); + expect( + rendered.container.querySelector('.cost-overview-chart'), + ).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewChart.tsx b/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewChart.tsx new file mode 100644 index 0000000000..2b40668409 --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewChart.tsx @@ -0,0 +1,120 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { + ComposedChart, + XAxis, + YAxis, + Tooltip, + CartesianGrid, + Area, + Line, + ResponsiveContainer, +} from 'recharts'; +import { + Maybe, + DateAggregation, + Trendline, + CostInsightsTheme, +} from '../../types'; +import { + overviewGraphTickFormatter, + formatGraphValue, +} from '../../utils/graphs'; +import CostOverviewTooltip from './CostOverviewTooltip'; +import { useTheme } from '@material-ui/core'; +import { useCostOverviewStyles as useStyles } from '../../utils/styles'; +import { NULL_METRIC } from '../../hooks/useConfig'; + +type CostOverviewChartProps = { + responsive: boolean; + aggregation: Array; + trendline?: Maybe; + metric: string | null; + tooltip: string; +}; + +const CostOverviewChart = ({ + responsive = true, + aggregation, + trendline, + metric, + tooltip, +}: CostOverviewChartProps) => { + const theme = useTheme(); + const styles = useStyles(theme); + + const id = metric ? metric : NULL_METRIC; + + const dailyCostData = aggregation.map((entry: DateAggregation) => ({ + date: Date.parse(entry.date), + [id]: entry.amount, + trend: trendline + ? trendline.slope * (Date.parse(entry.date) / 1000) + trendline.intercept + : null, + })); + + return ( + + + + + 0, 'dataMax']} + tick={{ fill: styles.axis.fill }} + tickFormatter={formatGraphValue} + width={styles.yAxis.width} + yAxisId={id} + /> + + + } + animationDuration={100} + /> + + + ); +}; + +export default CostOverviewChart; diff --git a/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewTooltip.tsx b/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewTooltip.tsx new file mode 100644 index 0000000000..17d466441d --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChart/CostOverviewTooltip.tsx @@ -0,0 +1,45 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import moment from 'moment'; +import { TooltipPayload, TooltipProps } from 'recharts'; +import Tooltip from '../../components/Tooltip'; +import { DEFAULT_DATE_FORMAT } from '../../types'; +import { formatGraphValue } from '../../utils/graphs'; + +type CostOverviewTooltipProps = TooltipProps & { + metric: string; + name: string; +}; + +const CostOverviewTooltip = ({ + label, + payload, + metric, + name, +}: CostOverviewTooltipProps) => { + const tooltipLabel = moment(label).format(DEFAULT_DATE_FORMAT); + const items = payload + ?.filter(data => data.name === metric) + .map((data: TooltipPayload) => ({ + label: name, + value: formatGraphValue(data.value as number), + fill: data.fill as string, + })); + return ; +}; + +export default CostOverviewTooltip; diff --git a/plugins/cost-insights/src/components/CostOverviewChart/index.ts b/plugins/cost-insights/src/components/CostOverviewChart/index.ts new file mode 100644 index 0000000000..21f345a282 --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChart/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostOverviewChart'; diff --git a/plugins/cost-insights/src/components/CostOverviewChartLegend/CostOverviewChartLegend.test.tsx b/plugins/cost-insights/src/components/CostOverviewChartLegend/CostOverviewChartLegend.test.tsx new file mode 100644 index 0000000000..a40ff58ec1 --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChartLegend/CostOverviewChartLegend.test.tsx @@ -0,0 +1,40 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { renderInTestApp } from '@backstage/test-utils'; +import CostOverviewChartLegend from './CostOverviewChartLegend'; +import React from 'react'; +import { ChangeStatistic } from '../../types'; + +describe('', () => { + it('Correctly displays text if change is not supplied', async () => { + const rendered = await renderInTestApp( + , + ); + expect(rendered.queryByText('Unclear')).toBeInTheDocument(); + }); + it('Correctly displays formatted change percentage', async () => { + const change = { + ratio: 0.3456, + amount: 40000, + } as ChangeStatistic; + const rendered = await renderInTestApp( + , + ); + expect(rendered.queryByText('Unclear')).not.toBeInTheDocument(); + expect(rendered.queryByText('35%')).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/CostOverviewChartLegend/CostOverviewChartLegend.tsx b/plugins/cost-insights/src/components/CostOverviewChartLegend/CostOverviewChartLegend.tsx new file mode 100644 index 0000000000..538cd2a63a --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChartLegend/CostOverviewChartLegend.tsx @@ -0,0 +1,48 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { Box, useTheme } from '@material-ui/core'; +import LegendItem from '../LegendItem'; +import { formatPercent } from '../../utils/formatters'; +import { ChangeStatistic, CostInsightsTheme } from '../../types'; + +type CostOverviewChartLegendProps = { + change?: ChangeStatistic; + title: string; + tooltip?: string; +}; + +const CostOverviewChartLegend = ({ + change, + title, + tooltip, +}: CostOverviewChartLegendProps) => { + const theme = useTheme(); + + return ( + + + {change ? formatPercent(change.ratio) : 'Unclear'} + + + ); +}; + +export default CostOverviewChartLegend; diff --git a/plugins/cost-insights/src/components/CostOverviewChartLegend/index.ts b/plugins/cost-insights/src/components/CostOverviewChartLegend/index.ts new file mode 100644 index 0000000000..1b6c1fe975 --- /dev/null +++ b/plugins/cost-insights/src/components/CostOverviewChartLegend/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CostOverviewChartLegend'; diff --git a/plugins/cost-insights/src/components/CurrencySelect/CurrencySelect.tsx b/plugins/cost-insights/src/components/CurrencySelect/CurrencySelect.tsx new file mode 100644 index 0000000000..24063a664e --- /dev/null +++ b/plugins/cost-insights/src/components/CurrencySelect/CurrencySelect.tsx @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { MenuItem, Select, SelectProps } from '@material-ui/core'; +import { Currency, CurrencyType, findAlways } from '../../types'; +import { useSelectStyles as useStyles } from '../../utils/styles'; + +const NULL_VALUE = 'engineers'; + +type CurrencySelectProps = { + currency: Currency; + currencies: Currency[]; + onSelect: (currency: Currency) => void; +}; + +const CurrencySelect = ({ + currency, + currencies, + onSelect, +}: CurrencySelectProps) => { + const classes = useStyles(); + + const getOption = (value: unknown) => { + const kind = (value === NULL_VALUE ? null : value) as CurrencyType; + return findAlways(currencies, c => c.kind === kind); + }; + + const handleOnChange: SelectProps['onChange'] = e => { + const option = getOption(e.target.value); + onSelect(option); + }; + + const renderValue: SelectProps['renderValue'] = value => { + const option = getOption(value); + return {option.label}; + }; + + return ( + + ); +}; + +export default CurrencySelect; diff --git a/plugins/cost-insights/src/components/CurrencySelect/index.ts b/plugins/cost-insights/src/components/CurrencySelect/index.ts new file mode 100644 index 0000000000..322b67d4ce --- /dev/null +++ b/plugins/cost-insights/src/components/CurrencySelect/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './CurrencySelect'; diff --git a/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx new file mode 100644 index 0000000000..9783fadcb2 --- /dev/null +++ b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/LabelDataflowInstructionsPage.tsx @@ -0,0 +1,96 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography } from '@material-ui/core'; +import { CodeSnippet } from '@backstage/core'; +import AlertInstructionsLayout from '../AlertInstructionsLayout'; + +const LabelDataflowInstructionsPage = () => { + return ( + + Labeling Dataflow Jobs + + Labels in Google Cloud Platform are key-value pairs that can be added to + most types of cloud resources. Since these labels are also exported in + billing data, adding labels allows a granular breakdown of cloud cost by + software entity. + + + In Cloud Dataflow, labels can be added to a job either programmatically + or via the command-line when launching a job. Note that GCP has + + restrictions + {' '} + on the length and characters that can be used in labels. + + + Labels are not retroactive, so cost tracking is only possible from when + the labels are first added to a Dataflow job. + + + + DataflowPipelineOptions + + Dataflow jobs using Beam's{' '} + + DataflowPipelineOptions + {' '} + directly can use the setLabels function to add one or more + labels: + + + + Dataflow jobs using Scio can similarly set options on the ScioContext: + "my-dataflow-job").asJava)`} + /> + + + + + Command-line + + Dataflow jobs launched from the command-line can add labels as an + argument: + + + + For more information on specifying options, see the{' '} + + Dataflow documentation + {' '} + or{' '} + + Scio Scaladoc + + . + + + + ); +}; + +export default LabelDataflowInstructionsPage; diff --git a/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts new file mode 100644 index 0000000000..052ed379ec --- /dev/null +++ b/plugins/cost-insights/src/components/LabelDataflowInstructionsPage/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './LabelDataflowInstructionsPage'; diff --git a/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx b/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx new file mode 100644 index 0000000000..dd87ecc8a1 --- /dev/null +++ b/plugins/cost-insights/src/components/LegendItem/LegendItem.tsx @@ -0,0 +1,78 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography, Tooltip } from '@material-ui/core'; +import LensIcon from '@material-ui/icons/Lens'; +import HelpOutlineOutlinedIcon from '@material-ui/icons/HelpOutlineOutlined'; +import { useCostGrowthLegendStyles } from '../../utils/styles'; + +type LegendItemProps = { + title: string; + tooltipText?: string; + markerColor?: string; + children?: React.ReactNode; +}; + +const LegendItem = ({ + title, + tooltipText, + markerColor, + children, +}: LegendItemProps) => { + const classes = useCostGrowthLegendStyles(); + return ( + + + {markerColor && ( +
+ +
+ )} + + {title} + + {tooltipText && ( + + {tooltipText} + + } + placement="top-start" + > + + + + + )} +
+ + + {children} + + +
+ ); +}; + +export default LegendItem; diff --git a/plugins/cost-insights/src/components/LegendItem/index.ts b/plugins/cost-insights/src/components/LegendItem/index.ts new file mode 100644 index 0000000000..763b8fc4f4 --- /dev/null +++ b/plugins/cost-insights/src/components/LegendItem/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './LegendItem'; diff --git a/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx new file mode 100644 index 0000000000..67d1ec3ad3 --- /dev/null +++ b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.test.tsx @@ -0,0 +1,71 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { waitFor } from '@testing-library/react'; +import UserEvent from '@testing-library/user-event'; +import MetricSelect, { MetricSelectProps } from './MetricSelect'; +import { renderInTestApp } from '@backstage/test-utils'; + +describe('', () => { + it('should display a metric', async () => { + const mockProps: MetricSelectProps = { + metric: 'test', + metrics: [{ kind: 'test', name: 'some-name' }], + onSelect: jest.fn(), + }; + const { getByText } = await renderInTestApp( + , + ); + expect(getByText(/some-name/)).toBeInTheDocument(); + }); + + it('should display a null metric', async () => { + const mockProps: MetricSelectProps = { + metric: null, + metrics: [{ kind: null, name: 'billie-nullish' }], + onSelect: jest.fn(), + }; + const { getByText } = await renderInTestApp( + , + ); + expect(getByText(/billie-nullish/)).toBeInTheDocument(); + }); + + it('should display all metrics', async () => { + const mockProps: MetricSelectProps = { + metric: null, + metrics: [ + { kind: null, name: 'billie-nullish' }, + { kind: 'MAU1M', name: 'Cost Per Million MAU' }, + { kind: 'my-cool-metric', name: 'metric-mcmetric-face' }, + ], + onSelect: jest.fn(), + }; + const { getAllByText, getByText, getByRole } = await renderInTestApp( + , + ); + const button = getByRole('button'); + + UserEvent.click(button); + + await waitFor(() => getAllByText(/billie-nullish/)); + + // The active metric should display in the popver list and in the input + expect(getAllByText(/billie-nullish/).length).toBe(2); + expect(getByText(/Cost Per Million MAU/)).toBeInTheDocument(); + expect(getByText(/metric-mcmetric-face/)).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx new file mode 100644 index 0000000000..1d3af911d4 --- /dev/null +++ b/plugins/cost-insights/src/components/MetricSelect/MetricSelect.tsx @@ -0,0 +1,67 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Select, MenuItem } from '@material-ui/core'; +import { Maybe, Metric, findAlways } from '../../types'; +import { useSelectStyles as useStyles } from '../../utils/styles'; +import { NULL_METRIC } from '../../hooks/useConfig'; + +export type MetricSelectProps = { + metric: Maybe; + metrics: Array; + onSelect: (metric: Maybe) => void; +}; + +const MetricSelect = ({ metric, metrics, onSelect }: MetricSelectProps) => { + const classes = useStyles(); + + const handleOnChange = (e: React.ChangeEvent<{ value: unknown }>) => { + if (e.target.value === NULL_METRIC) { + onSelect(null); + } else { + onSelect(e.target.value as string); + } + }; + + const renderValue = (value: unknown) => { + const kind = (value === NULL_METRIC ? null : value) as Maybe; + const { name } = findAlways(metrics, m => m.kind === kind); + return {name}; + }; + + return ( + + ); +}; + +export default MetricSelect; diff --git a/plugins/cost-insights/src/components/MetricSelect/index.ts b/plugins/cost-insights/src/components/MetricSelect/index.ts new file mode 100644 index 0000000000..f68e5031c1 --- /dev/null +++ b/plugins/cost-insights/src/components/MetricSelect/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './MetricSelect'; diff --git a/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx new file mode 100644 index 0000000000..c632ebad34 --- /dev/null +++ b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.test.tsx @@ -0,0 +1,84 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { getByRole, waitFor } from '@testing-library/react'; +import UserEvent from '@testing-library/user-event'; +import PeriodSelect, { DEFAULT_OPTIONS as options } from './PeriodSelect'; +import { Duration, getDefaultPageFilters, Group } from '../../types'; + +import { renderInTestApp } from '@backstage/test-utils'; + +const DefaultPageFilters = getDefaultPageFilters([{ id: 'tools' }] as Group[]); + +Date.now = jest.fn(() => new Date(Date.parse('2020-05-01')).valueOf()); + +describe('', () => { + it('Renders without exploding', async () => { + const rendered = await renderInTestApp( + , + ); + expect(rendered.getByTestId('period-select')).toBeInTheDocument(); + }); + + it('Should display all costGrowth period options', async () => { + const rendered = await renderInTestApp( + , + ); + const periodSelectContainer = rendered.getByTestId('period-select'); + const button = getByRole(periodSelectContainer, 'button'); + UserEvent.click(button); + await waitFor(() => rendered.getByText('Past 60 Days')); + options.forEach(option => + expect( + rendered.getByTestId(`period-select-option-${option.value}`), + ).toBeInTheDocument(), + ); + }); + + describe.each` + duration + ${Duration.P1M} + ${Duration.P3M} + ${Duration.P90D} + ${Duration.P30D} + `('Should select the correct duration', ({ duration }) => { + it(`Should select ${duration}`, async () => { + const mockOnSelect = jest.fn(); + const mockAggregation = + DefaultPageFilters.duration === duration + ? Duration.P1M + : DefaultPageFilters.duration; + + const rendered = await renderInTestApp( + , + ); + const periodSelect = rendered.getByTestId('period-select'); + const button = getByRole(periodSelect, 'button'); + + UserEvent.click(button); + await waitFor(() => rendered.getByText('Past 60 Days')); + UserEvent.click(rendered.getByTestId(`period-select-option-${duration}`)); + expect(mockOnSelect).toHaveBeenLastCalledWith(duration); + }); + }); +}); diff --git a/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx new file mode 100644 index 0000000000..688e22452e --- /dev/null +++ b/plugins/cost-insights/src/components/PeriodSelect/PeriodSelect.tsx @@ -0,0 +1,100 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { MenuItem, Select, SelectProps } from '@material-ui/core'; +import { + formatLastTwoLookaheadQuarters, + formatLastTwoMonths, +} from '../../utils/formatters'; +import { Duration, findAlways } from '../../types'; +import { useSelectStyles as useStyles } from '../../utils/styles'; + +export type PeriodOption = { + value: Duration; + label: string; +}; + +const LAST_6_MONTHS = 'Past 6 Months'; +const LAST_60_DAYS = 'Past 60 Days'; +const LAST_2_COMPLETED_MONTHS = formatLastTwoMonths(); +const LAST_2_LOOKAHEAD_QUARTERS = formatLastTwoLookaheadQuarters(); + +export const DEFAULT_OPTIONS: PeriodOption[] = [ + { + value: Duration.P90D, + label: LAST_6_MONTHS, + }, + { + value: Duration.P30D, + label: LAST_60_DAYS, + }, + { + value: Duration.P1M, + label: LAST_2_COMPLETED_MONTHS, + }, + { + value: Duration.P3M, + label: LAST_2_LOOKAHEAD_QUARTERS, + }, +]; + +type PeriodSelectProps = { + duration: Duration; + onSelect: (duration: Duration) => void; + options?: PeriodOption[]; +}; + +const PeriodSelect = ({ + duration, + onSelect, + options = DEFAULT_OPTIONS, +}: PeriodSelectProps) => { + const classes = useStyles(); + + const handleOnChange: SelectProps['onChange'] = e => { + onSelect(e.target.value as Duration); + }; + + const renderValue: SelectProps['renderValue'] = value => { + const option = findAlways(DEFAULT_OPTIONS, o => o.value === value); + return {option.label}; + }; + + return ( + + ); +}; + +export default PeriodSelect; diff --git a/plugins/cost-insights/src/components/PeriodSelect/index.ts b/plugins/cost-insights/src/components/PeriodSelect/index.ts new file mode 100644 index 0000000000..7bd70b3358 --- /dev/null +++ b/plugins/cost-insights/src/components/PeriodSelect/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './PeriodSelect'; diff --git a/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx new file mode 100644 index 0000000000..cc52012543 --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsights/ProductInsights.tsx @@ -0,0 +1,43 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography, Grid } from '@material-ui/core'; +import ProductInsightsCard from '../ProductInsightsCard'; +import { useConfig } from '../../hooks'; + +const ProductInsights = ({}) => { + const { products } = useConfig(); + + return ( + <> + + + Your team's product usage + + + + {products.map(product => ( + + + + ))} + + + ); +}; + +export default ProductInsights; diff --git a/plugins/cost-insights/src/components/ProductInsights/index.ts b/plugins/cost-insights/src/components/ProductInsights/index.ts new file mode 100644 index 0000000000..0a20d3c322 --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsights/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ProductInsights'; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx new file mode 100644 index 0000000000..6d40fc276a --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.test.tsx @@ -0,0 +1,167 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import ProductInsightsCard from './ProductInsightsCard'; +import { + MockComputeEngine, + createMockEntity, + mockDefaultState, + createMockProductCost, +} from '../../utils/mockData'; +import { + IdentityApi, + ApiRegistry, + identityApiRef, + ApiProvider, +} from '@backstage/core'; +import { costInsightsApiRef, CostInsightsApi } from '../../api'; +import { renderInTestApp } from '@backstage/test-utils'; +import { GroupsContext } from '../../hooks/useGroups'; +import { LoadingContext } from '../../hooks/useLoading'; +import { + Product, + ProductCost, + defaultCurrencies, + findAlways, +} from '../../types'; +import { + MockConfigProvider, + MockFilterProvider, + MockCurrencyProvider, + MockScrollProvider, +} from '../../utils/tests'; + +const mockLoadingDispatch = jest.fn(); +const mockSetPageFilters = jest.fn(); +const mockSetProductFilters = jest.fn(); +const mockSetCurrency = jest.fn(); +const engineers = findAlways(defaultCurrencies, c => c.kind === null); + +const identityApi: Partial = { + getProfile: () => ({ + email: 'test-email@example.com', + displayName: 'User 1', + }), +}; + +const costInsightsApi = ( + productCost: ProductCost, +): Partial => ({ + getProductInsights: () => + Promise.resolve(productCost) as Promise, +}); + +const getApis = (productCost: ProductCost) => { + return ApiRegistry.from([ + [identityApiRef, identityApi], + [costInsightsApiRef, costInsightsApi(productCost)], + ]); +}; + +const mockProductCost = createMockProductCost(() => ({ + entities: [], + aggregation: [3000, 4000], + change: { + ratio: 0.23, + amount: 1000, + }, +})); + +const renderProductInsightsCardInTestApp = async ( + productCost: ProductCost, + product: Product, +) => + await renderInTestApp( + + + + + + + + + + + + + + + , + ); + +describe('', () => { + it('Renders the scroll anchors', async () => { + const rendered = await renderProductInsightsCardInTestApp( + mockProductCost, + MockComputeEngine, + ); + expect( + rendered.queryByTestId(`scroll-test-compute-engine`), + ).toBeInTheDocument(); + }); + + it('Should render the right subheader for products with cost data', async () => { + const productCost = { + ...mockProductCost, + entities: [...Array(1000)].map(createMockEntity), + }; + const rendered = await renderProductInsightsCardInTestApp( + productCost, + MockComputeEngine, + ); + const subheader = 'entities, sorted by cost'; + const subheaderRgx = new RegExp( + `${productCost.entities.length} ${subheader}`, + ); + expect(rendered.getByText(subheaderRgx)).toBeInTheDocument(); + }); + + it('Should render the right subheader if there is no cost data or change data', async () => { + const productCost = { entities: [], aggregation: [0, 0] } as ProductCost; + const subheader = `There are no ${MockComputeEngine.name} costs within this timeframe for your team's projects.`; + const rendered = await renderProductInsightsCardInTestApp( + productCost, + MockComputeEngine, + ); + const subheaderRgx = new RegExp(subheader); + expect(rendered.getByText(subheaderRgx)).toBeInTheDocument(); + expect( + rendered.queryByTestId('.resource-growth-chart-legend'), + ).not.toBeInTheDocument(); + expect( + rendered.queryByTestId('.insights-bar-chart'), + ).not.toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx new file mode 100644 index 0000000000..1d24139c64 --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsightsCard/ProductInsightsCard.tsx @@ -0,0 +1,147 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useCallback, useEffect, useState } from 'react'; +import { InfoCard, useApi } from '@backstage/core'; +import { Box } from '@material-ui/core'; +import Alert from '@material-ui/lab/Alert'; +import { costInsightsApiRef } from '../../api'; +import PeriodSelect from '../PeriodSelect'; +import ResourceGrowthBarChart from '../ResourceGrowthBarChart'; +import ResourceGrowthBarChartLegend from '../ResourceGrowthBarChartLegend'; +import { useFilters, useLoading, useScroll } from '../../hooks'; +import { useProductInsightsCardStyles as useStyles } from '../../utils/styles'; +import { mapFiltersToProps, mapLoadingToProps } from './selector'; +import { Duration, Maybe, Product, ProductCost } from '../../types'; +import { pluralOf } from '../../utils/grammar'; + +type ProductInsightsCardProps = { + product: Product; +}; + +const ProductInsightsCard = ({ product }: ProductInsightsCardProps) => { + const client = useApi(costInsightsApiRef); + const classes = useStyles(); + const { ScrollAnchor } = useScroll(product.kind); + const [resource, setResource] = useState>(null); + const [error, setError] = useState>(null); + + const { group, product: productFilter, setProduct } = useFilters( + mapFiltersToProps(product.kind), + ); + const { loadingProduct, dispatchLoading } = useLoading( + mapLoadingToProps(product.kind), + ); + + // @see CostInsightsPage + // eslint-disable-next-line react-hooks/exhaustive-deps + const dispatchLoadingProduct = useCallback(dispatchLoading, [product.kind]); + + const amount = resource?.entities?.length || 0; + const hasCostsWithinTimeframe = resource?.change && amount; + + const subheader = amount + ? `${amount} ${pluralOf(amount, 'entity', 'entities')}, sorted by cost` + : `There are no ${product.name} costs within this timeframe for your team's projects.`; + + const costStart = resource?.aggregation[0] || 0; + const costEnd = resource?.aggregation[1] || 0; + + useEffect(() => { + async function load() { + if (loadingProduct) { + try { + const p: ProductCost = await client.getProductInsights( + product.kind, + group!, + productFilter!.duration, + ); + setResource(p); + } catch (e) { + setError(e); + } finally { + dispatchLoadingProduct(false); + } + } + } + load(); + }, [ + client, + product, + setResource, + loadingProduct, + dispatchLoadingProduct, + productFilter, + group, + product.kind, + ]); + + const onPeriodSelect = (duration: Duration) => { + dispatchLoadingProduct(true); + setProduct(duration); + }; + + const infoCardProps = { + headerProps: { + classes: classes, + action: ( + + ), + }, + }; + + if (error) { + return ( + + + {`Error: Could not fetch product insights for ${product.name}`} + + ); + } + + if (!resource) { + return null; + } + + return ( + + + {hasCostsWithinTimeframe && ( + <> + + + + + + + + )} + + ); +}; + +export default ProductInsightsCard; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/index.ts b/plugins/cost-insights/src/components/ProductInsightsCard/index.ts new file mode 100644 index 0000000000..ef378004f0 --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsightsCard/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ProductInsightsCard'; diff --git a/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts b/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts new file mode 100644 index 0000000000..001ff717bd --- /dev/null +++ b/plugins/cost-insights/src/components/ProductInsightsCard/selector.ts @@ -0,0 +1,56 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { MapFiltersToProps } from '../../hooks/useFilters'; +import { MapLoadingToProps } from '../../hooks/useLoading'; +import { Duration, PageFilters, ProductPeriod, findAlways } from '../../types'; + +type ProductInsightsCardFilterProps = PageFilters & { + product: ProductPeriod; + setProduct: (duration: Duration) => void; +}; + +type ProductInsightsCardLoadingProps = { + loadingProduct: boolean; + dispatchLoading: (isLoading: boolean) => void; +}; + +export const mapFiltersToProps = ( + product: string, +): MapFiltersToProps => ({ + pageFilters, + productFilters, + setProductFilters, +}) => ({ + ...pageFilters, + product: findAlways(productFilters, p => p.productType === product), + setProduct: (duration: Duration) => + setProductFilters( + productFilters.map(period => + period.productType === product ? { ...period, duration } : period, + ), + ), +}); + +export const mapLoadingToProps = ( + product: string, +): MapLoadingToProps => ({ + state, + dispatch, +}) => ({ + loadingProduct: state[product], + dispatchLoading: (isLoading: boolean) => dispatch({ [product]: isLoading }), +}); diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx new file mode 100644 index 0000000000..5c3856cc9e --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.test.tsx @@ -0,0 +1,85 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { renderInTestApp } from '@backstage/test-utils'; +import ProjectGrowthAlertCard from './ProjectGrowthAlertCard'; +import { createMockProjectGrowthAlert } from '../../utils/mockData'; +import { MockCurrencyProvider, MockConfigProvider } from '../../utils/tests'; +import { AlertCost, defaultCurrencies, findAlways } from '../../types'; + +const engineers = findAlways(defaultCurrencies, c => c.kind === null); + +const MockProject = 'test-project-1'; +const MockAlertCosts: AlertCost[] = [ + { id: 'test-id-1', aggregation: [150, 200] }, + { id: 'test-id-2', aggregation: [235, 400] }, +]; + +const MockProjectGrowthAlert = createMockProjectGrowthAlert(alert => ({ + ...alert, + project: MockProject, + products: MockAlertCosts, +})); + +describe('', () => { + it('renders the correct title and subheader for multiple services', async () => { + const subheader = new RegExp( + `${MockAlertCosts.length} products, sorted by cost`, + ); + const title = new RegExp(`Project growth for ${MockProject}`); + const rendered = await renderInTestApp( + + + , + + , + ); + expect(rendered.getByText(title)).toBeInTheDocument(); + expect(rendered.getByText(subheader)).toBeInTheDocument(); + }); + + it('renders the correct title and subheader for a single service', async () => { + const subheader = new RegExp('1 product'); + const title = new RegExp(`Project growth for ${MockProject}`); + const rendered = await renderInTestApp( + + + + + , + ); + expect(rendered.getByText(title)).toBeInTheDocument(); + expect(rendered.getByText(subheader)).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx new file mode 100644 index 0000000000..c27b201202 --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/ProjectGrowthAlertCard.tsx @@ -0,0 +1,60 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box } from '@material-ui/core'; +import { InfoCard } from '@backstage/core'; +import ResourceGrowthBarChart from '../ResourceGrowthBarChart'; +import ResourceGrowthBarChartLegend from '../ResourceGrowthBarChartLegend'; +import { Duration, ProjectGrowthAlert } from '../../types'; +import { pluralOf } from '../../utils/grammar'; + +type ProjectGrowthAlertProps = { + alert: ProjectGrowthAlert; +}; + +const ProjectGrowthAlertCard = ({ alert }: ProjectGrowthAlertProps) => { + const [costStart, costEnd] = alert.aggregation; + + const subheader = ` + ${alert.products.length} ${pluralOf(alert.products.length, 'product')}${ + alert.products.length > 1 ? ', sorted by cost' : '' + }`; + + return ( + + + + + + + + + ); +}; + +export default ProjectGrowthAlertCard; diff --git a/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts new file mode 100644 index 0000000000..ab608f5f4c --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectGrowthAlertCard/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ProjectGrowthAlertCard'; diff --git a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx new file mode 100644 index 0000000000..f8f4a90a9e --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/ProjectGrowthInstructionsPage.tsx @@ -0,0 +1,212 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography } from '@material-ui/core'; +import { InfoCard } from '@backstage/core'; +import AlertInstructionsLayout from '../AlertInstructionsLayout'; +import ProjectGrowthAlertCard from '../ProjectGrowthAlertCard'; +import { + AlertType, + Duration, + Entity, + Product, + ProjectGrowthAlert, +} from '../../types'; +import ResourceGrowthBarChartLegend from '../ResourceGrowthBarChartLegend'; +import ResourceGrowthBarChart from '../ResourceGrowthBarChart'; + +const ProjectGrowthInstructionsPage = () => { + const projectGrowthAlert: ProjectGrowthAlert = { + id: AlertType.ProjectGrowth, + project: 'example-project', + periodStart: 'Q1 2020', + periodEnd: 'Q2 2020', + aggregation: [60000, 120000], + change: { + ratio: 1, + amount: 60000, + }, + products: [ + { + id: 'Compute Engine', + aggregation: [58000, 118000], + }, + { + id: 'Cloud Dataflow', + aggregation: [1200, 1500], + }, + { + id: 'Cloud Storage', + aggregation: [800, 500], + }, + ], + }; + + const product: Product = { + kind: 'ComputeEngine', + name: 'Compute Engine', + }; + + const entities: Entity[] = [ + { + id: 'service-one', + aggregation: [18200, 58500], + }, + { + id: 'service-two', + aggregation: [1200, 1300], + }, + { + id: 'service-three', + aggregation: [600, 200], + }, + ]; + + return ( + + Investigating cloud cost growth + + Cost Insights shows an alert when costs for a particular billing entity, + such as a GCP project, have grown at a rate faster than our alerting + threshold. The responsible team should follow this guide to decide + whether this warrants further investigation. + + + + Is the growth expected? + + The first question to ask is whether growth is expected. Perhaps a new + product has been deployed, or additional regions added for + reliability. + + + Many services increase cost linearly with load. Has the demand + increased? This may happen as you open new markets, or run marketing + offers. Costs should be compared against a business metric, such as + daily users, to normalize natural increases from business growth. + + + Seasonal variance may also cause cost growth; yearly campaigns, an + increase in demand during certain times of year. + + + Cloud costs will often go up before they go down, in the case of + migrations. Teams moving to new infrastructure may run in both the old + and new environment during the migration. + + + + + Is the growth significant? + + Next, evaluate whether the growth is significant. This helps avoid + premature optimization, where cost in engineering time is more than + would be saved from the optimization over a reasonable timeframe. + + + We recommend reframing the cost growth itself in terms of engineering + time. How much engineering time, for an average fully-loaded + engineer cost at the company, is being overspent each month? Compare + this to expected engineering time for optimization to decide whether + the optimization is worthwhile. + + + + + + Identifying which cloud product contributed most + + + For projects meeting the alert threshold, Cost Insights shows a cost + comparison of cloud products over the examined time period: + + + + + + This allows you to quickly see which cloud products contributed to the + growth in cloud costs. + + + + + + Identifying the responsible workload + + + After identifying the cloud product, use the corresponding product + panel in Cost Insights to find a particular workload (or entity + ) that has grown in cost: + + + {/* ProductInsightsCard without API query / PeriodSelect */} + + + + + + + + + + + + + From here, you can dig into commit history or deployment logs to find + probable causes of an unexpected spike in cost. + + + + + Optimizing the workload + + Workload optimization varies between cloud products, but there are a + few general optimization areas to consider: + + Retention + + Is the workload or storage necessary? Truly idle or unused resources + can be cleaned up for immediate cost savings. For storage, how long do + we need the data? Many cloud products support retention policies to + automatically delete data after a certain time period. + + Efficiency + + Is the workload using cloud resources efficiently? For compute + resources, do the utilization metrics look reasonable? Autoscaling + infrastructure, such as Kubernetes, can run workloads more efficiently + without comprimising reliability. + + Lifecycle + + Is the workload using an optimal pricing model? Some cloud products + offer better pricing for data that is accessed less frequently. + + + + ); +}; + +export default ProjectGrowthInstructionsPage; diff --git a/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts new file mode 100644 index 0000000000..c75240405c --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectGrowthInstructionsPage/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ProjectGrowthInstructionsPage'; diff --git a/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx new file mode 100644 index 0000000000..92de819fe0 --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.test.tsx @@ -0,0 +1,68 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { getByRole, waitFor } from '@testing-library/react'; +import UserEvent from '@testing-library/user-event'; +import ProjectSelect from './ProjectSelect'; +import { MockFilterProvider } from '../../utils/tests'; +import { renderInTestApp } from '@backstage/test-utils'; + +const mockProjects = [ + { id: 'project1' }, + { id: 'project2' }, + { id: 'project3' }, +]; + +const mockSetPageFilters = jest.fn(); + +describe('', () => { + let Component: React.ReactNode; + beforeEach(() => { + Component = () => ( + + + + ); + }); + + it('Renders without exploding', async () => { + const rendered = await renderInTestApp(Component); + expect(rendered.getByText('All Projects')).toBeInTheDocument(); + }); + + it('shows all projects in the filter select', async () => { + const rendered = await renderInTestApp(Component); + const projectSelectContainer = rendered.getByTestId( + 'project-filter-select', + ); + const button = getByRole(projectSelectContainer, 'button'); + UserEvent.click(button); + await waitFor(() => rendered.getByTestId('option-all')); + mockProjects.forEach( + project => + project.id && + expect(rendered.getByText(project.id)).toBeInTheDocument(), + ); + }); +}); diff --git a/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx new file mode 100644 index 0000000000..cbcd8ede4e --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectSelect/ProjectSelect.tsx @@ -0,0 +1,70 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { MenuItem, Select } from '@material-ui/core'; +import { Maybe, Project } from '../../types'; +import { useSelectStyles as useStyles } from '../../utils/styles'; + +type ProjectSelectProps = { + project: Maybe; + projects: Array; + onSelect: (project: Maybe) => void; +}; + +const ProjectSelect = ({ project, projects, onSelect }: ProjectSelectProps) => { + const classes = useStyles(); + + const projectOptions = [{ id: 'all' } as Project, ...projects] + .filter(p => p.id) + .sort((a, b) => (a.id as string).localeCompare(b.id as string)); + + const handleOnChange = (e: React.ChangeEvent<{ value: unknown }>) => { + onSelect(e.target.value as string); + }; + + const renderValue = (value: unknown) => { + const proj = value as string; + return ( + + {proj === 'all' ? 'All Projects' : proj} + + ); + }; + + return ( + + ); +}; + +export default ProjectSelect; diff --git a/plugins/cost-insights/src/components/ProjectSelect/index.ts b/plugins/cost-insights/src/components/ProjectSelect/index.ts new file mode 100644 index 0000000000..47a2b9e22c --- /dev/null +++ b/plugins/cost-insights/src/components/ProjectSelect/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ProjectSelect'; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx new file mode 100644 index 0000000000..8355deab7d --- /dev/null +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.test.tsx @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import ResourceGrowthBarChart from './ResourceGrowthBarChart'; +import { Duration } from '../../types'; +import { renderInTestApp } from '@backstage/test-utils'; +import { createMockEntity } from '../../utils/mockData'; + +const MockResources = [...Array(10)].map((_, index) => + createMockEntity(() => ({ + id: `test-id-${index + 1}`, + // grow resource costs linearly for testing + aggregation: [index * 1000, (index + 1) * 1000], + })), +); + +describe('', () => { + it('Pre-renders without exploding', async () => { + const rendered = await renderInTestApp( + , + ); + expect(rendered.queryByTestId('bar-chart-wrapper')).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx new file mode 100644 index 0000000000..3ae35ba871 --- /dev/null +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChart/ResourceGrowthBarChart.tsx @@ -0,0 +1,97 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { TooltipPayload } from 'recharts'; +import { + currencyFormatter, + dateRegex, + formatDuration, +} from '../../utils/formatters'; +import { + BarChartData, + CostInsightsTheme, + DataKey, + Duration, + Entity, + inclusiveEndDateOf, + inclusiveStartDateOf, + Maybe, + ResourceData, + AlertCost, +} from '../../types'; +import BarChart from '../BarChart'; +import { TooltipItemProps } from '../Tooltip'; +import { useTheme } from '@material-ui/core'; + +export type ResourceGrowthBarChartProps = { + duration: Duration; + resources: Array; +}; + +const ResourceGrowthBarChart = ({ + duration, + resources, +}: ResourceGrowthBarChartProps) => { + const theme = useTheme(); + const getTooltipItem = (payload: TooltipPayload): Maybe => { + const label = dateRegex.test(payload.name) + ? formatDuration(payload.name, duration) + : payload.name; + const value = + typeof payload.value === 'number' + ? currencyFormatter.format(payload.value) + : (payload.value as string); + const fill = payload.fill as string; + + switch (payload.dataKey) { + case DataKey.Current: + case DataKey.Previous: + return { + label: label, + value: value, + fill: fill, + }; + default: + return null; + } + }; + + const barChartData: BarChartData = { + previousFill: theme.palette.lightBlue, + currentFill: theme.palette.darkBlue, + previousName: inclusiveStartDateOf(duration), + currentName: inclusiveEndDateOf(duration), + }; + + const resourceData: ResourceData[] = resources.map(resource => { + return { + name: resource.id, + previous: resource.aggregation[0], + current: resource.aggregation[1], + }; + }); + + return ( + + ); +}; + +export default ResourceGrowthBarChart; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts b/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts new file mode 100644 index 0000000000..b1388143e4 --- /dev/null +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChart/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ResourceGrowthBarChart'; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx new file mode 100644 index 0000000000..1e432ff3bc --- /dev/null +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.test.tsx @@ -0,0 +1,93 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ReactNode } from 'react'; +import { renderInTestApp } from '@backstage/test-utils'; +import ResourceGrowthBarChartLegend from './ResourceGrowthBarChartLegend'; +import { Currency, defaultCurrencies, Duration, findAlways } from '../../types'; +import { MockConfigProvider, MockCurrencyProvider } from '../../utils/tests'; + +const engineers = findAlways(defaultCurrencies, c => c.kind === null); + +const MockContext = ({ + children, + currency, +}: { + children: ReactNode; + currency: Currency; +}) => ( + + + {children} + + +); + +describe('', () => { + describe.each` + ratio | amount | costText | engineerTest + ${2.5} | ${300_000} | ${'Cost Growth'} | ${/\~6 engineers/} + ${-2.5} | ${-120_000} | ${'Cost Savings'} | ${/\~2 engineers/} + `( + 'Should display the cost text', + ({ ratio, amount, costText, engineerTest }) => { + it(`Should display the correct cost and engineer text for ${ratio} percent change`, async () => { + const rendered = await renderInTestApp( + + + , + ); + expect(rendered.getByText(costText)).toBeInTheDocument(); + expect(rendered.queryByText(engineerTest)).toBeInTheDocument(); + }); + }, + ); + + describe.each` + duration | periodStartText | periodEndText + ${Duration.P30D} | ${'First 30 Days'} | ${'Last 30 Days'} + ${Duration.P90D} | ${'First 90 Days'} | ${'Last 90 Days'} + `( + 'Should display the correct relative time', + ({ duration, periodStartText, periodEndText }) => { + it(`Should display the correct relative time for ${duration}`, async () => { + const rendered = await renderInTestApp( + + + , + ); + expect(rendered.getByText(periodStartText)).toBeInTheDocument(); + expect(rendered.getByText(periodEndText)).toBeInTheDocument(); + }); + }, + ); +}); diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx new file mode 100644 index 0000000000..1466e18ee1 --- /dev/null +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/ResourceGrowthBarChartLegend.tsx @@ -0,0 +1,72 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, useTheme } from '@material-ui/core'; +import LegendItem from '../LegendItem'; +import CostGrowth from '../CostGrowth'; +import { currencyFormatter, formatDuration } from '../../utils/formatters'; +import { + ChangeStatistic, + CostInsightsTheme, + Duration, + inclusiveEndDateOf, + inclusiveStartDateOf, +} from '../../types'; + +export type ResourceGrowthBarChartLegendProps = { + change: ChangeStatistic; + duration: Duration; + costStart: number; + costEnd: number; +}; + +const ResourceGrowthBarChartLegend = ({ + change, + duration, + costStart, + costEnd, +}: ResourceGrowthBarChartLegendProps) => { + const theme = useTheme(); + + const startOf = inclusiveStartDateOf(duration); + const endOf = inclusiveEndDateOf(duration); + const periodStartTitle = formatDuration(startOf, duration); + const periodEndTitle = formatDuration(endOf, duration); + + return ( + + + + {currencyFormatter.format(costStart)} + + + + + {currencyFormatter.format(costEnd)} + + + + + + + ); +}; + +export default ResourceGrowthBarChartLegend; diff --git a/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts new file mode 100644 index 0000000000..7071799805 --- /dev/null +++ b/plugins/cost-insights/src/components/ResourceGrowthBarChartLegend/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './ResourceGrowthBarChartLegend'; diff --git a/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx b/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx new file mode 100644 index 0000000000..8c12b34ffb --- /dev/null +++ b/plugins/cost-insights/src/components/Tooltip/Tooltip.test.tsx @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { renderInTestApp } from '@backstage/test-utils'; +import Tooltip from './Tooltip'; +import { CostInsightsThemeProvider } from '../CostInsightsPage/CostInsightsThemeProvider'; + +const mockTooltipItems = [ + { + label: 'Cost', + value: '$1,000,000', + fill: '#FFF', + }, + { + label: 'Test Metric', + value: '100,000,000', + fill: '#FFF', + }, +]; + +describe('', () => { + it('renders without exploding', async () => { + const rendered = await renderInTestApp( + + + , + ); + expect( + rendered.container.querySelector('.tooltip-content'), + ).toBeInTheDocument(); + }); + + it('formats label and tooltip item text correctly', async () => { + const rendered = await renderInTestApp( + + + , + ); + expect(rendered.getByText('05/16/2020')).toBeInTheDocument(); + expect(rendered.getByText('Cost')).toBeInTheDocument(); + expect(rendered.getByText('Test Metric')).toBeInTheDocument(); + expect(rendered.getByText('$1,000,000')).toBeInTheDocument(); + expect(rendered.getByText('100,000,000')).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx b/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx new file mode 100644 index 0000000000..727b2476c8 --- /dev/null +++ b/plugins/cost-insights/src/components/Tooltip/Tooltip.tsx @@ -0,0 +1,54 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography } from '@material-ui/core'; +import TooltipItem, { TooltipItemProps } from './TooltipItem'; +import { useTooltipStyles } from '../../utils/styles'; + +export type TooltipProps = { + label?: string; + items?: Array; +}; + +const Tooltip = ({ label, items }: TooltipProps) => { + const classes = useTooltipStyles(); + return ( + + {label && ( + + {label} + + )} + {items && + items.map((item, index) => ( + + ))} + + ); +}; + +export default Tooltip; diff --git a/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx b/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx new file mode 100644 index 0000000000..67d4eac15f --- /dev/null +++ b/plugins/cost-insights/src/components/Tooltip/TooltipItem.tsx @@ -0,0 +1,49 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, Typography } from '@material-ui/core'; +import LensIcon from '@material-ui/icons/Lens'; +import { useTooltipStyles as useStyles } from '../../utils/styles'; + +export type TooltipItemProps = { + value: string; + label: string; + fill: string; +}; + +const TooltipItem = ({ fill, label, value }: TooltipItemProps) => { + const classes = useStyles(); + const style = { fill: fill }; + return ( + + + + + + {label} + + {value} + + ); +}; + +export default TooltipItem; diff --git a/plugins/cost-insights/src/components/Tooltip/index.ts b/plugins/cost-insights/src/components/Tooltip/index.ts new file mode 100644 index 0000000000..ca20ab1242 --- /dev/null +++ b/plugins/cost-insights/src/components/Tooltip/index.ts @@ -0,0 +1,18 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './Tooltip'; +export * from './TooltipItem'; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx new file mode 100644 index 0000000000..6beb204b0d --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.test.tsx @@ -0,0 +1,66 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import UnlabeledDataflowAlertCard from './UnlabeledDataflowAlertCard'; +import { + createMockUnlabeledDataflowAlert, + createMockUnlabeledDataflowAlertProject, +} from '../../utils/mockData'; +import { renderInTestApp } from '@backstage/test-utils'; + +const MockUnlabeledDataflowAlertMultipleProjects = createMockUnlabeledDataflowAlert( + alert => ({ + ...alert, + projects: [...Array(10)].map(() => + createMockUnlabeledDataflowAlertProject(), + ), + }), +); + +const MockUnlabeledDataflowAlertSingleProject = createMockUnlabeledDataflowAlert( + alert => ({ + ...alert, + projects: [...Array(1)].map(() => + createMockUnlabeledDataflowAlertProject(), + ), + }), +); + +describe('', () => { + it('renders the correct subheader for multiple projects', async () => { + const subheader = new RegExp( + `Showing costs from ${MockUnlabeledDataflowAlertMultipleProjects.projects.length} ` + + 'projects with unlabeled Dataflow jobs in the last 30 days.', + ); + const rendered = await renderInTestApp( + , + ); + expect(rendered.getByText(subheader)).toBeInTheDocument(); + }); + + it('renders the correct subheader for a single project', async () => { + const subheader = new RegExp('1 project'); + const rendered = await renderInTestApp( + , + ); + expect(rendered.getByText(subheader)).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx new file mode 100644 index 0000000000..8dff85e867 --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/UnlabeledDataflowAlertCard.tsx @@ -0,0 +1,51 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box } from '@material-ui/core'; +import { InfoCard } from '@backstage/core'; +import UnlabeledDataflowBarChart from '../UnlabeledDataflowBarChart'; +import UnlabeledDataflowBarChartLegend from '../UnlabeledDataflowBarChartLegend'; +import { UnlabeledDataflowAlert } from '../../types'; +import { pluralOf } from '../../utils/grammar'; + +type UnlabeledDataflowAlertProps = { + alert: UnlabeledDataflowAlert; +}; + +const UnlabeledDataflowAlertCard = ({ alert }: UnlabeledDataflowAlertProps) => { + const projects = pluralOf(alert.projects.length, 'project'); + const subheader = ` + Showing costs from ${alert.projects.length} ${projects} with unlabeled Dataflow jobs in the last 30 days. + `; + return ( + + + + + + + + + + + ); +}; + +export default UnlabeledDataflowAlertCard; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts new file mode 100644 index 0000000000..6f22abc062 --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowAlertCard/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './UnlabeledDataflowAlertCard'; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/UnlabeledDataflowBarChart.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/UnlabeledDataflowBarChart.tsx new file mode 100644 index 0000000000..7b1f4e31ec --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/UnlabeledDataflowBarChart.tsx @@ -0,0 +1,73 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { TooltipPayload } from 'recharts'; +import BarChart from '../BarChart'; +import { TooltipItemProps } from '../Tooltip'; +import { + BarChartData, + CostInsightsTheme, + ResourceData, + UnlabeledDataflowAlertProject, +} from '../../types'; +import { currencyFormatter } from '../../utils/formatters'; +import { useTheme } from '@material-ui/core'; + +type UnlabeledDataflowBarChartProps = { + projects: Array; +}; + +export const UnlabeledDataflowBarChart = ({ + projects, +}: UnlabeledDataflowBarChartProps) => { + const theme = useTheme(); + const barChartData: BarChartData = { + previousFill: theme.palette.lightBlue, + currentFill: theme.palette.darkBlue, + previousName: 'Unlabeled Cost', + currentName: 'Labeled Cost', + }; + + const getTooltipItem = (payload: TooltipPayload): TooltipItemProps => { + return { + label: payload.name, + value: + typeof payload.value === 'number' + ? currencyFormatter.format(payload.value) + : (payload.value as string), + fill: payload.fill as string, + }; + }; + + const resources: ResourceData[] = projects.map(project => { + return { + name: project.id, + previous: project.unlabeledCost || 0, + current: project.labeledCost || 0, + }; + }); + + return ( + + ); +}; + +export default UnlabeledDataflowBarChart; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/index.ts b/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/index.ts new file mode 100644 index 0000000000..6f475d5a80 --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowBarChart/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './UnlabeledDataflowBarChart'; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.test.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.test.tsx new file mode 100644 index 0000000000..9ab4e90001 --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.test.tsx @@ -0,0 +1,34 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import UnlabeledDataflowBarChartLegend from './UnlabeledDataflowBarChartLegend'; +import { renderInTestApp } from '@backstage/test-utils'; + +describe('', () => { + it('Displays the correct text', async () => { + const rendered = await renderInTestApp( + , + ); + expect(rendered.getByText('Total Unlabeled Cost')).toBeInTheDocument(); + expect(rendered.getByText('Total Labeled Cost')).toBeInTheDocument(); + expect(rendered.getByText('$9,843')).toBeInTheDocument(); + expect(rendered.getByText('$2,309')).toBeInTheDocument(); + }); +}); diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.tsx b/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.tsx new file mode 100644 index 0000000000..68caaed6d0 --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/UnlabeledDataflowBarChartLegend.tsx @@ -0,0 +1,59 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Box, useTheme } from '@material-ui/core'; +import LegendItem from '../LegendItem'; +import { currencyFormatter } from '../../utils/formatters'; +import { CostInsightsTheme } from '../../types'; + +type UnlabeledDataflowBarChartLegendProps = { + labeledCost: number; + unlabeledCost: number; +}; + +const UnlabeledDataflowBarChartLegend = ({ + unlabeledCost, + labeledCost, +}: UnlabeledDataflowBarChartLegendProps) => { + const theme = useTheme(); + return ( + + + + {currencyFormatter.format(unlabeledCost)} + + + + + {currencyFormatter.format(labeledCost)} + + + + ); +}; + +export default UnlabeledDataflowBarChartLegend; diff --git a/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/index.ts b/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/index.ts new file mode 100644 index 0000000000..470722e60a --- /dev/null +++ b/plugins/cost-insights/src/components/UnlabeledDataflowBarChartLegend/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './UnlabeledDataflowBarChartLegend'; diff --git a/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx b/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx new file mode 100644 index 0000000000..69de854b00 --- /dev/null +++ b/plugins/cost-insights/src/components/WhyCostsMatter/WhyCostsMatter.tsx @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Typography, Box, Grid, Container, Divider } from '@material-ui/core'; + +const WhyCostsMatter = () => { + return ( + + + + + Why cloud costs matter + + + + + + Sustainability{' '} + + 🌎 + + + + Reducing cloud usage improves our carbon footprint. + + + + + + + + Revenue{' '} + + 💸 + + + + Keeping cloud costs well-tuned prevents infrastructure from eating + into revenue. + + + + + + + + Innovation{' '} + + đŸĨ‡ + + + + The more we save, the more we can reinvest in speed and + innovation. + + + + + + ); +}; + +export default WhyCostsMatter; diff --git a/plugins/cost-insights/src/components/WhyCostsMatter/index.ts b/plugins/cost-insights/src/components/WhyCostsMatter/index.ts new file mode 100644 index 0000000000..ed60207fde --- /dev/null +++ b/plugins/cost-insights/src/components/WhyCostsMatter/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { default } from './WhyCostsMatter'; diff --git a/plugins/cost-insights/src/hooks/index.ts b/plugins/cost-insights/src/hooks/index.ts new file mode 100644 index 0000000000..7065bcf91b --- /dev/null +++ b/plugins/cost-insights/src/hooks/index.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './useConfig'; +export * from './useCurrency'; +export * from './useFilters'; +export * from './useCurrency'; +export * from './useGroups'; +export * from './useLoading'; +export * from './useQueryParams'; +export * from './useScroll'; diff --git a/plugins/cost-insights/src/hooks/useConfig.tsx b/plugins/cost-insights/src/hooks/useConfig.tsx new file mode 100644 index 0000000000..aee6567056 --- /dev/null +++ b/plugins/cost-insights/src/hooks/useConfig.tsx @@ -0,0 +1,162 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { + ReactNode, + createContext, + useContext, + useEffect, + useState, +} from 'react'; +import { useApi, configApiRef } from '@backstage/core'; +import { Config as BackstageConfig } from '@backstage/config'; +import { Currency, defaultCurrencies, Product, Icon, Metric } from '../types'; +import { getIcon } from '../utils/navigation'; + +export const NULL_METRIC = 'dailyCost'; +export const NULL_METRIC_NAME = 'Daily Cost'; + +/* + * Config schema 2020-09-28 + * + * costInsights: + * engineerCost: 200000 + * products: + * productA: + * name: Product A + * icon: storage + * productB: + * name: Product B + * icon: data + * metrics: + * metricA: + * name: Metric A + * metricB: + * name: Metric B + */ + +export type ConfigContextProps = { + metrics: Metric[]; + products: Product[]; + icons: Icon[]; + engineerCost: number; + currencies: Currency[]; +}; + +export const ConfigContext = createContext( + undefined, +); + +const defaultState: ConfigContextProps = { + metrics: [{ kind: null, name: NULL_METRIC_NAME }], + products: [], + icons: [], + engineerCost: 0, + currencies: defaultCurrencies, +}; + +export const ConfigProvider = ({ children }: { children: ReactNode }) => { + const c: BackstageConfig = useApi(configApiRef); + const [config, setConfig] = useState(defaultState); + const [loading, setLoading] = useState(true); + + useEffect(() => { + function getProducts(): Product[] { + const products = c.getConfig('costInsights.products'); + return products.keys().map(key => ({ + kind: key, + name: products.getString(`${key}.name`), + aggregation: [0, 0], + })); + } + + function getMetrics(): Metric[] { + const metrics = c.getOptionalConfig('costInsights.metrics'); + if (metrics) { + return metrics.keys().map(key => ({ + kind: key === NULL_METRIC ? null : key, + name: metrics.getString(`${key}.name`), + })); + } + + return []; + } + + function getIcons(): Icon[] { + const products = c.getConfig('costInsights.products'); + const keys = products.keys(); + + return keys.map(k => ({ + kind: k, + component: getIcon(products.getOptionalString(`${k}.icon`)), + })); + } + + function getEngineerCost(): number { + return c.getNumber('costInsights.engineerCost'); + } + + function getConfig() { + const products = getProducts(); + const metrics = getMetrics(); + const engineerCost = getEngineerCost(); + const icons = getIcons(); + + if (metrics.find((m: Metric) => m.kind === null)) { + setConfig(prevState => ({ + ...prevState, + metrics, + products, + engineerCost, + icons, + })); + } else { + setConfig(prevState => ({ + ...prevState, + metrics: [...prevState.metrics, ...metrics], + products, + engineerCost, + icons, + })); + } + setLoading(false); + } + + getConfig(); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + + if (loading) { + return null; + } + + return ( + {children} + ); +}; + +export function useConfig(): ConfigContextProps { + const config = useContext(ConfigContext); + + if (!config) { + assertNever(); + } + + return config; +} + +function assertNever(): never { + throw new Error('Cannot use useConfig outside of ConfigProvider'); +} diff --git a/plugins/cost-insights/src/hooks/useCurrency.tsx b/plugins/cost-insights/src/hooks/useCurrency.tsx new file mode 100644 index 0000000000..f5d0df929a --- /dev/null +++ b/plugins/cost-insights/src/hooks/useCurrency.tsx @@ -0,0 +1,60 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { + Dispatch, + SetStateAction, + ReactNode, + useState, + useContext, +} from 'react'; +import { Currency, defaultCurrencies, findAlways } from '../types'; + +export type CurrencyContextProps = { + currency: Currency; + setCurrency: Dispatch>; +}; + +export type CurrencyProviderProps = { + children: ReactNode; +}; + +export const CurrencyContext = React.createContext< + CurrencyContextProps | undefined +>(undefined); + +export const CurrencyProvider = ({ children }: CurrencyProviderProps) => { + const engineers = findAlways(defaultCurrencies, c => c.kind === null); + const [currency, setCurrency] = useState(engineers); + return ( + + {children} + + ); +}; + +export function useCurrency(): [Currency, Dispatch>] { + const context = useContext(CurrencyContext); + + if (!context) { + assertNever(); + } + + return [context.currency, context.setCurrency]; +} + +function assertNever(): never { + throw Error('Cannot use useCurrency outside of CurrencyProvider'); +} diff --git a/plugins/cost-insights/src/hooks/useFilters.tsx b/plugins/cost-insights/src/hooks/useFilters.tsx new file mode 100644 index 0000000000..c2053d6b0f --- /dev/null +++ b/plugins/cost-insights/src/hooks/useFilters.tsx @@ -0,0 +1,148 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { + Dispatch, + ReactNode, + SetStateAction, + useContext, + useEffect, + useRef, + useState, +} from 'react'; +import { + getDefaultPageFilters, + PageFilters, + ProductFilters, + Duration, + Group, +} from '../types'; +import { useLocation, useNavigate } from 'react-router-dom'; +import { useQueryParams } from './useQueryParams'; +import { stringify } from '../utils/history'; +import { useGroups } from './useGroups'; +import { useConfig } from './useConfig'; + +const getInitialPageState = ( + groups: Group[], + queryParams?: Partial, +) => { + // The group is written initially to queryParams as null, since user groups are asynchronously + // loaded. We preserve nulls in queryParams for other parameters where null is meaningful; for + // group, avoid overwriting the default with null after groups are loaded. + const { group, ...otherParams } = queryParams || {}; + return { + ...getDefaultPageFilters(groups), + ...otherParams, + ...(group ? { group: group } : {}), + }; +}; + +export type FilterContextProps = { + pageFilters: PageFilters; + productFilters: ProductFilters; + setPageFilters: Dispatch>; + setProductFilters: Dispatch>; +}; + +export type MapFiltersToProps = (props: FilterContextProps) => T; + +export type FilterProviderProps = { + children: ReactNode; +}; + +export const FilterContext = React.createContext< + FilterContextProps | undefined +>(undefined); + +export const FilterProvider = ({ children }: FilterProviderProps) => { + const navigate = useNavigate(); + const location = useLocation(); + const queryParams = useQueryParams(); + const qsRef = useRef(''); + const groups = useGroups(); + const { products } = useConfig(); + + const defaultProductFilters = products.map(product => ({ + productType: product.kind, + duration: Duration.P1M, + })); + + const getInitialProductState = (productFilters?: ProductFilters) => { + if (!productFilters) return defaultProductFilters; + return defaultProductFilters.map(product => { + return ( + productFilters.find( + param => param.productType === product.productType, + ) || product + ); + }); + }; + + const [productFilters, setProductFilters] = useState( + getInitialProductState(queryParams.productFilters), + ); + const [pageFilters, setPageFilters] = useState( + getInitialPageState(groups, queryParams.pageFilters), + ); + + // TODO: Figure out why pageFilters doesn't get updated by the above when groups are loaded. + useEffect(() => { + setPageFilters(getInitialPageState(groups, queryParams.pageFilters)); + }, [groups]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + const queryString = stringify({ ...pageFilters, products: productFilters }); + if (queryString === qsRef.current) return; + qsRef.current = queryString; + // TODO Remove workaround once issue is resolved in react-router + // (https://github.com/ReactTraining/react-router/issues/7496) + // navigate({ ...location, search: queryString }); + navigate({ ...location, search: `?${queryString}` }); + }, [pageFilters, productFilters]); // eslint-disable-line react-hooks/exhaustive-deps + + return ( + + {children} + + ); +}; + +export function useFilters(mapFiltersToProps: MapFiltersToProps): T { + const context = useContext(FilterContext); + + if (!context) { + assertNever(); + } + + return mapFiltersToProps({ + pageFilters: context.pageFilters, + productFilters: context.productFilters, + setPageFilters: context.setPageFilters, + setProductFilters: context.setProductFilters, + }); +} + +function assertNever(): never { + throw Error('Cannot use useFilters outside of FilterProvider'); +} diff --git a/plugins/cost-insights/src/hooks/useGroups.tsx b/plugins/cost-insights/src/hooks/useGroups.tsx new file mode 100644 index 0000000000..02c32e7920 --- /dev/null +++ b/plugins/cost-insights/src/hooks/useGroups.tsx @@ -0,0 +1,84 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { ReactNode, useContext, useEffect, useState } from 'react'; +import { useApi, identityApiRef } from '@backstage/core'; +import { costInsightsApiRef } from '../api'; +import { MapLoadingToProps, useLoading } from './useLoading'; +import { DefaultLoadingAction, Group } from '../types'; + +type GroupsProviderLoadingProps = { + dispatchLoadingGroups: (isLoading: boolean) => void; +}; + +export const mapLoadingToProps: MapLoadingToProps = ({ + dispatch, +}) => ({ + dispatchLoadingGroups: (isLoading: boolean) => + dispatch({ [DefaultLoadingAction.UserGroups]: isLoading }), +}); + +type GroupsContextProps = { + groups: Group[]; +}; + +export type GroupsProviderProps = { + children: ReactNode; +}; + +export const GroupsContext = React.createContext({ + groups: [], +}); + +export const GroupsProvider = ({ children }: GroupsProviderProps) => { + const userId = useApi(identityApiRef).getUserId(); + const client = useApi(costInsightsApiRef); + const { dispatchLoadingGroups } = useLoading(mapLoadingToProps); + + const [groups, setGroups] = useState([]); + + useEffect(() => { + dispatchLoadingGroups(true); + + async function getUserGroups() { + const g = await client.getUserGroups(userId); + setGroups(g); + dispatchLoadingGroups(false); + } + + getUserGroups(); + }, [userId, client]); // eslint-disable-line react-hooks/exhaustive-deps + + return ( + + {children} + + ); +}; + +export function useGroups(): Group[] { + const { groups } = useContext(GroupsContext); + + if (!groups) { + assertNever(); + } + + return groups; +} + +function assertNever(): never { + throw Error('Cannot use useGroups outside of GroupsProvider'); +} diff --git a/plugins/cost-insights/src/hooks/useLoading.tsx b/plugins/cost-insights/src/hooks/useLoading.tsx new file mode 100644 index 0000000000..bc0df4bbc7 --- /dev/null +++ b/plugins/cost-insights/src/hooks/useLoading.tsx @@ -0,0 +1,107 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { + Dispatch, + ReactNode, + SetStateAction, + createContext, + useContext, + useEffect, + useMemo, + useReducer, + useState, +} from 'react'; +import { Backdrop, CircularProgress } from '@material-ui/core'; +import { + Loading, + getDefaultState, + DefaultLoadingAction, + getLoadingActions, +} from '../types'; +import { useBackdropStyles as useStyles } from '../utils/styles'; +import { useConfig } from './useConfig'; + +export type LoadingContextProps = { + state: Loading; + dispatch: Dispatch>>; + actions: Array; +}; + +export type LoadingProviderProps = { + children: ReactNode; +}; + +export type MapLoadingToProps = (props: LoadingContextProps) => T; + +export const LoadingContext = createContext( + undefined, +); + +function reducer(prevState: Loading, action: Partial): Loading { + return { + ...prevState, + ...action, + } as Record; +} + +export const LoadingProvider = ({ children }: LoadingProviderProps) => { + const classes = useStyles(); + const { products } = useConfig(); + const actions = useMemo(() => getLoadingActions(products.map(p => p.kind)), [ + products, + ]); + const [state, dispatch] = useReducer(reducer, getDefaultState(actions)); + const [isBackdropVisible, setBackdropVisible] = useState(false); + + useEffect(() => { + function displayLoadingBackdrop() { + // Initial page loading is handled by progress bar + setBackdropVisible( + !state[DefaultLoadingAction.CostInsightsInitial] && + Object.values(state).some(l => l), + ); + } + displayLoadingBackdrop(); + }, [state, setBackdropVisible]); + + return ( + + {children} + + + + + ); +}; + +export function useLoading(mapLoadingToProps: MapLoadingToProps): T { + const context = useContext(LoadingContext); + + if (!context) { + assertNever(); + } + + return mapLoadingToProps({ + state: context.state, + actions: context.actions, + dispatch: context.dispatch, + }); +} + +function assertNever(): never { + throw Error('useLoading cannot be used outside of LoadingProvider'); +} diff --git a/plugins/cost-insights/src/hooks/useQueryParams.tsx b/plugins/cost-insights/src/hooks/useQueryParams.tsx new file mode 100644 index 0000000000..1e6ce8f0fd --- /dev/null +++ b/plugins/cost-insights/src/hooks/useQueryParams.tsx @@ -0,0 +1,35 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { useLocation } from 'react-router-dom'; +import { Location } from 'history'; +import { PageFilters, ProductFilters } from '../types'; +import { parse } from '../utils/history'; + +export type FilterParams = { + pageFilters?: Partial; + productFilters?: ProductFilters; +}; + +export function useQueryParams(): FilterParams { + const location: Location = useLocation(); + const { products: productFilters, ...pageFilters } = parse(location.search); + + return { + productFilters: productFilters, + pageFilters: pageFilters, + }; +} diff --git a/plugins/cost-insights/src/hooks/useScroll.tsx b/plugins/cost-insights/src/hooks/useScroll.tsx new file mode 100644 index 0000000000..480495a257 --- /dev/null +++ b/plugins/cost-insights/src/hooks/useScroll.tsx @@ -0,0 +1,126 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { + Dispatch, + ReactNode, + SetStateAction, + useState, + useContext, + useEffect, + useRef, +} from 'react'; +import { CSSProperties } from '@material-ui/styles'; +import { Maybe } from '../types'; + +export type ScrollTo = Maybe; + +export type ScrollContextProps = { + scrollTo: ScrollTo; + setScrollTo: Dispatch>; +}; + +export type ScrollProviderProps = { + children: ReactNode; +}; + +export type ScrollUtils = { + ScrollAnchor: (props: Omit) => JSX.Element; + scrollIntoView: () => void; +}; + +export interface ScrollAnchorProps extends ScrollIntoViewOptions { + id: ScrollTo; + top?: number; + left?: number; +} + +export const ScrollContext = React.createContext< + ScrollContextProps | undefined +>(undefined); + +export const ScrollAnchor = ({ + id, + top, + left, + behavior, + block, + inline, +}: ScrollAnchorProps) => { + const divRef = useRef(null); + const context = useContext(ScrollContext); + + if (!context) { + assertNever(); + } + + const { scrollTo, setScrollTo } = context; + + const styles: CSSProperties = { + position: 'absolute', + height: 0, + width: 0, + top: top || 0, + left: left || 0, + }; + + useEffect(() => { + function scrollIntoView() { + const options = { + behavior: behavior || 'auto', + block: block || 'start', + inline: inline || 'nearest', + }; + + if (divRef.current && scrollTo === id) { + divRef.current.scrollIntoView(options); + setScrollTo(null); + } + } + + scrollIntoView(); + }, [scrollTo, setScrollTo, id, behavior, block, inline]); + + return
; +}; + +export const ScrollProvider = ({ children }: ScrollProviderProps) => { + const [scrollTo, setScrollTo] = useState(null); + + return ( + + {children} + + ); +}; + +export function useScroll(id: ScrollTo): ScrollUtils { + const context = useContext(ScrollContext); + + if (!context) { + assertNever(); + } + + return { + ScrollAnchor: props => , + scrollIntoView: () => context.setScrollTo(id), + }; +} + +function assertNever(): never { + throw new Error( + `Cannot use useScroll or ScrollAnchor outside ScrollProvider`, + ); +} diff --git a/plugins/cost-insights/src/index.ts b/plugins/cost-insights/src/index.ts new file mode 100644 index 0000000000..cf7aa3ea8c --- /dev/null +++ b/plugins/cost-insights/src/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { plugin } from './plugin'; +export * from './api'; +export * from './types'; diff --git a/plugins/cost-insights/src/plugin.test.ts b/plugins/cost-insights/src/plugin.test.ts new file mode 100644 index 0000000000..6210e11d4c --- /dev/null +++ b/plugins/cost-insights/src/plugin.test.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { plugin } from './plugin'; + +describe('cost-insights', () => { + it('should export plugin', () => { + expect(plugin).toBeDefined(); + }); +}); diff --git a/plugins/cost-insights/src/plugin.ts b/plugins/cost-insights/src/plugin.ts new file mode 100644 index 0000000000..d8d54ae71b --- /dev/null +++ b/plugins/cost-insights/src/plugin.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createPlugin, createRouteRef } from '@backstage/core'; +import CostInsightsPage from './components/CostInsightsPage'; +import ProjectGrowthInstructionsPage from './components/ProjectGrowthInstructionsPage'; +import LabelDataflowInstructionsPage from './components/LabelDataflowInstructionsPage'; + +export const rootRouteRef = createRouteRef({ + path: '/cost-insights', + title: 'Cost Insights', +}); + +export const projectGrowthAlertRef = createRouteRef({ + path: '/cost-insights/investigating-growth', + title: 'Investigating Growth', +}); + +export const unlabeledDataflowAlertRef = createRouteRef({ + path: '/cost-insights/labeling-jobs', + title: 'Labeling Dataflow Jobs', +}); + +export const plugin = createPlugin({ + id: 'cost-insights', + register({ router, featureFlags }) { + router.addRoute(rootRouteRef, CostInsightsPage); + router.addRoute(projectGrowthAlertRef, ProjectGrowthInstructionsPage); + router.addRoute(unlabeledDataflowAlertRef, LabelDataflowInstructionsPage); + featureFlags.register('cost-insights-currencies'); + }, +}); diff --git a/plugins/identity-backend/src/setupTests.ts b/plugins/cost-insights/src/setupTests.ts similarity index 94% rename from plugins/identity-backend/src/setupTests.ts rename to plugins/cost-insights/src/setupTests.ts index f7b6ca962d..8553642152 100644 --- a/plugins/identity-backend/src/setupTests.ts +++ b/plugins/cost-insights/src/setupTests.ts @@ -14,6 +14,6 @@ * limitations under the License. */ -require('jest-fetch-mock').enableMocks(); +import '@testing-library/jest-dom'; -export {}; +require('jest-fetch-mock').enableMocks(); diff --git a/plugins/cost-insights/src/types/Alert.ts b/plugins/cost-insights/src/types/Alert.ts new file mode 100644 index 0000000000..8d560096e3 --- /dev/null +++ b/plugins/cost-insights/src/types/Alert.ts @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ChangeStatistic } from './ChangeStatistic'; +import { Maybe } from './Maybe'; + +export type Alert = ProjectGrowthAlert | UnlabeledDataflowAlert; + +export interface AlertProps { + alert: Alert; +} + +export enum AlertType { + ProjectGrowth = 'projectGrowth', + UnlabeledDataflow = 'unlabeledDataflow', +} + +export interface AlertCost { + id: string; + aggregation: [number, number]; +} + +export interface ResourceData { + previous: number; + current: number; + name: Maybe; +} + +export interface BarChartData { + previousFill: string; + currentFill: string; + previousName: string; + currentName: string; +} + +export enum DataKey { + Previous = 'previous', + Current = 'current', + Name = 'name', +} + +export interface ProjectGrowthAlert { + id: AlertType.ProjectGrowth; + project: string; + periodStart: string; + periodEnd: string; + aggregation: [number, number]; + change: ChangeStatistic; + products: Array; +} + +export interface UnlabeledDataflowAlert { + id: AlertType.UnlabeledDataflow; + periodStart: string; + periodEnd: string; + projects: Array; + unlabeledCost: number; + labeledCost: number; +} + +export interface UnlabeledDataflowAlertProject { + id: string; + unlabeledCost: number; + labeledCost: number; +} diff --git a/plugins/cost-insights/src/types/ChangeStatistic.ts b/plugins/cost-insights/src/types/ChangeStatistic.ts new file mode 100644 index 0000000000..538692bb1d --- /dev/null +++ b/plugins/cost-insights/src/types/ChangeStatistic.ts @@ -0,0 +1,48 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface ChangeStatistic { + // The ratio of change from one duration to another, expressed as: (newSum - oldSum) / oldSum + ratio: number; + // The actual USD change between time periods (can be negative if costs decreased) + amount: number; +} + +export const EngineerThreshold = 0.5; + +export enum ChangeThreshold { + upper = 0.05, + lower = -0.05, +} + +export enum Growth { + Negligible, + Savings, + Excess, +} + +// Used by for displaying status colors +export function growthOf(amount: number, ratio: number) { + if (amount >= EngineerThreshold && ratio >= ChangeThreshold.upper) { + return Growth.Excess; + } + + if (amount >= EngineerThreshold && ratio <= ChangeThreshold.lower) { + return Growth.Savings; + } + + return Growth.Negligible; +} diff --git a/plugins/cost-insights/src/types/Cost.ts b/plugins/cost-insights/src/types/Cost.ts new file mode 100644 index 0000000000..84a8bfae51 --- /dev/null +++ b/plugins/cost-insights/src/types/Cost.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DateAggregation } from './DateAggregation'; +import { ChangeStatistic } from './ChangeStatistic'; +import { Trendline } from './Trendline'; + +export interface Cost { + id: string; + aggregation: DateAggregation[]; + change: ChangeStatistic; + trendline: Trendline; +} diff --git a/plugins/cost-insights/src/types/Currency.ts b/plugins/cost-insights/src/types/Currency.ts new file mode 100644 index 0000000000..633e405893 --- /dev/null +++ b/plugins/cost-insights/src/types/Currency.ts @@ -0,0 +1,78 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Duration } from './Duration'; +import { assertNever } from './Maybe'; + +export enum CurrencyType { + USD = 'USD', + CarbonOffsetTons = 'CARBON_OFFSET_TONS', + Beers = 'BEERS', + IceCream = 'PINTS_OF_ICE_CREAM', +} + +export interface Currency { + kind: string | null; + label: string; + unit: string; + prefix?: string; + rate?: number; +} + +export const rateOf = (cost: number, duration: Duration) => { + switch (duration) { + case Duration.P1M: + case Duration.P30D: + return cost / 12; + case Duration.P90D: + case Duration.P3M: + return cost / 4; + default: + return assertNever(duration); + } +}; + +export const defaultCurrencies: Currency[] = [ + { + kind: null, + label: 'Engineers 🛠', + unit: 'engineer', + }, + { + kind: CurrencyType.USD, + label: 'US Dollars đŸ’ĩ', + unit: 'dollar', + prefix: '$', + rate: 1, + }, + { + kind: CurrencyType.CarbonOffsetTons, + label: 'Carbon Offset Tons â™ģī¸âš–ī¸s', + unit: 'carbon offset ton', + rate: 3.5, + }, + { + kind: CurrencyType.Beers, + label: 'Beers đŸē', + unit: 'beer', + rate: 4.5, + }, + { + kind: CurrencyType.IceCream, + label: 'Pints of Ice Cream đŸĻ', + unit: 'ice cream pint', + rate: 5.5, + }, +]; diff --git a/plugins/cost-insights/src/types/DateAggregation.ts b/plugins/cost-insights/src/types/DateAggregation.ts new file mode 100644 index 0000000000..807387a265 --- /dev/null +++ b/plugins/cost-insights/src/types/DateAggregation.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type DateAggregation = { + date: string; // YYYY-MM-DD + amount: number; +}; diff --git a/plugins/cost-insights/src/types/Duration.test.ts b/plugins/cost-insights/src/types/Duration.test.ts new file mode 100644 index 0000000000..5b9f7b4a9b --- /dev/null +++ b/plugins/cost-insights/src/types/Duration.test.ts @@ -0,0 +1,32 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Duration, inclusiveEndDateOf, inclusiveStartDateOf } from './Duration'; + +Date.now = jest.fn(() => new Date(Date.parse('2020-06-05')).valueOf()); + +describe.each` + duration | startDate | endDate + ${Duration.P30D} | ${'2020-04-06'} | ${'2020-06-05'} + ${Duration.P90D} | ${'2019-12-08'} | ${'2020-06-05'} + ${Duration.P1M} | ${'2020-04-01'} | ${'2020-05-31'} + ${Duration.P3M} | ${'2019-10-01'} | ${'2020-03-31'} +`('Calculates interval dates correctly', ({ duration, startDate, endDate }) => { + it(`Calculates dates correctly for ${duration}`, () => { + expect(inclusiveStartDateOf(duration)).toBe(startDate); + expect(inclusiveEndDateOf(duration)).toBe(endDate); + }); +}); diff --git a/plugins/cost-insights/src/types/Duration.ts b/plugins/cost-insights/src/types/Duration.ts new file mode 100644 index 0000000000..6e6c5b1100 --- /dev/null +++ b/plugins/cost-insights/src/types/Duration.ts @@ -0,0 +1,85 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import moment from 'moment'; +import { assertNever } from './Maybe'; + +/** + * Time periods for cost comparison; slight abuse of ISO 8601 periods. We take P1M and P3M to mean + * 'last completed [month|quarter]', and P30D/P90D to be '[month|quarter] relative to today'. So if + * it's September 15, P1M represents costs for the month of August and P30D represents August 16 - + * September 15. + */ +export enum Duration { + P30D = 'P30D', + P90D = 'P90D', + P1M = 'P1M', + P3M = 'P3M', +} + +export const DEFAULT_DATE_FORMAT = 'YYYY-MM-DD'; + +// Derive the start date of a given period, assuming two repeating intervals +export function inclusiveStartDateOf(duration: Duration): string { + switch (duration) { + case Duration.P30D: + case Duration.P90D: + return moment() + .utc() + .subtract(moment.duration(duration).add(moment.duration(duration))) + .format(DEFAULT_DATE_FORMAT); + case Duration.P1M: + return moment() + .utc() + .startOf('month') + .subtract(moment.duration(duration).add(moment.duration(duration))) + .format(DEFAULT_DATE_FORMAT); + case Duration.P3M: + return moment() + .utc() + .startOf('quarter') + .subtract(moment.duration(duration).add(moment.duration(duration))) + .format(DEFAULT_DATE_FORMAT); + default: + return assertNever(duration); + } +} + +export function exclusiveEndDateOf(duration: Duration): string { + switch (duration) { + case Duration.P30D: + case Duration.P90D: + return moment().utc().add(1, 'day').format(DEFAULT_DATE_FORMAT); + case Duration.P1M: + return moment().utc().startOf('month').format(DEFAULT_DATE_FORMAT); + case Duration.P3M: + return moment().utc().startOf('quarter').format(DEFAULT_DATE_FORMAT); + default: + return assertNever(duration); + } +} + +export function inclusiveEndDateOf(duration: Duration): string { + return moment(exclusiveEndDateOf(duration)) + .utc() + .subtract(1, 'day') + .format(DEFAULT_DATE_FORMAT); +} + +// https://en.wikipedia.org/wiki/ISO_8601#Repeating_intervals +export function intervalsOf(duration: Duration) { + return `R2/${duration}/${exclusiveEndDateOf(duration)}`; +} diff --git a/packages/backend/src/plugins/identity.ts b/plugins/cost-insights/src/types/Entity.ts similarity index 72% rename from packages/backend/src/plugins/identity.ts rename to plugins/cost-insights/src/types/Entity.ts index 63a326965c..f5ac620289 100644 --- a/packages/backend/src/plugins/identity.ts +++ b/plugins/cost-insights/src/types/Entity.ts @@ -14,9 +14,11 @@ * limitations under the License. */ -import { createRouter } from '@backstage/plugin-identity-backend'; -import { PluginEnvironment } from '../types'; +import { ChangeStatistic } from './ChangeStatistic'; +import { Maybe } from './Maybe'; -export default async function createPlugin({ logger }: PluginEnvironment) { - return await createRouter({ logger }); +export interface Entity { + id: Maybe; + aggregation: [number, number]; + change?: Maybe; } diff --git a/plugins/cost-insights/src/types/Filters.ts b/plugins/cost-insights/src/types/Filters.ts new file mode 100644 index 0000000000..def1d74d1a --- /dev/null +++ b/plugins/cost-insights/src/types/Filters.ts @@ -0,0 +1,44 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Maybe } from './Maybe'; +import { Duration } from './Duration'; +import { Group } from './Group'; + +export interface PageFilters { + group: Maybe; + project: Maybe; + duration: Duration; + metric: Maybe; +} + +export type ProductFilters = Array; + +export type QueryParams = PageFilters & { products: ProductFilters }; + +export interface ProductPeriod { + duration: Duration; + productType: string; +} + +export function getDefaultPageFilters(groups: Group[]): PageFilters { + return { + group: groups.length ? groups[0].id : null, + project: null, + duration: Duration.P90D, + metric: null, + }; +} diff --git a/plugins/cost-insights/src/types/Group.ts b/plugins/cost-insights/src/types/Group.ts new file mode 100644 index 0000000000..3aef92e5b9 --- /dev/null +++ b/plugins/cost-insights/src/types/Group.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type Group = { + id: string; +}; diff --git a/plugins/cost-insights/src/types/Icon.ts b/plugins/cost-insights/src/types/Icon.ts new file mode 100644 index 0000000000..70f43a6813 --- /dev/null +++ b/plugins/cost-insights/src/types/Icon.ts @@ -0,0 +1,29 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type Icon = { + kind: string; + component: JSX.Element; +}; + +export enum IconType { + Compute = 'compute', + Data = 'data', + Database = 'database', + Storage = 'storage', + Search = 'search', + ML = 'ml', +} diff --git a/plugins/cost-insights/src/types/Loading.ts b/plugins/cost-insights/src/types/Loading.ts new file mode 100644 index 0000000000..f5da1d2b07 --- /dev/null +++ b/plugins/cost-insights/src/types/Loading.ts @@ -0,0 +1,63 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type Loading = Record; + +export enum DefaultLoadingAction { + UserGroups = 'user-groups', + CostInsightsInitial = 'cost-insights-initial', + CostInsightsPage = 'cost-insights-page', +} + +export const INITIAL_LOADING_ACTIONS = [ + DefaultLoadingAction.UserGroups, + DefaultLoadingAction.CostInsightsInitial, +]; + +export const getDefaultState = (loadingActions: string[]): Loading => { + return loadingActions.reduce( + (defaultState, action) => ({ ...defaultState, [action]: true }), + {}, + ); +}; + +export const getResetState = (loadingActions: string[]): Loading => { + return loadingActions.reduce( + (defaultState, action) => ({ ...defaultState, [action]: false }), + {}, + ); +}; + +export const getResetStateWithoutInitial = ( + loadingActions: string[], +): Loading => { + return loadingActions.reduce((defaultState, action) => { + const loadingActionState = (INITIAL_LOADING_ACTIONS as string[]).includes( + action, + ) + ? false + : true; + return { ...defaultState, [action]: loadingActionState }; + }, {}); +}; + +export function getLoadingActions(products: string[]): string[] { + return ([ + DefaultLoadingAction.UserGroups, + DefaultLoadingAction.CostInsightsInitial, + DefaultLoadingAction.CostInsightsPage, + ] as string[]).concat(products); +} diff --git a/plugins/cost-insights/src/types/Maybe.ts b/plugins/cost-insights/src/types/Maybe.ts new file mode 100644 index 0000000000..d721f28d75 --- /dev/null +++ b/plugins/cost-insights/src/types/Maybe.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type Maybe = T | null; + +export function notEmpty( + value: TValue | null | undefined, +): value is TValue { + return value !== null && value !== undefined; +} + +// Utility for exhaustiveness checking in switch statements +export function assertNever(x: never): never { + throw new Error(`Exhaustiveness check failed: ${x}`); +} + +export function assertAlways(argument: T | undefined): T { + if (argument === undefined) { + throw new TypeError( + 'Expected to always find a value but received undefined', + ); + } + return argument; +} + +// Utility for working with static lists; asserts a value will always be found or +// throws an error +export function findAlways( + collection: T[], + callback: (el: T) => boolean, +): T { + return assertAlways(collection.find(callback)); +} diff --git a/plugins/cost-insights/src/types/Metric.ts b/plugins/cost-insights/src/types/Metric.ts new file mode 100644 index 0000000000..5a440a8d1f --- /dev/null +++ b/plugins/cost-insights/src/types/Metric.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Maybe } from './Maybe'; + +export type Metric = { + kind: Maybe; + name: string; +}; diff --git a/plugins/cost-insights/src/types/Product.ts b/plugins/cost-insights/src/types/Product.ts new file mode 100644 index 0000000000..d2087644cb --- /dev/null +++ b/plugins/cost-insights/src/types/Product.ts @@ -0,0 +1,30 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Entity } from './Entity'; +import { ChangeStatistic } from './ChangeStatistic'; +import { Maybe } from './Maybe'; + +export interface Product { + kind: string; + name: string; +} + +export interface ProductCost { + entities?: Array; + aggregation: [number, number]; + change?: Maybe; +} diff --git a/plugins/cost-insights/src/types/Project.ts b/plugins/cost-insights/src/types/Project.ts new file mode 100644 index 0000000000..24259f6910 --- /dev/null +++ b/plugins/cost-insights/src/types/Project.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export interface Project { + id: string; +} diff --git a/plugins/cost-insights/src/types/Theme.ts b/plugins/cost-insights/src/types/Theme.ts new file mode 100644 index 0000000000..9053283351 --- /dev/null +++ b/plugins/cost-insights/src/types/Theme.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BackstagePalette, BackstageTheme } from '@backstage/theme'; +import { PaletteOptions } from '@material-ui/core/styles/createPalette'; + +type CostInsightsTooltipOptions = { + background: string; + color: string; +}; + +type CostInsightsPaletteAdditions = { + blue: string; + lightBlue: string; + darkBlue: string; + magenta: string; + yellow: string; + tooltip: CostInsightsTooltipOptions; + navigationText: string; + alertBackground: string; +}; + +export type CostInsightsPalette = BackstagePalette & + CostInsightsPaletteAdditions; + +export type CostInsightsPaletteOptions = PaletteOptions & + CostInsightsPaletteAdditions; + +export interface CostInsightsThemeOptions extends PaletteOptions { + palette: CostInsightsPaletteOptions; +} + +export interface CostInsightsTheme extends BackstageTheme { + palette: CostInsightsPalette; +} diff --git a/plugins/cost-insights/src/types/Trendline.ts b/plugins/cost-insights/src/types/Trendline.ts new file mode 100644 index 0000000000..aad7ba0bac --- /dev/null +++ b/plugins/cost-insights/src/types/Trendline.ts @@ -0,0 +1,19 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type Trendline = { + slope: number; + intercept: number; +}; diff --git a/plugins/cost-insights/src/types/index.ts b/plugins/cost-insights/src/types/index.ts new file mode 100644 index 0000000000..c3d9a87886 --- /dev/null +++ b/plugins/cost-insights/src/types/index.ts @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './Alert'; +export * from './ChangeStatistic'; +export * from './Cost'; +export * from './DateAggregation'; +export * from './Duration'; +export * from './Currency'; +export * from './Entity'; +export * from './Icon'; +export * from './Filters'; +export * from './Group'; +export * from './Loading'; +export * from './Maybe'; +export * from './Metric'; +export * from './Product'; +export * from './Project'; +export * from './Theme'; +export * from './Trendline'; diff --git a/plugins/cost-insights/src/utils/alerts.tsx b/plugins/cost-insights/src/utils/alerts.tsx new file mode 100644 index 0000000000..07602be191 --- /dev/null +++ b/plugins/cost-insights/src/utils/alerts.tsx @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { Alert, AlertType, assertNever } from '../types'; +import ProjectGrowthAlertCard from '../components/ProjectGrowthAlertCard'; +import UnlabeledDataflowAlertCard from '../components/UnlabeledDataflowAlertCard'; + +export function getAlertText(alert: Alert) { + switch (alert.id) { + case AlertType.ProjectGrowth: + return { + title: `Investigate cost growth in project ${alert.project}`, + subtitle: + 'Cost growth outpacing business growth is unsustainable long-term.', + } as AlertText; + case AlertType.UnlabeledDataflow: + return { + title: 'Add labels to workflows', + subtitle: + 'Labels show in billing data, enabling cost insights for each workflow.', + }; + default: + return assertNever(alert); + } +} + +export function getAlertUrl(alert: Alert) { + switch (alert.id) { + case AlertType.ProjectGrowth: + return '/cost-insights/investigating-growth' as AlertUrl; + case AlertType.UnlabeledDataflow: + return '/cost-insights/labeling-jobs' as AlertUrl; + default: + return assertNever(alert); + } +} + +export function getAlertButtonText(alert: Alert) { + switch (alert.id) { + case AlertType.ProjectGrowth: + case AlertType.UnlabeledDataflow: + return 'View Instructions' as AlertButtonText; + default: + return assertNever(alert); + } +} + +export function getAlertNavigation(alert: Alert, number: number) { + return `${alert.id}-${number}`; +} + +export function renderAlert(alert: Alert) { + switch (alert.id) { + case AlertType.ProjectGrowth: + return ; + case AlertType.UnlabeledDataflow: + return ; + default: + return assertNever(alert); + } +} + +export type AlertUrl = string; +export type AlertButtonText = string; + +export interface AlertText { + title: string; + subtitle: string; +} diff --git a/plugins/cost-insights/src/utils/formatters.test.ts b/plugins/cost-insights/src/utils/formatters.test.ts new file mode 100644 index 0000000000..a76e838b53 --- /dev/null +++ b/plugins/cost-insights/src/utils/formatters.test.ts @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { lengthyCurrencyFormatter, quarterOf } from './formatters'; + +Date.now = jest.fn(() => new Date(Date.parse('2019-12-07')).valueOf()); + +describe('date formatters', () => { + it('Formats quarters', () => { + expect(quarterOf('2020-01-01')).toBe('Q1 2020'); + expect(quarterOf('2020-02-29')).toBe('Q1 2020'); + expect(quarterOf('2020-05-11')).toBe('Q2 2020'); + expect(quarterOf('2020-06-30')).toBe('Q2 2020'); + expect(quarterOf('2020-07-01')).toBe('Q3 2020'); + expect(quarterOf('2020-10-04')).toBe('Q4 2020'); + }); + + it('Correctly formats values to two significant digits', () => { + const values = [ + 0.00000040925, + 0.21, + 0.0000004, + 0.4139877878, + 0.00000234566, + ]; + const formattedValues = values.map(val => + lengthyCurrencyFormatter.format(val), + ); + expect(formattedValues).toEqual([ + '$0.00000041', + '$0.21', + '$0.00000040', + '$0.41', + '$0.0000023', + ]); + }); +}); diff --git a/plugins/cost-insights/src/utils/formatters.ts b/plugins/cost-insights/src/utils/formatters.ts new file mode 100644 index 0000000000..f3790f315e --- /dev/null +++ b/plugins/cost-insights/src/utils/formatters.ts @@ -0,0 +1,126 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import moment from 'moment'; +import { + Duration, + inclusiveEndDateOf, + inclusiveStartDateOf, +} from '../types/Duration'; +import { pluralOf } from '../utils/grammar'; + +export type Period = { + periodStart: string; + periodEnd: string; +}; + +export const currencyFormatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 0, + maximumFractionDigits: 0, +}); + +export const lengthyCurrencyFormatter = new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 0, + minimumSignificantDigits: 2, + maximumSignificantDigits: 2, +}); + +export const numberFormatter = new Intl.NumberFormat('en-US', { + minimumFractionDigits: 0, + maximumFractionDigits: 0, +}); + +export const monthFormatter = new Intl.DateTimeFormat('en-US', { + timeZone: 'UTC', + month: 'long', + year: 'numeric', +}); + +export const dateFormatter = new Intl.DateTimeFormat('en-US', { + timeZone: 'UTC', + day: 'numeric', + month: 'short', +}); + +export const monthOf = (date: string): string => { + return monthFormatter.format(Date.parse(date)); +}; + +export const quarterOf = (date: string): string => { + // Supports formatting YYYY-MM-DD and YYYY-[Q]Q returned in alerts + const d = moment(date).isValid() ? moment(date) : moment(date, 'YYYY-[Q]Q'); + return d.format('[Q]Q YYYY'); +}; + +export function formatCurrency(amount: number, currency?: string): string { + const n = Math.round(amount); + const numString = numberFormatter.format(n); + + return currency ? `${numString} ${pluralOf(n, currency)}` : numString; +} + +export function formatPercent(n: number): string { + // Number.toFixed shows scientific notation for extreme numbers + if (isNaN(n) || Math.abs(n) < 0.01) { + return '0%'; + } + if (Math.abs(n) >= 1e19) { + return '∞%'; + } + return `${(n * 100).toFixed(0)}%`; +} + +export const formatLastTwoLookaheadQuarters = () => { + const start = moment(inclusiveStartDateOf(Duration.P3M)).format('[Q]Q YYYY'); + const end = moment(inclusiveEndDateOf(Duration.P3M)).format('[Q]Q YYYY'); + return `${start} vs ${end}`; +}; + +export const formatLastTwoMonths = () => { + const start = moment(inclusiveStartDateOf(Duration.P1M)).utc().format('MMMM'); + const end = moment(inclusiveEndDateOf(Duration.P1M)).utc().format('MMMM'); + return `${start} vs ${end}`; +}; + +export const dateRegex: RegExp = /^\d{4}-\d{2}-\d{2}$/; + +export const formatRelativeDuration = ( + date: string, + duration: Duration, +): string => { + const periodStart = inclusiveStartDateOf(duration); + const periodEnd = inclusiveEndDateOf(duration); + const days = moment.duration(duration).asDays(); + if (![periodStart, periodEnd].includes(date)) { + throw new Error(`Invalid relative date ${date} for duration ${duration}`); + } + return date === periodStart ? `First ${days} Days` : `Last ${days} Days`; +}; + +export function formatDuration(date: string, duration: Duration) { + switch (duration) { + case Duration.P1M: + return monthOf(date); + case Duration.P3M: + return quarterOf(date); + default: + return formatRelativeDuration(date, duration); + } +} diff --git a/plugins/cost-insights/src/utils/grammar.ts b/plugins/cost-insights/src/utils/grammar.ts new file mode 100644 index 0000000000..653c567d0a --- /dev/null +++ b/plugins/cost-insights/src/utils/grammar.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const vowels = { + a: 'A', + e: 'E', + i: 'I', + o: 'O', + u: 'U', +}; + +export const pluralOf = ( + n: number, + string: string, + plural?: string, +): string => { + if (n !== 1) { + if (plural) { + return plural; + } + return string.concat('s'); + } + return string; +}; + +export const indefiniteArticleOf = ( + articles: [string, string], + word: string, +) => { + const firstChar = word.charAt(0).toLowerCase(); + return firstChar in vowels + ? `${articles[1]} ${word}` + : `${articles[0]} ${word}`; +}; diff --git a/plugins/identity-backend/src/adapters/types.ts b/plugins/cost-insights/src/utils/graphs.tsx similarity index 59% rename from plugins/identity-backend/src/adapters/types.ts rename to plugins/cost-insights/src/utils/graphs.tsx index 59fd1324d1..5200b14b1f 100644 --- a/plugins/identity-backend/src/adapters/types.ts +++ b/plugins/cost-insights/src/utils/graphs.tsx @@ -14,29 +14,18 @@ * limitations under the License. */ -export type User = { - name: string; -}; +import { + currencyFormatter, + dateFormatter, + lengthyCurrencyFormatter, +} from './formatters'; -export type Group = { - name: string; - type: string; - members?: User[]; - children?: Group[]; -}; - -export type GroupsJson = { - groups: Group[]; -}; - -export type GroupsResponse = { - groups: Group[]; -}; - -export type GroupsRequest = { - user: string; - type: string; -}; -export interface IdentityApi { - getUserGroups(req: GroupsRequest): Promise; +export function formatGraphValue(value: number) { + if (value < 1) { + return lengthyCurrencyFormatter.format(value); + } + return currencyFormatter.format(value); } + +export const overviewGraphTickFormatter = (millis: string | number) => + typeof millis === 'number' ? dateFormatter.format(millis) : millis; diff --git a/plugins/cost-insights/src/utils/history.ts b/plugins/cost-insights/src/utils/history.ts new file mode 100644 index 0000000000..71e8e2c219 --- /dev/null +++ b/plugins/cost-insights/src/utils/history.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import qs from 'qs'; +import { QueryParams } from '../types'; + +export const stringify = (queryParams: Partial) => + qs.stringify(queryParams, { strictNullHandling: true }); +export const parse = (queryString: string): Partial => + qs.parse(queryString, { ignoreQueryPrefix: true, strictNullHandling: true }); diff --git a/plugins/cost-insights/src/utils/mockData.ts b/plugins/cost-insights/src/utils/mockData.ts new file mode 100644 index 0000000000..87dbcf8158 --- /dev/null +++ b/plugins/cost-insights/src/utils/mockData.ts @@ -0,0 +1,194 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + AlertType, + Entity, + ProjectGrowthAlert, + Product, + UnlabeledDataflowAlert, + UnlabeledDataflowAlertProject, + getDefaultState, + DefaultLoadingAction, + Duration, + ProductCost, + findAlways, +} from '../types'; +import { Config } from '@backstage/config'; +import { ConfigApi } from '@backstage/core'; + +type mockAlertRenderer = (alert: T) => T; +type mockEntityRenderer = (entity: T) => T; + +export const createMockEntity = ( + callback?: mockEntityRenderer, +): Entity => { + const defaultEntity: Entity = { + id: 'test-entity', + aggregation: [100, 200], + }; + + if (typeof callback === 'function') { + return callback({ ...defaultEntity }); + } + return { ...defaultEntity }; +}; + +export const createMockProduct = ( + callback?: mockEntityRenderer, +): Product => { + const defaultProduct: Product = { + kind: 'compute-engine', + name: 'Compute Engine', + }; + if (typeof callback === 'function') { + return callback({ ...defaultProduct }); + } + return { ...defaultProduct }; +}; + +export const createMockProductCost = ( + callback?: mockEntityRenderer, +): ProductCost => { + const defaultProduct: ProductCost = { + entities: [], + aggregation: [0, 0], + }; + if (typeof callback === 'function') { + return callback({ ...defaultProduct }); + } + return { ...defaultProduct }; +}; + +export const createMockProjectGrowthAlert = ( + callback?: mockAlertRenderer, +): ProjectGrowthAlert => { + const defaultAlert: ProjectGrowthAlert = { + id: AlertType.ProjectGrowth, + project: 'test-project-growth-alert', + periodStart: '2019-10-01', + periodEnd: '2020-03-31', + aggregation: [670532.1, 970502.8], + change: { + ratio: 0.5, + amount: 180000, + }, + products: [], + }; + + if (typeof callback === 'function') { + return callback({ ...defaultAlert }); + } + + return { ...defaultAlert }; +}; + +export const createMockUnlabeledDataflowAlert = ( + callback?: mockAlertRenderer, +): UnlabeledDataflowAlert => { + const defaultAlert: UnlabeledDataflowAlert = { + id: AlertType.UnlabeledDataflow, + periodStart: '2020-05-01', + periodEnd: '2020-06-1', + projects: [], + unlabeledCost: 0, + labeledCost: 0, + }; + + if (typeof callback === 'function') { + return callback({ ...defaultAlert }); + } + + return { ...defaultAlert }; +}; + +export const createMockUnlabeledDataflowAlertProject = ( + callback?: mockEntityRenderer, +): UnlabeledDataflowAlertProject => { + const defaultProject: UnlabeledDataflowAlertProject = { + id: 'test-alert-project', + unlabeledCost: 2000.0, + labeledCost: 3200.0, + }; + if (typeof callback === 'function') { + return callback({ ...defaultProject }); + } + return { ...defaultProject }; +}; + +export const MockProductTypes: Record = { + 'compute-engine': 'Compute Engine', + 'cloud-dataflow': 'Cloud Dataflow', + 'cloud-storage': 'Cloud Storage', + 'big-query': 'Big Query', + 'big-table': 'BigTable', + 'cloud-pub-sub': 'Cloud Pub/Sub', +}; + +export const MockProductFilters = Object.keys( + MockProductTypes, +).map(productType => ({ duration: Duration.P1M, productType })); + +export const MockProducts: Product[] = Object.keys(MockProductTypes).map( + productType => + createMockProduct(() => ({ + kind: productType, + name: MockProductTypes[productType], + })), +); + +export const MockLoadingActions = ([ + DefaultLoadingAction.UserGroups, + DefaultLoadingAction.CostInsightsInitial, + DefaultLoadingAction.CostInsightsPage, +] as string[]).concat(MockProducts.map(product => product.kind)); + +export const mockDefaultState = getDefaultState(MockLoadingActions); + +export const MockComputeEngine = findAlways( + MockProducts, + p => p.kind === 'compute-engine', +); +export const MockCloudDataflow = findAlways( + MockProducts, + p => p.kind === 'cloud-dataflow', +); +export const MockCloudStorage = findAlways( + MockProducts, + p => p.kind === 'cloud-storage', +); +export const MockBigQuery = findAlways( + MockProducts, + p => p.kind === 'big-query', +); +export const MockBigtable = findAlways( + MockProducts, + p => p.kind === 'big-table', +); + +export const MockProductsConfig: Partial = { + keys: () => Object.keys(MockProductTypes), +}; + +export const MockMetricsConfig: Partial = { + getOptionalString: () => 'daily-cost', + keys: () => ['daily-cost'], +}; + +export const MockCostInsightsConfig: Partial = { + getConfig: () => MockProductsConfig as Config, + getOptionalConfig: () => MockMetricsConfig as Config, +}; diff --git a/plugins/cost-insights/src/utils/navigation.tsx b/plugins/cost-insights/src/utils/navigation.tsx new file mode 100644 index 0000000000..d2cb1d20bb --- /dev/null +++ b/plugins/cost-insights/src/utils/navigation.tsx @@ -0,0 +1,74 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import MoneyIcon from '@material-ui/icons/MonetizationOn'; +import ActionIcon from '@material-ui/icons/Whatshot'; +import Settings from '@material-ui/icons/Settings'; +import AccountTree from '@material-ui/icons/AccountTree'; +import Storage from '@material-ui/icons/Storage'; +import Search from '@material-ui/icons/Search'; +import CloudQueue from '@material-ui/icons/CloudQueue'; +import School from '@material-ui/icons/School'; +import ViewHeadline from '@material-ui/icons/ViewHeadline'; +import { IconType } from '../types'; + +export enum DefaultNavigation { + CostOverviewCard = 'cost-overview-card', + AlertInsightsHeader = 'alert-insights-header', +} + +export type NavigationItem = { + navigation: string; + icon: JSX.Element; + title: string; +}; + +export const getDefaultNavigationItems = (alerts: number): NavigationItem[] => { + const items = [ + { + navigation: DefaultNavigation.CostOverviewCard, + icon: , + title: 'Cost Overview', + }, + ]; + if (alerts > 0) { + items.push({ + navigation: DefaultNavigation.AlertInsightsHeader, + icon: , + title: 'Action Items', + }); + } + return items; +}; + +export function getIcon(icon?: string): JSX.Element { + switch (icon) { + case IconType.Compute: + return ; + case IconType.Data: + return ; + case IconType.Database: + return ; + case IconType.Storage: + return ; + case IconType.Search: + return ; + case IconType.ML: + return ; + default: + return ; + } +} diff --git a/plugins/cost-insights/src/utils/sort.test.ts b/plugins/cost-insights/src/utils/sort.test.ts new file mode 100644 index 0000000000..2f4ca87c7e --- /dev/null +++ b/plugins/cost-insights/src/utils/sort.test.ts @@ -0,0 +1,32 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { aggregationSort } from './sort'; + +describe('aggregationSort', () => { + const aggregation = [ + { date: '2020-07-05', amount: 0.250991 }, + { date: '2020-07-06', amount: 0.253284 }, + { date: '2020-07-01', amount: 0.260798 }, + ]; + + it('sorts in ascending order', () => { + const sortedAggregation = aggregation.sort(aggregationSort); + expect(sortedAggregation[0].date).toBe('2020-07-01'); + expect(sortedAggregation[1].date).toBe('2020-07-05'); + expect(sortedAggregation[2].date).toBe('2020-07-06'); + }); +}); diff --git a/plugins/cost-insights/src/utils/sort.ts b/plugins/cost-insights/src/utils/sort.ts new file mode 100644 index 0000000000..944f5fc806 --- /dev/null +++ b/plugins/cost-insights/src/utils/sort.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DateAggregation, ResourceData } from '../types'; + +export const aggregationSort = ( + a: DateAggregation, + b: DateAggregation, +): number => a.date.localeCompare(b.date); +export const resourceSort = (a: ResourceData, b: ResourceData) => + b.previous + b.current - (a.previous + a.current); diff --git a/plugins/cost-insights/src/utils/styles.ts b/plugins/cost-insights/src/utils/styles.ts new file mode 100644 index 0000000000..e6b38ee719 --- /dev/null +++ b/plugins/cost-insights/src/utils/styles.ts @@ -0,0 +1,455 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + createStyles, + darken, + getLuminance, + lighten, + makeStyles, +} from '@material-ui/core'; +import { BackstageTheme } from '@backstage/theme'; +import { CostInsightsTheme, CostInsightsThemeOptions } from '../types'; + +export const costInsightsLightTheme = { + palette: { + blue: '#509AF5', + lightBlue: '#9BF0E1', + darkBlue: '#4101F5', + magenta: '#DC148C', + yellow: '#FFC864', + tooltip: { + background: '#171717', + color: '#DDD', + }, + navigationText: '#b5b5b5', + alertBackground: 'rgba(219, 219, 219, 0.13)', + }, +} as CostInsightsThemeOptions; + +// Higher tonal values from light theme (Google recommends 600 -> 200) +// https://material.io/design/color/the-color-system.html#tools-for-picking-colors +export const costInsightsDarkTheme = { + palette: { + blue: '#77b8f9', + lightBlue: '#d8f9f4', + darkBlue: '#b595fd', + magenta: '#ee93cd', + yellow: '#fff2da', + tooltip: { + background: '#EEE', + color: '#424242', + }, + navigationText: '#b5b5b5', + alertBackground: 'rgba(32, 32, 32, 0.13)', + }, +} as CostInsightsThemeOptions; + +// The opposite of MUI's emphasize function - darken darks, lighten lights +export function brighten(color: string, coefficient = 0.2) { + return getLuminance(color) > 0.5 + ? lighten(color, coefficient) + : darken(color, coefficient); +} + +export const useCostOverviewStyles = (theme: CostInsightsTheme) => ({ + axis: { + fill: theme.palette.text.primary, + }, + container: { + height: 450, + width: 1200, + }, + cartesianGrid: { + stroke: theme.palette.textVerySubtle, + }, + chart: { + margin: { + right: 30, + top: 16, + }, + }, + yAxis: { + width: 75, + }, +}); + +export const useBarChartStyles = (theme: CostInsightsTheme) => ({ + axis: { + fill: theme.palette.text.primary, + }, + barChart: { + margin: { + left: 16, + right: 16, + }, + }, + cartesianGrid: { + stroke: theme.palette.textVerySubtle, + }, + cursor: { + fill: theme.palette.textVerySubtle, + fillOpacity: 0.3, + }, + container: { + height: 400, + width: 1200, + }, + infoIcon: { + marginLeft: 2, + fontSize: '1.25em', + }, + xAxis: { + height: 50, + }, +}); + +export const useBarChartStepperButtonStyles = makeStyles( + (theme: CostInsightsTheme) => + createStyles({ + root: { + ...theme.typography.button, + boxSizing: 'border-box', + transition: theme.transitions.create( + ['background-color', 'box-shadow', 'border'], + { + duration: theme.transitions.duration.short, + }, + ), + borderRadius: '50%', + padding: 0, + width: 40, + height: 40, + boxShadow: theme.shadows[6], + '&:active': { + boxShadow: theme.shadows[12], + }, + color: theme.palette.text.primary, + backgroundColor: lighten(theme.palette.background.default, 0.1), + '&:hover': { + backgroundColor: lighten(theme.palette.background.default, 0.2), + textDecoration: 'none', + }, + }, + }), +); + +export const useBarChartLabelStyles = makeStyles(() => + createStyles({ + foreignObject: { + textAlign: 'center', + }, + label: { + display: 'block', + textDecoration: 'none', + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + }, + infoIcon: { + marginLeft: 2, + fontSize: '1.25em', + }, + }), +); + +export const useCostInsightsStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + h6Subtle: { + ...theme.typography.h6, + fontWeight: 'normal', + color: theme.palette.textSubtle, + }, + }), +); + +export const useCostInsightsTabsStyles = makeStyles( + (theme: BackstageTheme) => ({ + tabs: { + borderBottom: `1px solid ${theme.palette.textVerySubtle}`, + backgroundColor: brighten(theme.palette.background.default), + padding: theme.spacing(0, 4), + }, + tab: { + minHeight: 68, + minWidth: 180, + padding: theme.spacing(1, 4), + '&:hover': { + color: 'inherit', + backgroundColor: 'inherit', + }, + }, + indicator: { + backgroundColor: theme.palette.navigation.indicator, + height: 4, + }, + tabLabel: { + display: 'flex', + alignItems: 'center', + }, + tabLabelText: { + fontSize: theme.typography.fontSize, + fontWeight: theme.typography.fontWeightBold, + }, + menuItem: { + display: 'flex', + justifyContent: 'space-between', + alignItems: 'center', + minWidth: 180, + padding: theme.spacing(2, 2), + }, + menuItemSelected: { + backgroundColor: lighten(theme.palette.background.default, 0.3), + }, + }), +); + +export const useAlertCardActionHeaderStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + root: { + paddingBottom: theme.spacing(2), + borderRadius: 'unset', + }, + title: { + fontSize: theme.typography.fontSize, + fontWeight: theme.typography.fontWeightBold, + lineHeight: 1.5, + }, + action: { + margin: 0, + }, + }), +); + +export const useCostGrowthStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + excess: { + color: theme.palette.status.error, + }, + savings: { + color: theme.palette.status.ok, + }, + }), +); + +export const useCostGrowthLegendStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + h5: { + ...theme.typography.h5, + fontWeight: 500, + padding: 0, + }, + marker: { + display: 'inherit', + marginRight: theme.spacing(1), + }, + helpIcon: { + display: 'inherit', + }, + title: { + ...theme.typography.overline, + fontWeight: 500, + lineHeight: 0, + marginRight: theme.spacing(1), + color: theme.palette.textSubtle, + }, + tooltip: { + display: 'block', + padding: theme.spacing(1), + backgroundColor: theme.palette.navigation.background, + }, + tooltipText: { + color: theme.palette.background.default, + fontSize: theme.typography.fontSize, + lineHeight: 1.5, + }, + }), +); + +export const useBarChartStepperStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + paper: { + display: 'flex', + flexDirection: 'row', + justifyContent: 'space-around', + alignItems: 'center', + background: 'transparent', + padding: 8, + }, + step: { + backgroundColor: theme.palette.action.disabled, + borderRadius: '50%', + width: 9, + height: 9, + margin: '0 2px', + }, + stepActive: { + backgroundColor: theme.palette.primary.main, + }, + steps: { + display: 'flex', + flexDirection: 'row', + }, + backButton: { + position: 'absolute', + left: 0, + top: 'calc(50% - 60px)', + zIndex: 100, + }, + nextButton: { + position: 'absolute', + right: 0, + top: 'calc(50% - 60px)', + zIndex: 100, + }, + }), +); + +export const useNavigationStyles = makeStyles( + (theme: CostInsightsTheme) => + createStyles({ + menuList: { + borderRadius: theme.shape.borderRadius, + backgroundColor: theme.palette.navigation.background, + }, + menuItem: { + background: 'transparent', + border: 0, + textTransform: 'none', + width: '100%', + minHeight: theme.spacing(6), + margin: theme.spacing(0.5, 2, 0.5, 0), + }, + listItemIcon: { + minWidth: 40, + }, + navigationIcon: { + fill: theme.palette.navigationText, + }, + title: { + whiteSpace: 'nowrap', + lineHeight: 1, + color: theme.palette.navigationText, + fontWeight: theme.typography.fontWeightBold, + }, + }), +); + +export const useTooltipStyles = makeStyles( + (theme: CostInsightsTheme) => + createStyles({ + tooltip: { + padding: theme.spacing(1.5), + backgroundColor: theme.palette.tooltip.background, + borderRadius: theme.shape.borderRadius, + boxShadow: theme.shadows[1], + color: theme.palette.tooltip.color, + fontSize: theme.typography.fontSize, + }, + lensIcon: { + fontSize: `.75rem`, + }, + }), +); + +export const useAlertInsightsSectionStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + button: { + backgroundColor: theme.palette.textVerySubtle, + color: theme.palette.text.primary, + }, + }), +); + +export const useSelectStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + select: { + minWidth: 200, + textAlign: 'start', + }, + menuItem: { + minWidth: 200, + padding: theme.spacing(2), + '&.compact': { + padding: theme.spacing(1, 2), + }, + }, + }), +); + +export const useAlertActionCardStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + card: { + boxShadow: 'none', + }, + avatar: { + backgroundColor: theme.palette.textVerySubtle, + color: theme.palette.text.primary, + }, + }), +); + +export const useAlertActionCardHeader = makeStyles( + (theme: CostInsightsTheme) => + createStyles({ + root: { + paddingBottom: theme.spacing(2), + borderRadius: theme.shape.borderRadius, + cursor: 'pointer', + transition: theme.transitions.create('background', { + duration: theme.transitions.duration.short, + }), + '&:hover': { + background: theme.palette.alertBackground, + }, + }, + action: { + margin: 0, + }, + title: { + fontSize: theme.typography.fontSize, + fontWeight: theme.typography.fontWeightBold, + }, + }), +); + +export const useProductInsightsCardStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + root: { + padding: theme.spacing(2, 2, 2, 2.5), // restore backstage default padding + }, + action: { + margin: 0, // unset negative margins + }, + }), +); + +export const useBackdropStyles = makeStyles( + (theme: BackstageTheme) => + createStyles({ + root: { + zIndex: theme.zIndex.modal, + }, + }), +); diff --git a/plugins/cost-insights/src/utils/tests.tsx b/plugins/cost-insights/src/utils/tests.tsx new file mode 100644 index 0000000000..807232555b --- /dev/null +++ b/plugins/cost-insights/src/utils/tests.tsx @@ -0,0 +1,86 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React, { Dispatch, ReactNode, SetStateAction } from 'react'; +import { + getDefaultPageFilters, + PageFilters, + ProductFilters, + Group, +} from '../types'; +import { FilterContext } from '../hooks/useFilters'; +import { ConfigContext, ConfigContextProps } from '../hooks/useConfig'; +import { CurrencyContext, CurrencyContextProps } from '../hooks/useCurrency'; +import { ScrollContext, ScrollProviderProps } from '../hooks/useScroll'; +import { MockProductFilters } from './mockData'; + +export const MockGroups: Group[] = [{ id: 'tech' }, { id: 'mock-group' }]; + +type MockFilterProviderProps = { + setPageFilters: Dispatch>; + setProductFilters: Dispatch>; + children: ReactNode; +}; + +export const MockFilterProvider = ({ + setPageFilters, + setProductFilters, + children, +}: MockFilterProviderProps) => { + const pageFilters = getDefaultPageFilters(MockGroups); + return ( + + {children} + + ); +}; + +export const MockConfigProvider = ({ + metrics, + products, + icons, + engineerCost, + currencies, + children, +}: ConfigContextProps & { children: React.ReactNode }) => ( + + {children} + +); + +export const MockCurrencyProvider = ({ + currency, + setCurrency, + children, +}: CurrencyContextProps & { children: React.ReactNode }) => ( + + {children} + +); + +export const MockScrollProvider = ({ children }: ScrollProviderProps) => ( + + {children} + +); diff --git a/plugins/explore/package.json b/plugins/explore/package.json index 1a498f1dc2..2f25b4f137 100644 --- a/plugins/explore/package.json +++ b/plugins/explore/package.json @@ -41,7 +41,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/explore/src/components/ExplorePluginPage.tsx b/plugins/explore/src/components/ExplorePluginPage.tsx index 4365157f62..83402d8062 100644 --- a/plugins/explore/src/components/ExplorePluginPage.tsx +++ b/plugins/explore/src/components/ExplorePluginPage.tsx @@ -79,6 +79,13 @@ const toolsCards = [ 'https://storage.googleapis.com/wf-blogs-engineering-media/2018/09/fe13bb32-wf-tech-radar-hero-1024x597.png', tags: ['standards', 'landscape'], }, + { + title: 'Cost Insights', + description: 'Insights into cloud costs for your organization.', + url: '/cost-insights', + image: 'https://cloud.google.com/images/press/logo-cloud.png', + tags: ['cloud', 'finops'], + }, { title: 'GraphiQL', description: diff --git a/plugins/gcp-projects/package.json b/plugins/gcp-projects/package.json index 603fcf5a31..406b2428df 100644 --- a/plugins/gcp-projects/package.json +++ b/plugins/gcp-projects/package.json @@ -4,7 +4,6 @@ "main": "src/index.ts", "types": "src/index.ts", "license": "Apache-2.0", - "private": true, "publishConfig": { "access": "public", "main": "dist/index.esm.js", @@ -39,7 +38,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/github-actions/README.md b/plugins/github-actions/README.md index 24bc96937f..07a69cdfad 100644 --- a/plugins/github-actions/README.md +++ b/plugins/github-actions/README.md @@ -11,7 +11,7 @@ TBD ### Generic Requirements 1. Provide OAuth credentials: - 1. [Create an OAuth App](https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/) with callback URL set to `https://localhost:3000/auth/github`. + 1. [Create an OAuth App](https://developer.github.com/apps/building-oauth-apps/creating-an-oauth-app/) with callback URL set to `http://localhost:7000/api/auth/github`. 2. Take Client ID and Client Secret from the newly created app's settings page and put them into `AUTH_GITHUB_CLIENT_ID` and `AUTH_GITHUB_CLIENT_SECRET` env variables. 2. Annotate your component with a correct GitHub Actions repository and owner: diff --git a/plugins/github-actions/package.json b/plugins/github-actions/package.json index f7000407ac..5d85d8b3fa 100644 --- a/plugins/github-actions/package.json +++ b/plugins/github-actions/package.json @@ -47,7 +47,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.test.tsx b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.test.tsx new file mode 100644 index 0000000000..1d6001e038 --- /dev/null +++ b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.test.tsx @@ -0,0 +1,131 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Props as RecentWorkflowRunsCardProps } from './RecentWorkflowRunsCard'; +import React from 'react'; +import { render } from '@testing-library/react'; +import { RecentWorkflowRunsCard } from './RecentWorkflowRunsCard'; +import { ApiProvider, ApiRegistry, errorApiRef } from '@backstage/core-api'; +import { useWorkflowRuns } from '../useWorkflowRuns'; +import { ThemeProvider } from '@material-ui/core'; +import { lightTheme } from '@backstage/theme'; +import { MemoryRouter } from 'react-router'; + +jest.mock('../useWorkflowRuns', () => ({ + useWorkflowRuns: jest.fn(), +})); + +const mockErrorApi: jest.Mocked = { + post: jest.fn(), + error$: jest.fn(), +}; + +describe('', () => { + const entity = { + apiVersion: 'v1', + kind: 'Component', + metadata: { + name: 'software', + annotations: { + 'github.com/project-slug': 'theorg/the-service', + }, + }, + spec: { + owner: 'guest', + type: 'service', + lifecycle: 'production', + }, + }; + + const workflowRuns = [1, 2, 3, 4, 5].map(n => ({ + id: `run-id-${n}`, + message: `Commit message for workflow ${n}`, + source: { branchName: `branch-${n}` }, + status: 'completed', + })); + + beforeEach(() => { + (useWorkflowRuns as jest.Mock).mockReturnValue([{ runs: workflowRuns }]); + }); + + afterEach(() => { + jest.resetAllMocks(); + }); + + const renderSubject = (props: RecentWorkflowRunsCardProps = { entity }) => + render( + + + + + + + , + ); + + it('renders a table with a row for each workflow', async () => { + const subject = renderSubject(); + + workflowRuns.forEach(run => { + expect(subject.getByText(run.message)).toBeInTheDocument(); + }); + }); + + it('renders a workflow row correctly', async () => { + const subject = renderSubject(); + const [run] = workflowRuns; + expect(subject.getByText(run.message).closest('a')).toHaveAttribute( + 'href', + `/ci-cd/${run.id}`, + ); + expect(subject.getByText(run.source.branchName)).toBeInTheDocument(); + }); + + it('requests only the required number of workflow runs', async () => { + const limit = 3; + renderSubject({ entity, limit }); + expect(useWorkflowRuns).toHaveBeenCalledWith( + expect.objectContaining({ initialPageSize: limit }), + ); + }); + + it('uses the github repo and owner from the entity annotation', async () => { + renderSubject(); + expect(useWorkflowRuns).toHaveBeenCalledWith( + expect.objectContaining({ owner: 'theorg', repo: 'the-service' }), + ); + }); + + it('filters workflows by branch if one is specified', async () => { + const branch = 'master'; + renderSubject({ entity, branch }); + expect(useWorkflowRuns).toHaveBeenCalledWith( + expect.objectContaining({ branch }), + ); + }); + + describe('where there is an error fetching workflows', () => { + const error = 'error getting workflows'; + beforeEach(() => { + (useWorkflowRuns as jest.Mock).mockReturnValue([{ runs: [], error }]); + }); + + it('sends the error to the errorApi', async () => { + renderSubject(); + expect(mockErrorApi.post).toHaveBeenCalledWith(error); + }); + }); +}); diff --git a/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx new file mode 100644 index 0000000000..e5bba7fad9 --- /dev/null +++ b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.tsx @@ -0,0 +1,103 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Entity } from '@backstage/catalog-model'; +import { errorApiRef, useApi } from '@backstage/core-api'; +import { GITHUB_ACTIONS_ANNOTATION } from '../useProjectName'; +import { useWorkflowRuns } from '../useWorkflowRuns'; +import React, { useEffect } from 'react'; +import { EmptyState, Table } from '@backstage/core'; +import { WorkflowRunStatus } from '../WorkflowRunStatus'; +import { Button, Card, Link, TableContainer } from '@material-ui/core'; +import { generatePath, Link as RouterLink } from 'react-router-dom'; + +const firstLine = (message: string): string => message.split('\n')[0]; + +export type Props = { + entity: Entity; + branch?: string; + dense?: boolean; + limit?: number; +}; + +export const RecentWorkflowRunsCard = ({ + entity, + branch, + dense = false, + limit = 5, +}: Props) => { + const errorApi = useApi(errorApiRef); + const [owner, repo] = ( + entity?.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION] ?? '/' + ).split('/'); + const [{ runs = [], loading, error }] = useWorkflowRuns({ + owner, + repo, + branch, + initialPageSize: limit, + }); + useEffect(() => { + if (error) { + errorApi.post(error); + } + }, [error, errorApi]); + + return !runs.length ? ( + + Create new Workflow + + } + /> + ) : ( + +
( + + {firstLine(data.message)} + + ), + }, + { title: 'Branch', field: 'source.branchName' }, + { title: 'Status', field: 'status', render: WorkflowRunStatus }, + ]} + data={runs} + /> + + ); +}; diff --git a/plugins/github-actions/src/components/Cards/index.ts b/plugins/github-actions/src/components/Cards/index.ts index 8c987ea1d5..ab918d3b77 100644 --- a/plugins/github-actions/src/components/Cards/index.ts +++ b/plugins/github-actions/src/components/Cards/index.ts @@ -14,3 +14,4 @@ * limitations under the License. */ export { LatestWorkflowRunCard, LatestWorkflowsForBranchCard } from './Cards'; +export { RecentWorkflowRunsCard } from './RecentWorkflowRunsCard'; diff --git a/plugins/github-actions/src/components/Router.tsx b/plugins/github-actions/src/components/Router.tsx index fae56a0480..e7430d40ed 100644 --- a/plugins/github-actions/src/components/Router.tsx +++ b/plugins/github-actions/src/components/Router.tsx @@ -20,18 +20,14 @@ import { rootRouteRef, buildRouteRef } from '../plugin'; import { WorkflowRunDetails } from './WorkflowRunDetails'; import { WorkflowRunsTable } from './WorkflowRunsTable'; import { GITHUB_ACTIONS_ANNOTATION } from './useProjectName'; -import { WarningPanel } from '@backstage/core'; +import { MissingAnnotationEmptyState } from '@backstage/core'; export const isPluginApplicableToEntity = (entity: Entity) => Boolean(entity.metadata.annotations?.[GITHUB_ACTIONS_ANNOTATION]); export const Router = ({ entity }: { entity: Entity }) => - // TODO(shmidt-i): move warning to a separate standardized component !isPluginApplicableToEntity(entity) ? ( - -
{GITHUB_ACTIONS_ANNOTATION}
annotation is missing on the - entity. -
+ ) : ( { const { value: projectName, loading } = useProjectName(entity); const [owner, repo] = (projectName ?? '/').split('/'); - const [tableProps, { retry, setPage, setPageSize }] = useWorkflowRuns({ + const [ + { runs, ...tableProps }, + { retry, setPage, setPageSize }, + ] = useWorkflowRuns({ owner, repo, branch, }); - return ( + return !runs ? ( + + Create new Workflow + + } + /> + ) : ( { - return new Promise(resolve => { - const { user, type } = req; - const userGroups = this._getUserGroups(this.groups, user); - const groups = this.filterGroupsByType(userGroups, type); - resolve({ groups }); - }); - } - - _getUserGroups(groups: Group[], user: string) { - const userGroups: Set = new Set(); - groups.forEach(group => { - if (this.isUserInGroup(group, user)) { - userGroups.add(group); - } - - if (group.children) { - const userSubGroups = this._getUserGroups(group.children, user) ?? []; - const isUserInSubGroup = Boolean(userSubGroups.length); - if (isUserInSubGroup) { - userGroups.add(group); - } - userSubGroups.forEach(subGroup => userGroups.add(subGroup)); - } - }); - return Array.from(userGroups); - } - - private filterGroupsByType = (userGroups: Group[], type: string) => { - const groups = type - ? userGroups - .filter((group: Group) => group.type === type) - .map(group => ({ name: group.name, type: group.type })) - : userGroups.map(group => ({ - name: group.name, - type: group.type, - })); - return groups; - }; - - private isUserInGroup = (group: Group, user: string): boolean => { - if (group.members) { - const groupMembers = group.members; - const groupsWithUser = groupMembers.filter( - member => member.name === user, - ); - return Boolean(groupsWithUser.length); - } - return false; - }; -} diff --git a/plugins/identity-backend/src/service/standaloneApplication.ts b/plugins/identity-backend/src/service/standaloneApplication.ts deleted file mode 100644 index 5eea4fb8f5..0000000000 --- a/plugins/identity-backend/src/service/standaloneApplication.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2020 Spotify AB - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - errorHandler, - notFoundHandler, - requestLoggingHandler, -} from '@backstage/backend-common'; -import compression from 'compression'; -import cors from 'cors'; -import express from 'express'; -import helmet from 'helmet'; -import { Logger } from 'winston'; -import { createRouter } from './router'; - -export interface ApplicationOptions { - enableCors: boolean; - logger: Logger; -} - -export async function createStandaloneApplication( - options: ApplicationOptions, -): Promise { - const { enableCors, logger } = options; - const app = express(); - - app.use(helmet()); - if (enableCors) { - app.use(cors()); - } - app.use(compression()); - app.use(express.json()); - app.use(requestLoggingHandler()); - app.use('/', await createRouter({ logger })); - app.use(notFoundHandler()); - app.use(errorHandler()); - - return app; -} diff --git a/plugins/jenkins/README.md b/plugins/jenkins/README.md index 8f0d43cba7..3f5334b94f 100644 --- a/plugins/jenkins/README.md +++ b/plugins/jenkins/README.md @@ -32,8 +32,6 @@ proxy: Authorization: $secret: env: JENKINS_BASIC_AUTH_HEADER - pathRewrite: - '^/proxy/jenkins/api/': '/' ``` 4. Add an environment variable which contains the Jenkins credentials, (note: use an API token not your password) diff --git a/plugins/jenkins/package.json b/plugins/jenkins/package.json index e777dd2119..84e8a47664 100644 --- a/plugins/jenkins/package.json +++ b/plugins/jenkins/package.json @@ -44,7 +44,9 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/testing-library__jest-dom": "^5.9.1", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/jenkins/src/api/index.ts b/plugins/jenkins/src/api/index.ts index 2b95fe97d9..0fa48a1d17 100644 --- a/plugins/jenkins/src/api/index.ts +++ b/plugins/jenkins/src/api/index.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { createApiRef } from '@backstage/core'; +import { createApiRef, DiscoveryApi } from '@backstage/core'; import { CITableBuildInfo } from '../components/BuildsPage/lib/CITable'; const jenkins = require('jenkins'); @@ -24,28 +24,42 @@ export const jenkinsApiRef = createApiRef({ description: 'Used by the Jenkins plugin to make requests', }); -export class JenkinsApi { - apiUrl: string; - jenkins: any; +const DEFAULT_PROXY_PATH = '/jenkins/api'; - constructor(apiUrl: string) { - this.apiUrl = apiUrl; - this.jenkins = jenkins({ baseUrl: apiUrl, promisify: true }); +type Options = { + discoveryApi: DiscoveryApi; + /** + * Path to use for requests via the proxy, defaults to /jenkins/api + */ + proxyPath?: string; +}; + +export class JenkinsApi { + private readonly discoveryApi: DiscoveryApi; + private readonly proxyPath: string; + + constructor(options: Options) { + this.discoveryApi = options.discoveryApi; + this.proxyPath = options.proxyPath ?? DEFAULT_PROXY_PATH; + } + + private async getClient() { + const proxyUrl = await this.discoveryApi.getBaseUrl('proxy'); + return jenkins({ baseUrl: proxyUrl + this.proxyPath, promisify: true }); } async retry(buildName: string) { + const client = await this.getClient(); // looks like the current SDK only supports triggering a new build // can't see any support for replay (re-running the specific build with the same SCM info) - return await this.jenkins.job.build(buildName); + return await client.job.build(buildName); } async getLastBuild(jobName: string) { - const job = await this.jenkins.job.get(jobName); + const client = await this.getClient(); + const job = await client.job.get(jobName); - const lastBuild = await this.jenkins.build.get( - jobName, - job.lastBuild.number, - ); + const lastBuild = await client.build.get(jobName, job.lastBuild.number); return lastBuild; } @@ -84,17 +98,19 @@ export class JenkinsApi { } async getJob(jobName: string) { - return this.jenkins.job.get({ + const client = await this.getClient(); + return client.job.get({ name: jobName, depth: 1, }); } async getFolder(folderName: string) { - const folder = await this.jenkins.job.get(folderName); + const client = await this.getClient(); + const folder = await client.job.get(folderName); const results = []; for (const jobSummary of folder.jobs) { - const jobDetails = await this.jenkins.job.get({ + const jobDetails = await client.job.get({ name: `${folderName}/${jobSummary.name}`, depth: 1, }); @@ -104,7 +120,7 @@ export class JenkinsApi { // skipping folders inside folders for now } else { for (const buildDetails of jobDetails.builds) { - const build = await this.jenkins.build.get({ + const build = await client.build.get({ name: `${folderName}/${jobSummary.name}`, number: buildDetails.number, depth: 1, @@ -191,10 +207,11 @@ export class JenkinsApi { } async getBuild(buildName: string) { + const client = await this.getClient(); const { jobName, buildNumber } = this.extractJobDetailsFromBuildName( buildName, ); - const buildResult = await this.jenkins.build.get(jobName, buildNumber); + const buildResult = await client.build.get(jobName, buildNumber); return buildResult; } diff --git a/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx b/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx index 282cbc59b5..23f9af445c 100644 --- a/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx +++ b/plugins/jenkins/src/components/BuildsPage/lib/CITable/CITable.tsx @@ -109,20 +109,27 @@ const generatedColumns: TableColumn[] = [ title: 'Build', field: 'buildName', highlight: true, - render: (row: Partial) => ( - - {row.buildName} - - ), + render: (row: Partial) => { + if (!row.source?.branchName || !row.buildNumber) { + return <>{row.buildName}; + } + + return ( + + {row.buildName} + + ); + }, }, { title: 'Source', + field: 'source.branchName', render: (row: Partial) => ( <>

@@ -136,6 +143,7 @@ const generatedColumns: TableColumn[] = [ }, { title: 'Status', + field: 'status', render: (row: Partial) => { return ( @@ -146,6 +154,7 @@ const generatedColumns: TableColumn[] = [ }, { title: 'Tests', + sorting: false, render: (row: Partial) => { return ( <> @@ -168,6 +177,7 @@ const generatedColumns: TableColumn[] = [ }, { title: 'Actions', + sorting: false, render: (row: Partial) => ( diff --git a/plugins/jenkins/src/plugin.ts b/plugins/jenkins/src/plugin.ts index 8282f6b7f9..23c54743a3 100644 --- a/plugins/jenkins/src/plugin.ts +++ b/plugins/jenkins/src/plugin.ts @@ -18,7 +18,7 @@ import { createPlugin, createRouteRef, createApiFactory, - configApiRef, + discoveryApiRef, } from '@backstage/core'; import { jenkinsApiRef, JenkinsApi } from './api'; @@ -37,11 +37,8 @@ export const plugin = createPlugin({ apis: [ createApiFactory({ api: jenkinsApiRef, - deps: { configApi: configApiRef }, - factory: ({ configApi }) => - new JenkinsApi( - `${configApi.getString('backend.baseUrl')}/proxy/jenkins/api`, - ), + deps: { discoveryApi: discoveryApiRef }, + factory: ({ discoveryApi }) => new JenkinsApi({ discoveryApi }), }), ], }); diff --git a/plugins/kubernetes-backend/examples/dice-roller/README.md b/plugins/kubernetes-backend/examples/dice-roller/README.md new file mode 100644 index 0000000000..47fc345c73 --- /dev/null +++ b/plugins/kubernetes-backend/examples/dice-roller/README.md @@ -0,0 +1,44 @@ +# Dice roller + +An app to roll dice (it doesn't actually do that). + +# Viewing in local Minikube running Backstage locally + +## Prerequisites + +- kubectl installed +- Minikube installed, with the following addons + - metrics-server + - ingress +- jq installed +- Backstage locally built and ready to run + +## Steps + +1. Start minikube +2. Get the Kubernetes master base url `kubectl cluster-info` +3. Apply manifests `kubectl apply -f dice-roller-manifests.yaml` +4. Get service account token (see below) +5. Start Backstage UI and backend +6. Register existing component in Backstage + - https://github.com/mclarke47/dice-roller/blob/master/catalog-info.yaml + +Update `app-config.yaml` as follows. + +```yaml +--- +kubernetes: + clusterLocatorMethod: 'configMultiTenant' + clusters: + - url: + name: minikube + serviceAccountToken: +``` + +### Getting the service account token + +``` +kubectl get secret DICE_ROLLER_TOKEN_NAME -o=json | jq -r '.data["token"]' | base64 --decode | pbcopy +``` + +Paste into `app-config.yaml` `kubernetes.clusters[].serviceAccountToken` diff --git a/plugins/kubernetes-backend/examples/dice-roller/catalog-info.yaml b/plugins/kubernetes-backend/examples/dice-roller/catalog-info.yaml new file mode 100644 index 0000000000..a944232224 --- /dev/null +++ b/plugins/kubernetes-backend/examples/dice-roller/catalog-info.yaml @@ -0,0 +1,13 @@ +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: dice-roller + description: It rolls dice + tags: + - go + annotations: + 'backstage.io/kubernetes-id': dice-roller +spec: + type: service + lifecycle: production + owner: guest diff --git a/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml b/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml new file mode 100644 index 0000000000..50956bd7d3 --- /dev/null +++ b/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml @@ -0,0 +1,166 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dice-roller + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + selector: + matchLabels: + app: dice-roller + replicas: 10 + template: + metadata: + labels: + app: dice-roller + 'backstage.io/kubernetes-id': dice-roller + spec: + containers: + - name: nginx + image: nginx:1.14.2 + ports: + - containerPort: 80 + +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dice-roller-canary + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + selector: + matchLabels: + app: dice-roller-canary + replicas: 2 + template: + metadata: + labels: + app: dice-roller-canary + 'backstage.io/kubernetes-id': dice-roller + spec: + containers: + - name: nginx + image: nginx:1.14.2 + ports: + - containerPort: 80 + - name: side-car + image: nginx:1.14.2 + ports: + - containerPort: 81 + - name: other-side-car + image: nginx:1.14.2 + ports: + - containerPort: 82 + +--- +apiVersion: autoscaling/v1 +kind: HorizontalPodAutoscaler +metadata: + name: dice-roller + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + scaleTargetRef: + apiVersion: apps/v1 + kind: Deployment + name: dice-roller + minReplicas: 10 + maxReplicas: 15 + targetCPUUtilizationPercentage: 50 + +--- +apiVersion: networking.k8s.io/v1beta1 +kind: Ingress +metadata: + name: dice-roller + annotations: + nginx.ingress.kubernetes.io/rewrite-target: /$1 + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + rules: + - host: nginx + http: + paths: + - path: / + backend: + serviceName: dice-roller + servicePort: 80 + +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: dice-roller + namespace: default + labels: + 'backstage.io/kubernetes-id': dice-roller +data: + foo: bar + +--- +apiVersion: v1 +kind: Secret +metadata: + name: dice-roller + labels: + 'backstage.io/kubernetes-id': dice-roller +type: Opaque +data: + username: YWRtaW4= +--- +apiVersion: v1 +kind: Service +metadata: + name: dice-roller + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + selector: + app: dice-roller + ports: + - protocol: TCP + port: 80 + targetPort: 9376 + name: port1 + - protocol: TCP + port: 81 + targetPort: 9377 + name: port2 + +--- +apiVersion: v1 +kind: Service +metadata: + name: dice-roller-lb + labels: + 'backstage.io/kubernetes-id': dice-roller +spec: + selector: + app: dice-roller + ports: + - port: 8765 + targetPort: 9376 + type: LoadBalancer + +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dice-roller +automountServiceAccountToken: false + +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: sa-admin +roleRef: + kind: ClusterRole + name: cluster-admin + apiGroup: rbac.authorization.k8s.io +subjects: + - kind: ServiceAccount + name: dice-roller + namespace: default diff --git a/plugins/kubernetes-backend/package.json b/plugins/kubernetes-backend/package.json index 406d9c8d7f..4ff8149322 100644 --- a/plugins/kubernetes-backend/package.json +++ b/plugins/kubernetes-backend/package.json @@ -21,20 +21,25 @@ }, "dependencies": { "@backstage/backend-common": "^0.1.1-alpha.23", + "@backstage/config": "^0.1.1-alpha.23", "@types/express": "^4.17.6", + "@kubernetes/client-node": "^0.12.1", "compression": "^1.7.4", "cors": "^2.8.5", "express": "^4.17.1", "express-promise-router": "^3.0.3", "fs-extra": "^9.0.0", "helmet": "^4.0.0", + "lodash": "^4.17.15", "morgan": "^1.10.0", + "stream-buffers": "^3.0.2", "winston": "^3.2.1", "yn": "^4.0.0" }, "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.23", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "supertest": "^4.0.2", + "@backstage/cli": "^0.1.1-alpha.23" }, "files": [ "dist" diff --git a/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.test.ts b/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.test.ts new file mode 100644 index 0000000000..34788d16cb --- /dev/null +++ b/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.test.ts @@ -0,0 +1,105 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import '@backstage/backend-common'; +import { MultiTenantConfigClusterLocator } from './MultiTenantConfigClusterLocator'; +import { ConfigReader, Config } from '@backstage/config'; + +describe('MultiTenantConfigClusterLocator', () => { + it('empty clusters returns empty cluster details', async () => { + const config: Config = new ConfigReader( + { + clusters: [], + }, + 'ctx', + ); + + const sut = MultiTenantConfigClusterLocator.fromConfig( + config.getConfigArray('clusters'), + ); + + const result = await sut.getClusterByServiceId('ignored'); + + expect(result).toStrictEqual([]); + }); + + it('one clusters returns one cluster details', async () => { + const config: Config = new ConfigReader( + { + clusters: [ + { + name: 'cluster1', + url: 'http://localhost:8080', + }, + ], + }, + 'ctx', + ); + + const sut = MultiTenantConfigClusterLocator.fromConfig( + config.getConfigArray('clusters'), + ); + + const result = await sut.getClusterByServiceId('ignored'); + + expect(result).toStrictEqual([ + { + name: 'cluster1', + serviceAccountToken: undefined, + url: 'http://localhost:8080', + }, + ]); + }); + + it('two clusters returns two cluster details', async () => { + const config: Config = new ConfigReader( + { + clusters: [ + { + name: 'cluster1', + serviceAccountToken: undefined, + url: 'http://localhost:8080', + }, + { + name: 'cluster2', + serviceAccountToken: undefined, + url: 'http://localhost:8081', + }, + ], + }, + 'ctx', + ); + + const sut = MultiTenantConfigClusterLocator.fromConfig( + config.getConfigArray('clusters'), + ); + + const result = await sut.getClusterByServiceId('ignored'); + + expect(result).toStrictEqual([ + { + name: 'cluster1', + serviceAccountToken: undefined, + url: 'http://localhost:8080', + }, + { + name: 'cluster2', + serviceAccountToken: undefined, + url: 'http://localhost:8081', + }, + ]); + }); +}); diff --git a/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.ts b/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.ts new file mode 100644 index 0000000000..3d9e2dd8b4 --- /dev/null +++ b/plugins/kubernetes-backend/src/cluster-locator/MultiTenantConfigClusterLocator.ts @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Config } from '@backstage/config'; +import { ClusterDetails, KubernetesClusterLocator } from '..'; + +// This cluster locator assumes that every service is located on every cluster +// Therefore it will always return all clusters in an app configuration file +export class MultiTenantConfigClusterLocator + implements KubernetesClusterLocator { + private readonly clusterDetails: ClusterDetails[]; + + constructor(clusterDetails: ClusterDetails[]) { + this.clusterDetails = clusterDetails; + } + + static fromConfig(config: Config[]): MultiTenantConfigClusterLocator { + return new MultiTenantConfigClusterLocator( + config.map(c => { + return { + name: c.getString('name'), + url: c.getString('url'), + serviceAccountToken: c.getOptionalString('serviceAccountToken'), + }; + }), + ); + } + + // As this implementation always returns all clusters serviceId is ignored here + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async getClusterByServiceId(_serviceId: string): Promise { + return this.clusterDetails; + } +} diff --git a/plugins/kubernetes-backend/src/cluster-locator/types.ts b/plugins/kubernetes-backend/src/cluster-locator/types.ts new file mode 100644 index 0000000000..9b793da558 --- /dev/null +++ b/plugins/kubernetes-backend/src/cluster-locator/types.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export type ClusterLocatorMethod = 'configMultiTenant' | 'http'; diff --git a/plugins/kubernetes-backend/src/index.ts b/plugins/kubernetes-backend/src/index.ts index 7612c392a2..96f070ff1e 100644 --- a/plugins/kubernetes-backend/src/index.ts +++ b/plugins/kubernetes-backend/src/index.ts @@ -15,3 +15,4 @@ */ export * from './service/router'; +export * from './types/types'; diff --git a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts new file mode 100644 index 0000000000..a3dc67716a --- /dev/null +++ b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.test.ts @@ -0,0 +1,136 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import '@backstage/backend-common'; +import { KubernetesClientProvider } from './KubernetesClientProvider'; + +describe('KubernetesClientProvider', () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('can get core client by cluster details', async () => { + const sut = new KubernetesClientProvider(); + + const mockGetKubeConfig = jest.fn(sut.getKubeConfig.bind({})); + + sut.getKubeConfig = mockGetKubeConfig; + + const result = sut.getCoreClientByClusterDetails({ + name: 'cluster-name', + url: 'http://localhost:9999', + serviceAccountToken: 'TOKEN', + }); + + expect(result.basePath).toBe('http://localhost:9999'); + // These fields aren't on the type but are there + const auth = (result as any).authentications.default; + expect(auth.users[0].token).toBe('TOKEN'); + expect(auth.clusters[0].name).toBe('cluster-name'); + + expect(mockGetKubeConfig.mock.calls.length).toBe(1); + }); + + it('can get cached core client by cluster details', async () => { + const sut = new KubernetesClientProvider(); + + const mockGetKubeConfig = jest.fn(sut.getKubeConfig.bind({})); + + sut.getKubeConfig = mockGetKubeConfig; + + const result1 = sut.getCoreClientByClusterDetails({ + name: 'cluster-name', + url: 'http://localhost:9999', + serviceAccountToken: 'TOKEN', + }); + + const result2 = sut.getCoreClientByClusterDetails({ + name: 'cluster-name', + url: 'http://localhost:9999', + serviceAccountToken: 'TOKEN', + }); + + expect(result1.basePath).toBe('http://localhost:9999'); + // These fields aren't on the type but are there + const auth1 = (result1 as any).authentications.default; + expect(auth1.users[0].token).toBe('TOKEN'); + expect(auth1.clusters[0].name).toBe('cluster-name'); + + expect(result2.basePath).toBe('http://localhost:9999'); + // These fields aren't on the type but are there + const auth2 = (result2 as any).authentications.default; + expect(auth2.users[0].token).toBe('TOKEN'); + expect(auth2.clusters[0].name).toBe('cluster-name'); + + expect(mockGetKubeConfig.mock.calls.length).toBe(1); + }); + + it('can get apps client by cluster details', async () => { + const sut = new KubernetesClientProvider(); + + const mockGetKubeConfig = jest.fn(sut.getKubeConfig.bind({})); + + sut.getKubeConfig = mockGetKubeConfig; + + const result = sut.getAppsClientByClusterDetails({ + name: 'cluster-name', + url: 'http://localhost:9999', + serviceAccountToken: 'TOKEN', + }); + + expect(result.basePath).toBe('http://localhost:9999'); + // These fields aren't on the type but are there + const auth = (result as any).authentications.default; + expect(auth.users[0].token).toBe('TOKEN'); + expect(auth.clusters[0].name).toBe('cluster-name'); + + expect(mockGetKubeConfig.mock.calls.length).toBe(1); + }); + + it('can get cached apps client by cluster details', async () => { + const sut = new KubernetesClientProvider(); + + const mockGetKubeConfig = jest.fn(sut.getKubeConfig.bind({})); + + sut.getKubeConfig = mockGetKubeConfig; + + const result1 = sut.getAppsClientByClusterDetails({ + name: 'cluster-name', + url: 'http://localhost:9999', + serviceAccountToken: 'TOKEN', + }); + + const result2 = sut.getAppsClientByClusterDetails({ + name: 'cluster-name', + url: 'http://localhost:9999', + serviceAccountToken: 'TOKEN', + }); + + expect(result1.basePath).toBe('http://localhost:9999'); + // These fields aren't on the type but are there + const auth1 = (result1 as any).authentications.default; + expect(auth1.users[0].token).toBe('TOKEN'); + expect(auth1.clusters[0].name).toBe('cluster-name'); + + expect(result2.basePath).toBe('http://localhost:9999'); + // These fields aren't on the type but are there + const auth2 = (result2 as any).authentications.default; + expect(auth2.users[0].token).toBe('TOKEN'); + expect(auth2.clusters[0].name).toBe('cluster-name'); + + expect(mockGetKubeConfig.mock.calls.length).toBe(1); + }); +}); diff --git a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts new file mode 100644 index 0000000000..8b12d53afc --- /dev/null +++ b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts @@ -0,0 +1,144 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ClusterDetails } from '..'; +import { + AppsV1Api, + AutoscalingV1Api, + CoreV1Api, + KubeConfig, + NetworkingV1beta1Api, +} from '@kubernetes/client-node'; + +export class KubernetesClientProvider { + private readonly coreClientMap: { + [key: string]: CoreV1Api; + }; + + private readonly appsClientMap: { + [key: string]: AppsV1Api; + }; + + private readonly autoscalingClientMap: { + [key: string]: AutoscalingV1Api; + }; + + private readonly networkingBeta1ClientMap: { + [key: string]: NetworkingV1beta1Api; + }; + + constructor() { + this.coreClientMap = {}; + this.appsClientMap = {}; + this.autoscalingClientMap = {}; + this.networkingBeta1ClientMap = {}; + } + + // visible for testing + getKubeConfig(clusterDetails: ClusterDetails) { + const cluster = { + name: clusterDetails.name, + server: clusterDetails.url, + // TODO configure this + skipTLSVerify: true, + }; + + // TODO configure + const user = { + name: 'service-account', + token: clusterDetails.serviceAccountToken, + }; + + const context = { + name: `${clusterDetails.name}`, + user: user.name, + cluster: cluster.name, + }; + + const kc = new KubeConfig(); + kc.loadFromOptions({ + clusters: [cluster], + users: [user], + contexts: [context], + currentContext: context.name, + }); + return kc; + } + + getCoreClientByClusterDetails(clusterDetails: ClusterDetails) { + const clientMapKey = clusterDetails.name; + + if (this.coreClientMap.hasOwnProperty(clientMapKey)) { + return this.coreClientMap[clientMapKey]; + } + + const kc = this.getKubeConfig(clusterDetails); + + const client = kc.makeApiClient(CoreV1Api); + + this.coreClientMap[clientMapKey] = client; + + return client; + } + + getAppsClientByClusterDetails(clusterDetails: ClusterDetails) { + const clientMapKey = clusterDetails.name; + + if (this.appsClientMap.hasOwnProperty(clientMapKey)) { + return this.appsClientMap[clientMapKey]; + } + + const kc = this.getKubeConfig(clusterDetails); + + const client = kc.makeApiClient(AppsV1Api); + + this.appsClientMap[clientMapKey] = client; + + return client; + } + + getAutoscalingClientByClusterDetails(clusterDetails: ClusterDetails) { + const clientMapKey = clusterDetails.name; + + if (this.autoscalingClientMap.hasOwnProperty(clientMapKey)) { + return this.autoscalingClientMap[clientMapKey]; + } + + const kc = this.getKubeConfig(clusterDetails); + + const client = kc.makeApiClient(AutoscalingV1Api); + + this.autoscalingClientMap[clientMapKey] = client; + + return client; + } + + getNetworkingBeta1Client(clusterDetails: ClusterDetails) { + const clientMapKey = clusterDetails.name; + + if (this.networkingBeta1ClientMap.hasOwnProperty(clientMapKey)) { + return this.networkingBeta1ClientMap[clientMapKey]; + } + + const kc = this.getKubeConfig(clusterDetails); + + const client = kc.makeApiClient(NetworkingV1beta1Api); + + this.networkingBeta1ClientMap[clientMapKey] = client; + + return client; + } +} diff --git a/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts b/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts new file mode 100644 index 0000000000..8f390f309b --- /dev/null +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts @@ -0,0 +1,254 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getVoidLogger } from '@backstage/backend-common'; +import { KubernetesClientBasedFetcher } from './KubernetesFetcher'; + +describe('KubernetesClientProvider', () => { + let clientMock: any; + let kubernetesClientProvider: any; + let sut: KubernetesClientBasedFetcher; + + beforeEach(() => { + jest.resetAllMocks(); + clientMock = { + listPodForAllNamespaces: jest.fn(), + listServiceForAllNamespaces: jest.fn(), + }; + + kubernetesClientProvider = { + getCoreClientByClusterDetails: jest.fn(() => clientMock), + getAppsClientByClusterDetails: jest.fn(() => clientMock), + getAutoscalingClientByClusterDetails: jest.fn(() => clientMock), + getNetworkingBeta1Client: jest.fn(() => clientMock), + }; + + sut = new KubernetesClientBasedFetcher({ + kubernetesClientProvider, + logger: getVoidLogger(), + }); + }); + + const testErrorResponse = async (errorResponse: any, expectedResult: any) => { + clientMock.listPodForAllNamespaces.mockResolvedValueOnce({ + body: { + items: [ + { + metadata: { + name: 'pod-name', + }, + }, + ], + }, + }); + + clientMock.listServiceForAllNamespaces.mockRejectedValue(errorResponse); + + const result = await sut.fetchObjectsByServiceId( + 'some-service', + { + name: 'cluster1', + url: 'http://localhost:9999', + serviceAccountToken: undefined, + }, + new Set(['pods', 'services']), + ); + + expect(result).toStrictEqual({ + errors: [expectedResult], + responses: [ + { + type: 'pods', + resources: [ + { + metadata: { + name: 'pod-name', + }, + }, + ], + }, + ], + }); + + expect(clientMock.listPodForAllNamespaces.mock.calls.length).toBe(1); + expect(clientMock.listServiceForAllNamespaces.mock.calls.length).toBe(1); + + expect( + kubernetesClientProvider.getAppsClientByClusterDetails.mock.calls.length, + ).toBe(2); + expect( + kubernetesClientProvider.getCoreClientByClusterDetails.mock.calls.length, + ).toBe(2); + }; + + it('should return pods, services', async () => { + clientMock.listPodForAllNamespaces.mockResolvedValueOnce({ + body: { + items: [ + { + metadata: { + name: 'pod-name', + }, + }, + ], + }, + }); + + clientMock.listServiceForAllNamespaces.mockResolvedValueOnce({ + body: { + items: [ + { + metadata: { + name: 'service-name', + }, + }, + ], + }, + }); + + const result = await sut.fetchObjectsByServiceId( + 'some-service', + { + name: 'cluster1', + url: 'http://localhost:9999', + serviceAccountToken: undefined, + }, + new Set(['pods', 'services']), + ); + + expect(result).toStrictEqual({ + errors: [], + responses: [ + { + type: 'pods', + resources: [ + { + metadata: { + name: 'pod-name', + }, + }, + ], + }, + { + type: 'services', + resources: [ + { + metadata: { + name: 'service-name', + }, + }, + ], + }, + ], + }); + + expect(clientMock.listPodForAllNamespaces.mock.calls.length).toBe(1); + expect(clientMock.listServiceForAllNamespaces.mock.calls.length).toBe(1); + + expect( + kubernetesClientProvider.getAppsClientByClusterDetails.mock.calls.length, + ).toBe(2); + expect( + kubernetesClientProvider.getCoreClientByClusterDetails.mock.calls.length, + ).toBe(2); + }); + it('should throw error on unknown type', () => { + expect(() => + sut.fetchObjectsByServiceId( + 'some-service', + { + name: 'cluster1', + url: 'http://localhost:9999', + serviceAccountToken: undefined, + }, + new Set(['foo']), + ), + ).toThrow('unrecognised type=foo'); + + expect(clientMock.listPodForAllNamespaces.mock.calls.length).toBe(0); + expect(clientMock.listServiceForAllNamespaces.mock.calls.length).toBe(0); + + expect( + kubernetesClientProvider.getAppsClientByClusterDetails.mock.calls.length, + ).toBe(0); + expect( + kubernetesClientProvider.getCoreClientByClusterDetails.mock.calls.length, + ).toBe(0); + }); + // they're in testErrorResponse + // eslint-disable-next-line jest/expect-expect + it('should return pods, unauthorized error', async () => { + await testErrorResponse( + { + response: { + statusCode: 401, + request: { + uri: { + pathname: '/some/path', + }, + }, + }, + }, + { + errorType: 'UNAUTHORIZED_ERROR', + resourcePath: '/some/path', + statusCode: 401, + }, + ); + }); + // they're in testErrorResponse + // eslint-disable-next-line jest/expect-expect + it('should return pods, system error', async () => { + await testErrorResponse( + { + response: { + statusCode: 500, + request: { + uri: { + pathname: '/some/path', + }, + }, + }, + }, + { + errorType: 'SYSTEM_ERROR', + resourcePath: '/some/path', + statusCode: 500, + }, + ); + }); + // they're in testErrorResponse + // eslint-disable-next-line jest/expect-expect + it('should return pods, unknown error', async () => { + await testErrorResponse( + { + response: { + statusCode: 900, + request: { + uri: { + pathname: '/some/path', + }, + }, + }, + }, + { + errorType: 'UNKNOWN_ERROR', + resourcePath: '/some/path', + statusCode: 900, + }, + ); + }); +}); diff --git a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts new file mode 100644 index 0000000000..f66a45816a --- /dev/null +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts @@ -0,0 +1,296 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import http from 'http'; +import { + AppsV1Api, + AutoscalingV1Api, + CoreV1Api, + ExtensionsV1beta1Ingress, + NetworkingV1beta1Api, + V1ConfigMap, + V1Deployment, + V1HorizontalPodAutoscaler, + V1Pod, + V1ReplicaSet, +} from '@kubernetes/client-node'; +import { KubernetesClientProvider } from './KubernetesClientProvider'; +import { V1Service } from '@kubernetes/client-node/dist/gen/model/v1Service'; +import { Logger } from 'winston'; +import { + KubernetesFetcher, + ClusterDetails, + KubernetesObjectTypes, + FetchResponse, + FetchResponseWrapper, + KubernetesFetchError, + KubernetesErrorTypes, +} from '..'; +import lodash, { Dictionary } from 'lodash'; + +export interface Clients { + core: CoreV1Api; + apps: AppsV1Api; + autoscaling: AutoscalingV1Api; + networkingBeta1: NetworkingV1beta1Api; +} + +export interface KubernetesClientBasedFetcherOptions { + kubernetesClientProvider: KubernetesClientProvider; + logger: Logger; +} + +type FetchResult = FetchResponse | KubernetesFetchError; + +const isError = (fr: FetchResult): fr is KubernetesFetchError => + fr.hasOwnProperty('errorType'); + +function fetchResultsToResponseWrapper( + results: FetchResult[], +): FetchResponseWrapper { + const groupBy: Dictionary = lodash.groupBy(results, value => { + return isError(value) ? 'errors' : 'responses'; + }); + + return { + errors: groupBy.errors ?? [], + responses: groupBy.responses ?? [], + } as FetchResponseWrapper; // TODO would be nice to get rid of this 'as' +} + +const statusCodeToErrorType = (statusCode: number): KubernetesErrorTypes => { + switch (statusCode) { + case 401: + return 'UNAUTHORIZED_ERROR'; + case 500: + return 'SYSTEM_ERROR'; + default: + return 'UNKNOWN_ERROR'; + } +}; + +const captureKubernetesErrorsRethrowOthers = (e: any): KubernetesFetchError => { + if (e.response && e.response.statusCode) { + return { + errorType: statusCodeToErrorType(e.response.statusCode), + statusCode: e.response.statusCode, + resourcePath: e.response.request.uri.pathname, + }; + } + throw e; +}; + +export class KubernetesClientBasedFetcher implements KubernetesFetcher { + private readonly kubernetesClientProvider: KubernetesClientProvider; + private readonly logger: Logger; + + constructor({ + kubernetesClientProvider, + logger, + }: KubernetesClientBasedFetcherOptions) { + this.kubernetesClientProvider = kubernetesClientProvider; + this.logger = logger; + } + + fetchObjectsByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + objectTypesToFetch: Set, + ): Promise { + const fetchResults = Array.from(objectTypesToFetch).map(type => { + return this.fetchByObjectType(serviceId, clusterDetails, type).catch( + captureKubernetesErrorsRethrowOthers, + ); + }); + + return Promise.all(fetchResults).then(fetchResultsToResponseWrapper); + } + + // TODO could probably do with a tidy up + private fetchByObjectType( + serviceId: string, + clusterDetails: ClusterDetails, + type: KubernetesObjectTypes, + ): Promise { + switch (type) { + case 'pods': + return this.fetchPodsByServiceId(serviceId, clusterDetails).then(r => ({ + type: type, + resources: r, + })); + case 'configmaps': + return this.fetchConfigMapsByServiceId( + serviceId, + clusterDetails, + ).then(r => ({ type: type, resources: r })); + case 'deployments': + return this.fetchDeploymentsByServiceId( + serviceId, + clusterDetails, + ).then(r => ({ type: type, resources: r })); + case 'replicasets': + return this.fetchReplicaSetsByServiceId( + serviceId, + clusterDetails, + ).then(r => ({ type: type, resources: r })); + case 'services': + return this.fetchServicesByServiceId( + serviceId, + clusterDetails, + ).then(r => ({ type: type, resources: r })); + case 'horizontalpodautoscalers': + return this.fetchHorizontalPodAutoscalersByServiceId( + serviceId, + clusterDetails, + ).then(r => ({ type: type, resources: r })); + case 'ingresses': + return this.fetchIngressesByServiceId( + serviceId, + clusterDetails, + ).then(r => ({ type: type, resources: r })); + default: + // unrecognised type + throw new Error(`unrecognised type=${type}`); + } + } + + private singleClusterFetch( + clusterDetails: ClusterDetails, + fn: ( + client: Clients, + ) => Promise<{ body: { items: Array }; response: http.IncomingMessage }>, + ): Promise> { + const core = this.kubernetesClientProvider.getCoreClientByClusterDetails( + clusterDetails, + ); + const apps = this.kubernetesClientProvider.getAppsClientByClusterDetails( + clusterDetails, + ); + const autoscaling = this.kubernetesClientProvider.getAutoscalingClientByClusterDetails( + clusterDetails, + ); + const networkingBeta1 = this.kubernetesClientProvider.getNetworkingBeta1Client( + clusterDetails, + ); + + this.logger.debug(`calling cluster=${clusterDetails.name}`); + return fn({ core, apps, autoscaling, networkingBeta1 }).then(({ body }) => { + return body.items; + }); + } + + private fetchServicesByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch(clusterDetails, ({ core }) => + core.listServiceForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } + + private fetchPodsByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch(clusterDetails, ({ core }) => + core.listPodForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } + + private fetchConfigMapsByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch(clusterDetails, ({ core }) => + core.listConfigMapForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } + + private fetchDeploymentsByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch(clusterDetails, ({ apps }) => + apps.listDeploymentForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } + + private fetchReplicaSetsByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch(clusterDetails, ({ apps }) => + apps.listReplicaSetForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } + + private fetchHorizontalPodAutoscalersByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch( + clusterDetails, + ({ autoscaling }) => + autoscaling.listHorizontalPodAutoscalerForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } + + private fetchIngressesByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + ): Promise> { + return this.singleClusterFetch( + clusterDetails, + ({ networkingBeta1 }) => + networkingBeta1.listIngressForAllNamespaces( + false, + '', + '', + `backstage.io/kubernetes-id=${serviceId}`, + ), + ); + } +} diff --git a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts new file mode 100644 index 0000000000..56da3235cc --- /dev/null +++ b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.test.ts @@ -0,0 +1,248 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { handleGetKubernetesObjectsByServiceId } from './getKubernetesObjectsByServiceIdHandler'; +import { getVoidLogger } from '@backstage/backend-common'; +import { ClusterDetails } from '..'; + +const TEST_SERVICE_ID = 'my-service'; + +const fetchObjectsByServiceId = jest.fn(); + +const getClusterByServiceId = jest.fn(); + +const mockFetch = (mock: jest.Mock) => { + mock.mockImplementation((serviceId: string, clusterDetails: ClusterDetails) => + Promise.resolve({ + errors: [], + responses: [ + { + type: 'pods', + resources: [ + { + metadata: { + name: `my-pods-${serviceId}-${clusterDetails.name}`, + }, + }, + ], + }, + { + type: 'configmaps', + resources: [ + { + metadata: { + name: `my-configmaps-${serviceId}-${clusterDetails.name}`, + }, + }, + ], + }, + { + type: 'services', + resources: [ + { + metadata: { + name: `my-services-${serviceId}-${clusterDetails.name}`, + }, + }, + ], + }, + ], + }), + ); +}; + +describe('handleGetKubernetesObjectsByServiceId', () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + + it('retrieve objects for one cluster', async () => { + getClusterByServiceId.mockImplementation(() => + Promise.resolve([ + { + name: 'test-cluster', + }, + ]), + ); + + mockFetch(fetchObjectsByServiceId); + + const result = await handleGetKubernetesObjectsByServiceId( + TEST_SERVICE_ID, + { + fetchObjectsByServiceId, + }, + { + getClusterByServiceId, + }, + getVoidLogger(), + ); + + expect(getClusterByServiceId.mock.calls.length).toBe(1); + expect(fetchObjectsByServiceId.mock.calls.length).toBe(1); + expect(result).toStrictEqual({ + items: [ + { + cluster: { + name: 'test-cluster', + }, + errors: [], + resources: [ + { + resources: [ + { + metadata: { + name: 'my-pods-my-service-test-cluster', + }, + }, + ], + type: 'pods', + }, + { + resources: [ + { + metadata: { + name: 'my-configmaps-my-service-test-cluster', + }, + }, + ], + type: 'configmaps', + }, + { + resources: [ + { + metadata: { + name: 'my-services-my-service-test-cluster', + }, + }, + ], + type: 'services', + }, + ], + }, + ], + }); + }); + + it('retrieve objects for two clusters', async () => { + getClusterByServiceId.mockImplementation(() => + Promise.resolve([ + { + name: 'test-cluster', + }, + { + name: 'other-cluster', + }, + ]), + ); + + mockFetch(fetchObjectsByServiceId); + + const result = await handleGetKubernetesObjectsByServiceId( + TEST_SERVICE_ID, + { + fetchObjectsByServiceId, + }, + { + getClusterByServiceId, + }, + getVoidLogger(), + ); + + expect(getClusterByServiceId.mock.calls.length).toBe(1); + expect(fetchObjectsByServiceId.mock.calls.length).toBe(2); + expect(result).toStrictEqual({ + items: [ + { + cluster: { + name: 'test-cluster', + }, + errors: [], + resources: [ + { + resources: [ + { + metadata: { + name: 'my-pods-my-service-test-cluster', + }, + }, + ], + type: 'pods', + }, + { + resources: [ + { + metadata: { + name: 'my-configmaps-my-service-test-cluster', + }, + }, + ], + type: 'configmaps', + }, + { + resources: [ + { + metadata: { + name: 'my-services-my-service-test-cluster', + }, + }, + ], + type: 'services', + }, + ], + }, + { + cluster: { + name: 'other-cluster', + }, + errors: [], + resources: [ + { + resources: [ + { + metadata: { + name: 'my-pods-my-service-other-cluster', + }, + }, + ], + type: 'pods', + }, + { + resources: [ + { + metadata: { + name: 'my-configmaps-my-service-other-cluster', + }, + }, + ], + type: 'configmaps', + }, + { + resources: [ + { + metadata: { + name: 'my-services-my-service-other-cluster', + }, + }, + ], + type: 'services', + }, + ], + }, + ], + }); + }); +}); diff --git a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts new file mode 100644 index 0000000000..1690b8be40 --- /dev/null +++ b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts @@ -0,0 +1,74 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Logger } from 'winston'; +import { + KubernetesClusterLocator, + KubernetesFetcher, + KubernetesObjectTypes, + ObjectsByServiceIdResponse, +} from '..'; + +export type GetKubernetesObjectsByServiceIdHandler = ( + serviceId: string, + fetcher: KubernetesFetcher, + clusterLocator: KubernetesClusterLocator, + logger: Logger, + objectsToFetch?: Set, +) => Promise; + +const DEFAULT_OBJECTS = new Set([ + 'pods', + 'services', + 'configmaps', + 'deployments', + 'replicasets', + 'horizontalpodautoscalers', + 'ingresses', +]); + +// Fans out the request to all clusters that the service lives in, aggregates their responses together +export const handleGetKubernetesObjectsByServiceId: GetKubernetesObjectsByServiceIdHandler = async ( + serviceId, + fetcher, + clusterLocator, + logger, + objectsToFetch = DEFAULT_OBJECTS, +) => { + const clusterDetails = await clusterLocator.getClusterByServiceId(serviceId); + + logger.info( + `serviceId=${serviceId} clusterDetails=[${clusterDetails + .map(c => c.name) + .join(', ')}]`, + ); + + return Promise.all( + clusterDetails.map(cd => { + return fetcher + .fetchObjectsByServiceId(serviceId, cd, objectsToFetch) + .then(result => { + return { + cluster: { + name: cd.name, + }, + resources: result.responses, + errors: result.errors, + }; + }); + }), + ).then(r => ({ items: r })); +}; diff --git a/plugins/kubernetes-backend/src/service/router.test.ts b/plugins/kubernetes-backend/src/service/router.test.ts new file mode 100644 index 0000000000..7731fe9abb --- /dev/null +++ b/plugins/kubernetes-backend/src/service/router.test.ts @@ -0,0 +1,87 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getVoidLogger } from '@backstage/backend-common'; +import express from 'express'; +import request from 'supertest'; +import { makeRouter } from './router'; +import { + KubernetesClusterLocator, + KubernetesFetcher, + ObjectsByServiceIdResponse, +} from '..'; + +describe('router', () => { + let app: express.Express; + let kubernetesFetcher: jest.Mocked; + let kubernetesClusterLocator: jest.Mocked; + let handleGetByServiceId: jest.Mock>; + + beforeAll(async () => { + kubernetesFetcher = { + fetchObjectsByServiceId: jest.fn(), + }; + + kubernetesClusterLocator = { + getClusterByServiceId: jest.fn(), + }; + + handleGetByServiceId = jest.fn(); + + const router = makeRouter( + getVoidLogger(), + kubernetesFetcher, + kubernetesClusterLocator, + handleGetByServiceId as any, + ); + app = express().use(router); + }); + + beforeEach(() => { + jest.resetAllMocks(); + }); + + describe('GET /services/:serviceId', () => { + it('happy path: lists kubernetes objects', async () => { + const result = { + clusterOne: { + pods: [ + { + metadata: { + name: 'pod1', + }, + }, + ], + }, + } as any; + handleGetByServiceId.mockReturnValueOnce(Promise.resolve(result)); + + const response = await request(app).get('/services/test-service'); + + expect(response.status).toEqual(200); + expect(response.body).toEqual(result); + }); + + it('internal error: lists kubernetes objects', async () => { + handleGetByServiceId.mockRejectedValue(Error('some internal error')); + + const response = await request(app).get('/services/test-service'); + + expect(response.status).toEqual(500); + expect(response.body).toEqual({ error: 'some internal error' }); + }); + }); +}); diff --git a/plugins/kubernetes-backend/src/service/router.ts b/plugins/kubernetes-backend/src/service/router.ts index b200896887..bdb14bb74d 100644 --- a/plugins/kubernetes-backend/src/service/router.ts +++ b/plugins/kubernetes-backend/src/service/router.ts @@ -17,19 +17,68 @@ import express from 'express'; import Router from 'express-promise-router'; import { Logger } from 'winston'; +import { Config } from '@backstage/config'; +import { ClusterLocatorMethod } from '../cluster-locator/types'; +import { MultiTenantConfigClusterLocator } from '../cluster-locator/MultiTenantConfigClusterLocator'; +import { KubernetesClientBasedFetcher } from './KubernetesFetcher'; +import { KubernetesClientProvider } from './KubernetesClientProvider'; +import { + GetKubernetesObjectsByServiceIdHandler, + handleGetKubernetesObjectsByServiceId, +} from './getKubernetesObjectsByServiceIdHandler'; +import { KubernetesClusterLocator, KubernetesFetcher } from '..'; export interface RouterOptions { logger: Logger; + config: Config; } -const makeRouter = (logger: Logger): express.Router => { +const getClusterLocator = (config: Config): KubernetesClusterLocator => { + const clusterLocatorMethod = config.getString( + 'kubernetes.clusterLocatorMethod', + ) as ClusterLocatorMethod; + + switch (clusterLocatorMethod) { + case 'configMultiTenant': + return MultiTenantConfigClusterLocator.fromConfig( + config.getConfigArray('kubernetes.clusters'), + ); + case 'http': + throw new Error('not implemented'); + default: + throw new Error( + `Unsupported kubernetes.clusterLocatorMethod "${clusterLocatorMethod}"`, + ); + } +}; + +export const makeRouter = ( + logger: Logger, + fetcher: KubernetesFetcher, + clusterLocator: KubernetesClusterLocator, + handleGetByServiceId: GetKubernetesObjectsByServiceIdHandler, +): express.Router => { const router = Router(); router.use(express.json()); + // TODO error handling router.get('/services/:serviceId', async (req, res) => { const serviceId = req.params.serviceId; - logger.info(`HERE ${serviceId}`); - res.send({ serviceId }); + + try { + const response = await handleGetByServiceId( + serviceId, + fetcher, + clusterLocator, + logger, + ); + res.send(response); + } catch (e) { + logger.error( + `action=retrieveObjectsByServiceId service=${serviceId}, error=${e}`, + ); + res.status(500).send({ error: e.message }); + } }); return router; @@ -41,5 +90,18 @@ export async function createRouter( const logger = options.logger; logger.info('Initializing Kubernetes backend'); - return makeRouter(logger); + + const clusterLocator = getClusterLocator(options.config); + + const fetcher = new KubernetesClientBasedFetcher({ + kubernetesClientProvider: new KubernetesClientProvider(), + logger, + }); + + return makeRouter( + logger, + fetcher, + clusterLocator, + handleGetKubernetesObjectsByServiceId, + ); } diff --git a/plugins/kubernetes-backend/src/service/standaloneApplication.ts b/plugins/kubernetes-backend/src/service/standaloneApplication.ts index 5eea4fb8f5..e23e87a7a2 100644 --- a/plugins/kubernetes-backend/src/service/standaloneApplication.ts +++ b/plugins/kubernetes-backend/src/service/standaloneApplication.ts @@ -25,6 +25,7 @@ import express from 'express'; import helmet from 'helmet'; import { Logger } from 'winston'; import { createRouter } from './router'; +import { ConfigReader } from '@backstage/config'; export interface ApplicationOptions { enableCors: boolean; @@ -35,6 +36,7 @@ export async function createStandaloneApplication( options: ApplicationOptions, ): Promise { const { enableCors, logger } = options; + const config = ConfigReader.fromConfigs([]); const app = express(); app.use(helmet()); @@ -44,7 +46,7 @@ export async function createStandaloneApplication( app.use(compression()); app.use(express.json()); app.use(requestLoggingHandler()); - app.use('/', await createRouter({ logger })); + app.use('/', await createRouter({ logger, config })); app.use(notFoundHandler()); app.use(errorHandler()); diff --git a/plugins/kubernetes-backend/src/types/types.ts b/plugins/kubernetes-backend/src/types/types.ts new file mode 100644 index 0000000000..0cb42eec1a --- /dev/null +++ b/plugins/kubernetes-backend/src/types/types.ts @@ -0,0 +1,128 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + ExtensionsV1beta1Ingress, + V1ConfigMap, + V1Deployment, + V1HorizontalPodAutoscaler, + V1Pod, + V1ReplicaSet, + V1Service, +} from '@kubernetes/client-node'; + +export interface ClusterDetails { + name: string; + url: string; + // TODO this will eventually be configured by the auth translation work + serviceAccountToken: string | undefined; +} + +export interface ClusterObjects { + cluster: { name: string }; + resources: FetchResponse[]; + errors: KubernetesFetchError[]; +} + +export interface ObjectsByServiceIdResponse { + items: ClusterObjects[]; +} + +export interface FetchResponseWrapper { + errors: KubernetesFetchError[]; + responses: FetchResponse[]; +} + +export type FetchResponse = + | PodFetchResponse + | ServiceFetchResponse + | ConfigMapFetchResponse + | DeploymentFetchResponse + | ReplicaSetsFetchResponse + | HorizontalPodAutoscalersFetchResponse + | IngressesFetchResponse; + +// TODO fairly sure there's a easier way to do this + +export type KubernetesObjectTypes = + | 'pods' + | 'services' + | 'configmaps' + | 'deployments' + | 'replicasets' + | 'horizontalpodautoscalers' + | 'ingresses'; + +export interface PodFetchResponse { + type: 'pods'; + resources: Array; +} + +export interface ServiceFetchResponse { + type: 'services'; + resources: Array; +} + +export interface ConfigMapFetchResponse { + type: 'configmaps'; + resources: Array; +} + +export interface DeploymentFetchResponse { + type: 'deployments'; + resources: Array; +} + +export interface ReplicaSetsFetchResponse { + type: 'replicasets'; + resources: Array; +} + +export interface HorizontalPodAutoscalersFetchResponse { + type: 'horizontalpodautoscalers'; + resources: Array; +} + +export interface IngressesFetchResponse { + type: 'ingresses'; + resources: Array; +} + +// Fetches information from a kubernetes cluster using the cluster details object +// to target a specific cluster +export interface KubernetesFetcher { + fetchObjectsByServiceId( + serviceId: string, + clusterDetails: ClusterDetails, + objectTypesToFetch: Set, + ): Promise; +} + +// Used to locate which cluster(s) a service is running on +export interface KubernetesClusterLocator { + getClusterByServiceId(serviceId: string): Promise; +} + +export type KubernetesErrorTypes = + | 'UNAUTHORIZED_ERROR' + | 'SYSTEM_ERROR' + | 'UNKNOWN_ERROR'; + +export interface KubernetesFetchError { + errorType: KubernetesErrorTypes; + statusCode?: number; + resourcePath?: string; +} diff --git a/plugins/kubernetes/package.json b/plugins/kubernetes/package.json index d9311deb85..6d177c8326 100644 --- a/plugins/kubernetes/package.json +++ b/plugins/kubernetes/package.json @@ -22,7 +22,9 @@ "dependencies": { "@backstage/catalog-model": "^0.1.1-alpha.23", "@backstage/core": "^0.1.1-alpha.23", + "@backstage/plugin-kubernetes-backend": "^0.1.1-alpha.23", "@backstage/theme": "^0.1.1-alpha.23", + "@kubernetes/client-node": "^0.12.1", "@material-ui/core": "^4.11.0", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "4.0.0-alpha.45", @@ -34,12 +36,15 @@ "devDependencies": { "@backstage/cli": "^0.1.1-alpha.23", "@backstage/dev-utils": "^0.1.1-alpha.23", + "@backstage/test-utils": "^0.1.1-alpha.23", "@testing-library/jest-dom": "^5.10.1", "@testing-library/react": "^10.4.1", "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/kubernetes/src/Router.tsx b/plugins/kubernetes/src/Router.tsx index 994788bf72..41f534fbef 100644 --- a/plugins/kubernetes/src/Router.tsx +++ b/plugins/kubernetes/src/Router.tsx @@ -22,7 +22,7 @@ import { rootCatalogKubernetesRouteRef } from './plugin'; import { KubernetesContent } from './components/KubernetesContent'; import { WarningPanel } from '@backstage/core'; -const KUBERNETES_ANNOTATION = 'backstage.io/kubernetes'; +const KUBERNETES_ANNOTATION = 'backstage.io/kubernetes-id'; export const Router = ({ entity }: { entity: Entity }) => { const kubernetesAnnotationValue = diff --git a/plugins/kubernetes/src/api/KubernetesBackendClient.ts b/plugins/kubernetes/src/api/KubernetesBackendClient.ts index fed3cd2ed0..cbb3b03a38 100644 --- a/plugins/kubernetes/src/api/KubernetesBackendClient.ts +++ b/plugins/kubernetes/src/api/KubernetesBackendClient.ts @@ -16,6 +16,7 @@ import { DiscoveryApi } from '@backstage/core'; import { KubernetesApi } from './types'; +import { ObjectsByServiceIdResponse } from '@backstage/plugin-kubernetes-backend'; export class KubernetesBackendClient implements KubernetesApi { private readonly discoveryApi: DiscoveryApi; @@ -37,7 +38,9 @@ export class KubernetesBackendClient implements KubernetesApi { return await response.json(); } - async getObjectsByServiceId(serviceId: String): Promise<{}> { + async getObjectsByServiceId( + serviceId: String, + ): Promise { return await this.getRequired(`/services/${serviceId}`); } } diff --git a/plugins/kubernetes/src/api/types.ts b/plugins/kubernetes/src/api/types.ts index 2ad6e567f9..5ec3cda6f8 100644 --- a/plugins/kubernetes/src/api/types.ts +++ b/plugins/kubernetes/src/api/types.ts @@ -15,6 +15,7 @@ */ import { createApiRef } from '@backstage/core'; +import { ObjectsByServiceIdResponse } from '@backstage/plugin-kubernetes-backend'; export const kubernetesApiRef = createApiRef({ id: 'plugin.kubernetes.service', @@ -23,5 +24,5 @@ export const kubernetesApiRef = createApiRef({ }); export interface KubernetesApi { - getObjectsByServiceId(serviceId: String): Promise<{}>; + getObjectsByServiceId(serviceId: String): Promise; } diff --git a/plugins/kubernetes/src/components/ConfigMaps/ConfigMaps.test.tsx b/plugins/kubernetes/src/components/ConfigMaps/ConfigMaps.test.tsx new file mode 100644 index 0000000000..35b8f2143a --- /dev/null +++ b/plugins/kubernetes/src/components/ConfigMaps/ConfigMaps.test.tsx @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import { ConfigMaps } from './ConfigMaps'; +import * as configmapFixture from './__fixtures__/configmap.json'; +import { wrapInTestApp } from '@backstage/test-utils'; + +describe('ConfigMaps', () => { + it('should render configmap', async () => { + const { getByText } = render( + wrapInTestApp( + , + ), + ); + + // title + expect(getByText('dice-roller')).toBeInTheDocument(); + expect(getByText('Config Map')).toBeInTheDocument(); + + // values + expect(getByText('Immutable')).toBeInTheDocument(); + expect(getByText('false')).toBeInTheDocument(); + expect(getByText('Data')).toBeInTheDocument(); + expect(getByText('Foo: bar')).toBeInTheDocument(); // TODO wish this wasn't upper case + }); +}); diff --git a/plugins/kubernetes/src/components/ConfigMaps/ConfigMaps.tsx b/plugins/kubernetes/src/components/ConfigMaps/ConfigMaps.tsx new file mode 100644 index 0000000000..5a013eb2c6 --- /dev/null +++ b/plugins/kubernetes/src/components/ConfigMaps/ConfigMaps.tsx @@ -0,0 +1,51 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Grid } from '@material-ui/core'; +import { V1ConfigMap } from '@kubernetes/client-node'; +import { InfoCard, StructuredMetadataTable } from '@backstage/core'; + +type ConfigMapsProps = { + configMaps: V1ConfigMap[]; + children?: React.ReactNode; +}; + +export const ConfigMaps = ({ configMaps }: ConfigMapsProps) => { + return ( + + {configMaps.map((cm, i) => { + return ( + + +

+ +
+ + + ); + })} + + ); +}; diff --git a/plugins/kubernetes/src/components/ConfigMaps/__fixtures__/configmap.json b/plugins/kubernetes/src/components/ConfigMaps/__fixtures__/configmap.json new file mode 100644 index 0000000000..77ea844611 --- /dev/null +++ b/plugins/kubernetes/src/components/ConfigMaps/__fixtures__/configmap.json @@ -0,0 +1,46 @@ +[ + { + "data": { + "foo": "bar" + }, + "metadata": { + "annotations": { + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"data\":{\"foo\":\"bar\"},\"kind\":\"ConfigMap\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"}}\n" + }, + "creationTimestamp": "2020-09-24T11:39:26.000Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:data": { + ".": {}, + "f:foo": {} + }, + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-24T11:39:26.000Z" + } + ], + "name": "dice-roller", + "namespace": "default", + "resourceVersion": "503867", + "selfLink": "/api/v1/namespaces/default/configmaps/dice-roller", + "uid": "e9efe5ee-53b9-4422-aef2-877a03c73d5f" + } + } +] diff --git a/plugins/kubernetes/src/components/ConfigMaps/index.ts b/plugins/kubernetes/src/components/ConfigMaps/index.ts new file mode 100644 index 0000000000..b1c7d37a5a --- /dev/null +++ b/plugins/kubernetes/src/components/ConfigMaps/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { ConfigMaps } from './ConfigMaps'; diff --git a/plugins/kubernetes/src/components/DeploymentTables/DeploymentTables.test.tsx b/plugins/kubernetes/src/components/DeploymentTables/DeploymentTables.test.tsx new file mode 100644 index 0000000000..3dacac7055 --- /dev/null +++ b/plugins/kubernetes/src/components/DeploymentTables/DeploymentTables.test.tsx @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import { DeploymentTables } from './DeploymentTables'; +import * as twoDeployFixture from './__fixtures__/2-deployments.json'; +import { wrapInTestApp } from '@backstage/test-utils'; + +describe('DeploymentTables', () => { + it('should render 2 deployments', async () => { + const { getByText } = render( + wrapInTestApp( + , + ), + ); + + // title + expect(getByText('dice-roller')).toBeInTheDocument(); + expect(getByText('dice-roller-canary')).toBeInTheDocument(); + + // pod names + expect(getByText('dice-roller-6c8646bfd-2m5hv')).toBeInTheDocument(); + expect( + getByText('dice-roller-canary-7d64cd756c-55rfq'), + ).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/DeploymentTables/DeploymentTables.tsx b/plugins/kubernetes/src/components/DeploymentTables/DeploymentTables.tsx new file mode 100644 index 0000000000..a009c20d7e --- /dev/null +++ b/plugins/kubernetes/src/components/DeploymentTables/DeploymentTables.tsx @@ -0,0 +1,220 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { Fragment } from 'react'; +import { Chip, Grid } from '@material-ui/core'; +import { + StatusAborted, + StatusError, + StatusOK, + SubvalueCell, + Table, + TableColumn, +} from '@backstage/core'; +import { + V1ComponentCondition, + V1Deployment, + V1Pod, + V1ReplicaSet, +} from '@kubernetes/client-node'; +import { V1OwnerReference } from '@kubernetes/client-node/dist/gen/model/v1OwnerReference'; +import { DeploymentTriple } from '../../types/types'; + +const renderCondition = (condition: V1ComponentCondition | undefined) => { + if (!condition) { + return ; + } + + const status = condition.status; + + if (status === 'True') { + return ; + } else if (status === 'False') { + return ; + } + return ; +}; + +const columns: TableColumn[] = [ + { + title: 'name', + highlight: true, + width: '20%', + render: (pod: V1Pod) => pod.metadata?.name ?? 'un-named pod', + }, + { + title: 'images', + width: '20%', + render: (pod: V1Pod) => { + const containerStatuses = pod.status?.containerStatuses ?? []; + return containerStatuses.map((cs, i) => { + return ; + }); + }, + }, + { + title: 'phase', + render: (pod: V1Pod) => pod.status?.phase ?? 'unknown', + }, + { + title: 'containers ready', + align: 'center', + render: (pod: V1Pod) => { + const containerStatuses = pod.status?.containerStatuses ?? []; + const containersReady = containerStatuses.filter(cs => cs.ready).length; + + return `${containersReady}/${containerStatuses.length}`; + }, + }, + { + title: 'total restarts', + render: (pod: V1Pod) => { + const containerStatuses = pod.status?.containerStatuses ?? []; + return containerStatuses?.reduce((a, b) => a + b.restartCount, 0); + }, + type: 'numeric', + }, + { + title: 'status', + width: '20%', + render: (pod: V1Pod) => { + const containerStatuses = pod.status?.containerStatuses ?? []; + const errors = containerStatuses.reduce((accum, next) => { + if (next.state === undefined) { + return accum; + } + + const waiting = next.state.waiting; + const terminated = next.state.terminated; + + const renderCell = (reason: string | undefined) => ( + + Container: {next.name}} + subvalue={reason} + /> +
+ + ); + + if (waiting) { + accum.push(renderCell(waiting.reason)); + } + + if (terminated) { + accum.push(renderCell(terminated.reason)); + } + + return accum; + }, [] as React.ReactNode[]); + + if (errors.length === 0) { + return OK; + } + + return errors; + }, + }, + { + title: 'Pod Initialized', + align: 'center', + render: (pod: V1Pod) => { + const conditions = pod.status?.conditions ?? []; + return renderCondition(conditions.find(c => c.type === 'Initialized')); + }, + }, + { + title: 'Pod Ready', + align: 'center', + render: (pod: V1Pod) => { + const conditions = pod.status?.conditions ?? []; + return renderCondition(conditions.find(c => c.type === 'Ready')); + }, + }, + { + title: 'Containers Ready', + align: 'center', + render: (pod: V1Pod) => { + const conditions = pod.status?.conditions ?? []; + return renderCondition( + conditions.find(c => c.type === 'ContainersReady'), + ); + }, + }, + { + title: 'Pod Scheduled', + align: 'center', + render: (pod: V1Pod) => { + const conditions = pod.status?.conditions ?? []; + return renderCondition(conditions.find(c => c.type === 'PodScheduled')); + }, + }, +]; + +type DeploymentTablesProps = { + deploymentTriple: DeploymentTriple; + children?: React.ReactNode; +}; + +export const DeploymentTables = ({ + deploymentTriple, +}: DeploymentTablesProps) => { + const isOwnedBy = ( + ownerReferences: V1OwnerReference[], + obj: V1Pod | V1ReplicaSet | V1Deployment, + ): boolean => { + return ownerReferences?.some(or => or.name === obj.metadata?.name); + }; + + return ( + + {deploymentTriple.deployments.map((deployment, i) => ( + + {deploymentTriple.replicaSets + // Filter out replica sets with no replicas + .filter(rs => rs.status && rs.status.replicas > 0) + // Find the replica sets this deployment owns + .filter(rs => + isOwnedBy(rs.metadata?.ownerReferences ?? [], deployment), + ) + .map((rs, j) => { + // Find the pods this replica set owns and render them in the table + const ownedPods = deploymentTriple.pods.filter(pod => + isOwnedBy(pod.metadata?.ownerReferences ?? [], rs), + ); + + return ( + +
+ + ); + })} + + ))} + + ); +}; diff --git a/plugins/kubernetes/src/components/DeploymentTables/__fixtures__/2-deployments.json b/plugins/kubernetes/src/components/DeploymentTables/__fixtures__/2-deployments.json new file mode 100644 index 0000000000..e51d0d0b5f --- /dev/null +++ b/plugins/kubernetes/src/components/DeploymentTables/__fixtures__/2-deployments.json @@ -0,0 +1,4435 @@ +{ + "pods": [ + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.11\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller-6c8646bfd-2m5hv", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593216", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-2m5hv", + "uid": "aadb71c0-36fa-43e3-b38a-162f134d4359" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://aa4489297c34c48bb33c18474a8d2b33854a82ed42155680b259f635f556ce70", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.11", + "podIPs": [ + { + "ip": "172.17.0.11" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:50.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.7\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller-6c8646bfd-4v6s8", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593221", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-4v6s8", + "uid": "32e56490-6f20-4757-991f-a0c7fb407358" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://d91cc76c41249b8d3dfcf538d180b471b2a7966aae0d17a818307c8a9b4af897", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.7", + "podIPs": [ + { + "ip": "172.17.0.7" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:50.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-24T11:39:26.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-24T11:39:26.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.6\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-24T11:39:27.000Z" + } + ], + "name": "dice-roller-6c8646bfd-b9zt5", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "503886", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-b9zt5", + "uid": "8b6601b6-469e-4e89-8fd0-abb2f1a567e4" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:26.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:27.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:27.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:26.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://c50e0d0fa96f09a2ed5df7dd5a7f7de88e6b7c7addb8f002f299d6afc52d82ce", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-24T11:39:27.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.6", + "podIPs": [ + { + "ip": "172.17.0.6" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-24T11:39:26.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.13\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller-6c8646bfd-cfxqc", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593211", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-cfxqc", + "uid": "e87e1776-0ca7-41fb-aeea-e1f648387545" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:51.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://c1641d986aae424429b7c2c1117baeb17d3794f73206bd57292cdf8264f929b2", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.13", + "podIPs": [ + { + "ip": "172.17.0.13" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:51.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.15\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:54.000Z" + } + ], + "name": "dice-roller-6c8646bfd-dtv5z", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593190", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-dtv5z", + "uid": "1638a41b-e47e-4c17-a1f7-7b447df248b6" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:51.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:53.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:53.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://e62c32db58dbfe0a74b2d2cba0e0a97b7f222693c68e930037ac8738c4758ca3", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.15", + "podIPs": [ + { + "ip": "172.17.0.15" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:51.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.12\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:53.000Z" + } + ], + "name": "dice-roller-6c8646bfd-hhts2", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593186", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-hhts2", + "uid": "ea0b147a-c56a-46e6-9445-7a0b1b0ed3c0" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:53.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:53.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://bcdbc153630f90556d57ff0d62f04d847ca63a5f0a7e5d9230683623d33d4b8d", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.12", + "podIPs": [ + { + "ip": "172.17.0.12" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:50.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.14\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller-6c8646bfd-j68lm", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593226", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-j68lm", + "uid": "b230ff1d-7a13-479b-9c7b-77c26bd79f62" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://30fa8a3429f86ab8e9a4cec472b79d74266609082703f48950f4aae021e9d6a2", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.14", + "podIPs": [ + { + "ip": "172.17.0.14" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:50.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.9\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:53.000Z" + } + ], + "name": "dice-roller-6c8646bfd-m6f9w", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593181", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-m6f9w", + "uid": "9b0079f6-ff29-4619-bf6e-71cc10199ac5" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:53.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:53.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://f78767ee90eedffe46ff64bfe76d7f69426800dd89f3df012daf0baf3a9c5bdd", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.9", + "podIPs": [ + { + "ip": "172.17.0.9" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:50.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-24T11:39:27.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-24T11:39:27.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.4\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-24T11:39:28.000Z" + } + ], + "name": "dice-roller-6c8646bfd-nv9pk", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "503918", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-nv9pk", + "uid": "acf7f77f-78c6-4d4b-bc73-637211770ffc" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:27.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:28.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:28.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-24T11:39:27.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://63dec9b32942c4b09ae43d09d6978261f674a3ee623823b8f1d20da8044c12ac", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-24T11:39:28.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.4", + "podIPs": [ + { + "ip": "172.17.0.4" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-24T11:39:27.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T09:58:50.000Z", + "generateName": "dice-roller-6c8646bfd-", + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"5126c354-4310-4e23-a9e4-c9b87cb69792\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.10\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller-6c8646bfd-pjhfj", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + } + ], + "resourceVersion": "593205", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-6c8646bfd-pjhfj", + "uid": "78775c3a-7af2-4ebe-a676-bc2e5dfa2bcc" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "status": "True", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T09:58:50.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://cbb83dda250db74285dcbe0b81bd0896acf402bac9710af090311f7360f824aa", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T09:58:53.000Z" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.10", + "podIPs": [ + { + "ip": "172.17.0.10" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T09:58:50.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T10:34:01.000Z", + "generateName": "dice-roller-canary-7d64cd756c-", + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "7d64cd756c" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"9208395b-a9a7-4e46-b881-6a189f7fbdb0\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"other-side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":82,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":81,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T10:34:01.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.16\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T14:18:54.000Z" + } + ], + "name": "dice-roller-canary-7d64cd756c-55rfq", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-canary-7d64cd756c", + "uid": "9208395b-a9a7-4e46-b881-6a189f7fbdb0" + } + ], + "resourceVersion": "620452", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-canary-7d64cd756c-55rfq", + "uid": "65ad28e3-5d51-4b4b-9bf8-4cb069803034" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "side-car", + "ports": [ + { + "containerPort": 81, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "other-side-car", + "ports": [ + { + "containerPort": 82, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T10:34:01.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T14:18:53.000Z", + "message": "containers with unready status: [side-car other-side-car]", + "reason": "ContainersNotReady", + "status": "False", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T14:18:53.000Z", + "message": "containers with unready status: [side-car other-side-car]", + "reason": "ContainersNotReady", + "status": "False", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T10:34:01.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://6ce15178d114a85f3d2e832de45c3355ab5b71ed5f4d4d225ee1c83bf07f69d9", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T10:34:01.000Z" + } + } + }, + { + "containerID": "docker://b3ce93d7f90bfe22558c61d2505b8473580574accdebb5fa4e51c0729c3511f4", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": { + "terminated": { + "containerID": "docker://b3ce93d7f90bfe22558c61d2505b8473580574accdebb5fa4e51c0729c3511f4", + "exitCode": 1, + "finishedAt": "2020-09-25T14:18:52.000Z", + "reason": "Error", + "startedAt": "2020-09-25T14:18:50.000Z" + } + }, + "name": "other-side-car", + "ready": false, + "restartCount": 38, + "started": false, + "state": { + "waiting": { + "message": "back-off 5m0s restarting failed container=other-side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)", + "reason": "CrashLoopBackOff" + } + } + }, + { + "containerID": "docker://b7f0e65a2b8ab48c5f234616cfe8286aa96b55c3ef09c5cfbc4cdbe67a96f8cb", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": { + "terminated": { + "containerID": "docker://b7f0e65a2b8ab48c5f234616cfe8286aa96b55c3ef09c5cfbc4cdbe67a96f8cb", + "exitCode": 1, + "finishedAt": "2020-09-25T14:18:52.000Z", + "reason": "Error", + "startedAt": "2020-09-25T14:18:50.000Z" + } + }, + "name": "side-car", + "ready": false, + "restartCount": 38, + "started": false, + "state": { + "waiting": { + "message": "back-off 5m0s restarting failed container=side-car pod=dice-roller-canary-7d64cd756c-55rfq_default(65ad28e3-5d51-4b4b-9bf8-4cb069803034)", + "reason": "CrashLoopBackOff" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.16", + "podIPs": [ + { + "ip": "172.17.0.16" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T10:34:01.000Z" + } + }, + { + "metadata": { + "creationTimestamp": "2020-09-25T10:34:02.000Z", + "generateName": "dice-roller-canary-7d64cd756c-", + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "7d64cd756c" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:generateName": {}, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"9208395b-a9a7-4e46-b881-6a189f7fbdb0\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"other-side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":82,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":81,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:enableServiceLinks": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T10:34:02.000Z" + }, + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:conditions": { + "k:{\"type\":\"ContainersReady\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Initialized\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Ready\"}": { + ".": {}, + "f:lastProbeTime": {}, + "f:lastTransitionTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:containerStatuses": {}, + "f:hostIP": {}, + "f:phase": {}, + "f:podIP": {}, + "f:podIPs": { + ".": {}, + "k:{\"ip\":\"172.17.0.5\"}": { + ".": {}, + "f:ip": {} + } + }, + "f:startTime": {} + } + }, + "manager": "kubelet", + "operation": "Update", + "time": "2020-09-25T14:19:05.000Z" + } + ], + "name": "dice-roller-canary-7d64cd756c-vtbdx", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "ReplicaSet", + "name": "dice-roller-canary-7d64cd756c", + "uid": "9208395b-a9a7-4e46-b881-6a189f7fbdb0" + } + ], + "resourceVersion": "620481", + "selfLink": "/api/v1/namespaces/default/pods/dice-roller-canary-7d64cd756c-vtbdx", + "uid": "0b8d9d79-b43d-4339-be57-ad5c63add77e" + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "side-car", + "ports": [ + { + "containerPort": 81, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "other-side-car", + "ports": [ + { + "containerPort": 82, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File", + "volumeMounts": [ + { + "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", + "name": "default-token-5gctn", + "readOnly": true + } + ] + } + ], + "dnsPolicy": "ClusterFirst", + "enableServiceLinks": true, + "nodeName": "minikube", + "priority": 0, + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "serviceAccount": "default", + "serviceAccountName": "default", + "terminationGracePeriodSeconds": 30, + "tolerations": [ + { + "effect": "NoExecute", + "key": "node.kubernetes.io/not-ready", + "operator": "Exists", + "tolerationSeconds": 300 + }, + { + "effect": "NoExecute", + "key": "node.kubernetes.io/unreachable", + "operator": "Exists", + "tolerationSeconds": 300 + } + ], + "volumes": [ + { + "name": "default-token-5gctn", + "secret": { + "defaultMode": 420, + "secretName": "default-token-5gctn" + } + } + ] + }, + "status": { + "conditions": [ + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T10:34:02.000Z", + "status": "True", + "type": "Initialized" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T14:19:04.000Z", + "message": "containers with unready status: [side-car other-side-car]", + "reason": "ContainersNotReady", + "status": "False", + "type": "Ready" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T14:19:04.000Z", + "message": "containers with unready status: [side-car other-side-car]", + "reason": "ContainersNotReady", + "status": "False", + "type": "ContainersReady" + }, + { + "lastProbeTime": null, + "lastTransitionTime": "2020-09-25T10:34:02.000Z", + "status": "True", + "type": "PodScheduled" + } + ], + "containerStatuses": [ + { + "containerID": "docker://3f9cadc6f135247eb2df9aaca8f25ea05dcf42be86d58fb833c8acf192da0d66", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": {}, + "name": "nginx", + "ready": true, + "restartCount": 0, + "started": true, + "state": { + "running": { + "startedAt": "2020-09-25T10:34:03.000Z" + } + } + }, + { + "containerID": "docker://5e3a9f9129e5ce74fea249c013afcc056ee95a940fed24495ef9b58df67771f3", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": { + "terminated": { + "containerID": "docker://5e3a9f9129e5ce74fea249c013afcc056ee95a940fed24495ef9b58df67771f3", + "exitCode": 1, + "finishedAt": "2020-09-25T14:19:03.000Z", + "reason": "Error", + "startedAt": "2020-09-25T14:19:01.000Z" + } + }, + "name": "other-side-car", + "ready": false, + "restartCount": 38, + "started": false, + "state": { + "waiting": { + "message": "back-off 5m0s restarting failed container=other-side-car pod=dice-roller-canary-7d64cd756c-vtbdx_default(0b8d9d79-b43d-4339-be57-ad5c63add77e)", + "reason": "CrashLoopBackOff" + } + } + }, + { + "containerID": "docker://21b42cae298c0ed7f90373974d8c88b0941d17733f35398144a17ece32e03210", + "image": "nginx:1.14.2", + "imageID": "docker-pullable://nginx@sha256:f7988fb6c02e0ce69257d9bd9cf37ae20a60f1df7563c3a2a6abe24160306b8d", + "lastState": { + "terminated": { + "containerID": "docker://21b42cae298c0ed7f90373974d8c88b0941d17733f35398144a17ece32e03210", + "exitCode": 1, + "finishedAt": "2020-09-25T14:19:03.000Z", + "reason": "Error", + "startedAt": "2020-09-25T14:19:01.000Z" + } + }, + "name": "side-car", + "ready": false, + "restartCount": 38, + "started": false, + "state": { + "waiting": { + "message": "back-off 5m0s restarting failed container=side-car pod=dice-roller-canary-7d64cd756c-vtbdx_default(0b8d9d79-b43d-4339-be57-ad5c63add77e)", + "reason": "CrashLoopBackOff" + } + } + } + ], + "hostIP": "192.168.64.2", + "phase": "Running", + "podIP": "172.17.0.5", + "podIPs": [ + { + "ip": "172.17.0.5" + } + ], + "qosClass": "BestEffort", + "startTime": "2020-09-25T10:34:02.000Z" + } + } + ], + "replicaSets": [ + { + "metadata": { + "annotations": { + "deployment.kubernetes.io/desired-replicas": "10", + "deployment.kubernetes.io/max-replicas": "13", + "deployment.kubernetes.io/revision": "2" + }, + "creationTimestamp": "2020-09-24T11:39:26.000Z", + "generation": 3, + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + }, + "managedFields": [ + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:deployment.kubernetes.io/desired-replicas": {}, + "f:deployment.kubernetes.io/max-replicas": {}, + "f:deployment.kubernetes.io/revision": {} + }, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"7551e949-42d1-4061-83c5-9da107186e47\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:replicas": {}, + "f:selector": { + "f:matchLabels": { + ".": {}, + "f:app": {}, + "f:pod-template-hash": {} + } + }, + "f:template": { + "f:metadata": { + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + } + }, + "f:status": { + "f:availableReplicas": {}, + "f:fullyLabeledReplicas": {}, + "f:observedGeneration": {}, + "f:readyReplicas": {}, + "f:replicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller-6c8646bfd", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "Deployment", + "name": "dice-roller", + "uid": "7551e949-42d1-4061-83c5-9da107186e47" + } + ], + "resourceVersion": "593228", + "selfLink": "/apis/apps/v1/namespaces/default/replicasets/dice-roller-6c8646bfd", + "uid": "5126c354-4310-4e23-a9e4-c9b87cb69792" + }, + "spec": { + "replicas": 10, + "selector": { + "matchLabels": { + "app": "dice-roller", + "pod-template-hash": "6c8646bfd" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "6c8646bfd" + } + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "terminationGracePeriodSeconds": 30 + } + } + }, + "status": { + "availableReplicas": 10, + "fullyLabeledReplicas": 10, + "observedGeneration": 3, + "readyReplicas": 10, + "replicas": 10 + } + }, + { + "metadata": { + "annotations": { + "deployment.kubernetes.io/desired-replicas": "2", + "deployment.kubernetes.io/max-replicas": "3", + "deployment.kubernetes.io/revision": "3" + }, + "creationTimestamp": "2020-09-25T10:34:01.000Z", + "generation": 2, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "7d64cd756c" + }, + "managedFields": [ + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:deployment.kubernetes.io/desired-replicas": {}, + "f:deployment.kubernetes.io/max-replicas": {}, + "f:deployment.kubernetes.io/revision": {} + }, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"0b6ae80f-999b-40e9-b116-ea925f0ed07b\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:replicas": {}, + "f:selector": { + "f:matchLabels": { + ".": {}, + "f:app": {}, + "f:pod-template-hash": {} + } + }, + "f:template": { + "f:metadata": { + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"other-side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":82,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":81,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + } + }, + "f:status": { + "f:fullyLabeledReplicas": {}, + "f:observedGeneration": {}, + "f:replicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T14:19:01.000Z" + } + ], + "name": "dice-roller-canary-7d64cd756c", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "Deployment", + "name": "dice-roller-canary", + "uid": "0b6ae80f-999b-40e9-b116-ea925f0ed07b" + } + ], + "resourceVersion": "620479", + "selfLink": "/apis/apps/v1/namespaces/default/replicasets/dice-roller-canary-7d64cd756c", + "uid": "9208395b-a9a7-4e46-b881-6a189f7fbdb0" + }, + "spec": { + "replicas": 2, + "selector": { + "matchLabels": { + "app": "dice-roller-canary", + "pod-template-hash": "7d64cd756c" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "7d64cd756c" + } + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "side-car", + "ports": [ + { + "containerPort": 81, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "other-side-car", + "ports": [ + { + "containerPort": 82, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "terminationGracePeriodSeconds": 30 + } + } + }, + "status": { + "fullyLabeledReplicas": 2, + "observedGeneration": 2, + "replicas": 2 + } + }, + { + "metadata": { + "annotations": { + "deployment.kubernetes.io/desired-replicas": "2", + "deployment.kubernetes.io/max-replicas": "3", + "deployment.kubernetes.io/revision": "2" + }, + "creationTimestamp": "2020-09-25T09:25:16.000Z", + "generation": 4, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "bcb8d54dd" + }, + "managedFields": [ + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:deployment.kubernetes.io/desired-replicas": {}, + "f:deployment.kubernetes.io/max-replicas": {}, + "f:deployment.kubernetes.io/revision": {} + }, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"0b6ae80f-999b-40e9-b116-ea925f0ed07b\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:replicas": {}, + "f:selector": { + "f:matchLabels": { + ".": {}, + "f:app": {}, + "f:pod-template-hash": {} + } + }, + "f:template": { + "f:metadata": { + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":81,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + } + }, + "f:status": { + "f:observedGeneration": {}, + "f:replicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T10:34:04.000Z" + } + ], + "name": "dice-roller-canary-bcb8d54dd", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "Deployment", + "name": "dice-roller-canary", + "uid": "0b6ae80f-999b-40e9-b116-ea925f0ed07b" + } + ], + "resourceVersion": "598025", + "selfLink": "/apis/apps/v1/namespaces/default/replicasets/dice-roller-canary-bcb8d54dd", + "uid": "51942585-d599-42aa-bf23-9cf1acad4006" + }, + "spec": { + "replicas": 0, + "selector": { + "matchLabels": { + "app": "dice-roller-canary", + "pod-template-hash": "bcb8d54dd" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "bcb8d54dd" + } + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "side-car", + "ports": [ + { + "containerPort": 81, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "terminationGracePeriodSeconds": 30 + } + } + }, + "status": { + "observedGeneration": 4, + "replicas": 0 + } + }, + { + "metadata": { + "annotations": { + "deployment.kubernetes.io/desired-replicas": "2", + "deployment.kubernetes.io/max-replicas": "3", + "deployment.kubernetes.io/revision": "1" + }, + "creationTimestamp": "2020-09-25T09:02:53.000Z", + "generation": 3, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "c866fbf67" + }, + "managedFields": [ + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:deployment.kubernetes.io/desired-replicas": {}, + "f:deployment.kubernetes.io/max-replicas": {}, + "f:deployment.kubernetes.io/revision": {} + }, + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + }, + "f:ownerReferences": { + ".": {}, + "k:{\"uid\":\"0b6ae80f-999b-40e9-b116-ea925f0ed07b\"}": { + ".": {}, + "f:apiVersion": {}, + "f:blockOwnerDeletion": {}, + "f:controller": {}, + "f:kind": {}, + "f:name": {}, + "f:uid": {} + } + } + }, + "f:spec": { + "f:replicas": {}, + "f:selector": { + "f:matchLabels": { + ".": {}, + "f:app": {}, + "f:pod-template-hash": {} + } + }, + "f:template": { + "f:metadata": { + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {}, + "f:pod-template-hash": {} + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + } + }, + "f:status": { + "f:observedGeneration": {}, + "f:replicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:25:20.000Z" + } + ], + "name": "dice-roller-canary-c866fbf67", + "namespace": "default", + "ownerReferences": [ + { + "apiVersion": "apps/v1", + "blockOwnerDeletion": true, + "controller": true, + "kind": "Deployment", + "name": "dice-roller-canary", + "uid": "0b6ae80f-999b-40e9-b116-ea925f0ed07b" + } + ], + "resourceVersion": "588501", + "selfLink": "/apis/apps/v1/namespaces/default/replicasets/dice-roller-canary-c866fbf67", + "uid": "4d2dfe13-978f-4504-9036-ca585acdea6c" + }, + "spec": { + "replicas": 0, + "selector": { + "matchLabels": { + "app": "dice-roller-canary", + "pod-template-hash": "c866fbf67" + } + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller", + "pod-template-hash": "c866fbf67" + } + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "terminationGracePeriodSeconds": 30 + } + } + }, + "status": { + "observedGeneration": 3, + "replicas": 0 + } + } + ], + "deployments": [ + { + "metadata": { + "annotations": { + "deployment.kubernetes.io/revision": "2", + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"replicas\":10,\"selector\":{\"matchLabels\":{\"app\":\"dice-roller\"}},\"template\":{\"metadata\":{\"labels\":{\"app\":\"dice-roller\",\"backstage.io/kubernetes-id\":\"dice-roller\"}},\"spec\":{\"containers\":[{\"image\":\"nginx:1.14.2\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]}]}}}}\n" + }, + "creationTimestamp": "2020-09-23T12:00:55.000Z", + "generation": 3, + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:progressDeadlineSeconds": {}, + "f:replicas": {}, + "f:revisionHistoryLimit": {}, + "f:selector": { + "f:matchLabels": { + ".": {}, + "f:app": {} + } + }, + "f:strategy": { + "f:rollingUpdate": { + ".": {}, + "f:maxSurge": {}, + "f:maxUnavailable": {} + }, + "f:type": {} + }, + "f:template": { + "f:metadata": { + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + } + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-25T09:58:50.000Z" + }, + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + "f:deployment.kubernetes.io/revision": {} + } + }, + "f:status": { + "f:availableReplicas": {}, + "f:conditions": { + ".": {}, + "k:{\"type\":\"Available\"}": { + ".": {}, + "f:lastTransitionTime": {}, + "f:lastUpdateTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Progressing\"}": { + ".": {}, + "f:lastTransitionTime": {}, + "f:lastUpdateTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:observedGeneration": {}, + "f:readyReplicas": {}, + "f:replicas": {}, + "f:updatedReplicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T09:58:55.000Z" + } + ], + "name": "dice-roller", + "namespace": "default", + "resourceVersion": "593230", + "selfLink": "/apis/apps/v1/namespaces/default/deployments/dice-roller", + "uid": "7551e949-42d1-4061-83c5-9da107186e47" + }, + "spec": { + "progressDeadlineSeconds": 600, + "replicas": 10, + "revisionHistoryLimit": 10, + "selector": { + "matchLabels": { + "app": "dice-roller" + } + }, + "strategy": { + "rollingUpdate": { + "maxSurge": "25%", + "maxUnavailable": "25%" + }, + "type": "RollingUpdate" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "app": "dice-roller", + "backstage.io/kubernetes-id": "dice-roller" + } + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "terminationGracePeriodSeconds": 30 + } + } + }, + "status": { + "availableReplicas": 10, + "conditions": [ + { + "lastTransitionTime": "2020-09-23T12:00:55.000Z", + "lastUpdateTime": "2020-09-24T11:39:28.000Z", + "message": "ReplicaSet \"dice-roller-6c8646bfd\" has successfully progressed.", + "reason": "NewReplicaSetAvailable", + "status": "True", + "type": "Progressing" + }, + { + "lastTransitionTime": "2020-09-25T09:58:55.000Z", + "lastUpdateTime": "2020-09-25T09:58:55.000Z", + "message": "Deployment has minimum availability.", + "reason": "MinimumReplicasAvailable", + "status": "True", + "type": "Available" + } + ], + "observedGeneration": 3, + "readyReplicas": 10, + "replicas": 10, + "updatedReplicas": 10 + } + }, + { + "metadata": { + "annotations": { + "deployment.kubernetes.io/revision": "3", + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller-canary\",\"namespace\":\"default\"},\"spec\":{\"replicas\":2,\"selector\":{\"matchLabels\":{\"app\":\"dice-roller-canary\"}},\"template\":{\"metadata\":{\"labels\":{\"app\":\"dice-roller-canary\",\"backstage.io/kubernetes-id\":\"dice-roller\"}},\"spec\":{\"containers\":[{\"image\":\"nginx:1.14.2\",\"name\":\"nginx\",\"ports\":[{\"containerPort\":80}]},{\"image\":\"nginx:1.14.2\",\"name\":\"side-car\",\"ports\":[{\"containerPort\":81}]},{\"image\":\"nginx:1.14.2\",\"name\":\"other-side-car\",\"ports\":[{\"containerPort\":82}]}]}}}}\n" + }, + "creationTimestamp": "2020-09-25T09:02:53.000Z", + "generation": 3, + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:progressDeadlineSeconds": {}, + "f:replicas": {}, + "f:revisionHistoryLimit": {}, + "f:selector": { + "f:matchLabels": { + ".": {}, + "f:app": {} + } + }, + "f:strategy": { + "f:rollingUpdate": { + ".": {}, + "f:maxSurge": {}, + "f:maxUnavailable": {} + }, + "f:type": {} + }, + "f:template": { + "f:metadata": { + "f:labels": { + ".": {}, + "f:app": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:containers": { + "k:{\"name\":\"nginx\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"other-side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":82,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + }, + "k:{\"name\":\"side-car\"}": { + ".": {}, + "f:image": {}, + "f:imagePullPolicy": {}, + "f:name": {}, + "f:ports": { + ".": {}, + "k:{\"containerPort\":81,\"protocol\":\"TCP\"}": { + ".": {}, + "f:containerPort": {}, + "f:protocol": {} + } + }, + "f:resources": {}, + "f:terminationMessagePath": {}, + "f:terminationMessagePolicy": {} + } + }, + "f:dnsPolicy": {}, + "f:restartPolicy": {}, + "f:schedulerName": {}, + "f:securityContext": {}, + "f:terminationGracePeriodSeconds": {} + } + } + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-25T10:34:01.000Z" + }, + { + "apiVersion": "apps/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + "f:deployment.kubernetes.io/revision": {} + } + }, + "f:status": { + "f:conditions": { + ".": {}, + "k:{\"type\":\"Available\"}": { + ".": {}, + "f:lastTransitionTime": {}, + "f:lastUpdateTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + }, + "k:{\"type\":\"Progressing\"}": { + ".": {}, + "f:lastTransitionTime": {}, + "f:lastUpdateTime": {}, + "f:message": {}, + "f:reason": {}, + "f:status": {}, + "f:type": {} + } + }, + "f:observedGeneration": {}, + "f:replicas": {}, + "f:unavailableReplicas": {}, + "f:updatedReplicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-25T14:19:04.000Z" + } + ], + "name": "dice-roller-canary", + "namespace": "default", + "resourceVersion": "620480", + "selfLink": "/apis/apps/v1/namespaces/default/deployments/dice-roller-canary", + "uid": "0b6ae80f-999b-40e9-b116-ea925f0ed07b" + }, + "spec": { + "progressDeadlineSeconds": 600, + "replicas": 2, + "revisionHistoryLimit": 10, + "selector": { + "matchLabels": { + "app": "dice-roller-canary" + } + }, + "strategy": { + "rollingUpdate": { + "maxSurge": "25%", + "maxUnavailable": "25%" + }, + "type": "RollingUpdate" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "app": "dice-roller-canary", + "backstage.io/kubernetes-id": "dice-roller" + } + }, + "spec": { + "containers": [ + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "nginx", + "ports": [ + { + "containerPort": 80, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "side-car", + "ports": [ + { + "containerPort": 81, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + }, + { + "image": "nginx:1.14.2", + "imagePullPolicy": "IfNotPresent", + "name": "other-side-car", + "ports": [ + { + "containerPort": 82, + "protocol": "TCP" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "terminationMessagePolicy": "File" + } + ], + "dnsPolicy": "ClusterFirst", + "restartPolicy": "Always", + "schedulerName": "default-scheduler", + "securityContext": {}, + "terminationGracePeriodSeconds": 30 + } + } + }, + "status": { + "conditions": [ + { + "lastTransitionTime": "2020-09-25T09:02:53.000Z", + "lastUpdateTime": "2020-09-25T10:34:04.000Z", + "message": "ReplicaSet \"dice-roller-canary-7d64cd756c\" has successfully progressed.", + "reason": "NewReplicaSetAvailable", + "status": "True", + "type": "Progressing" + }, + { + "lastTransitionTime": "2020-09-25T13:48:06.000Z", + "lastUpdateTime": "2020-09-25T13:48:06.000Z", + "message": "Deployment does not have minimum availability.", + "reason": "MinimumReplicasUnavailable", + "status": "False", + "type": "Available" + } + ], + "observedGeneration": 3, + "replicas": 2, + "unavailableReplicas": 2, + "updatedReplicas": 2 + } + } + ] +} diff --git a/plugins/kubernetes/src/components/DeploymentTables/index.ts b/plugins/kubernetes/src/components/DeploymentTables/index.ts new file mode 100644 index 0000000000..dac38c5c81 --- /dev/null +++ b/plugins/kubernetes/src/components/DeploymentTables/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { DeploymentTables } from './DeploymentTables'; diff --git a/plugins/kubernetes/src/components/HorizontalPodAutoscalers/HorizontalPodAutoscalers.test.tsx b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/HorizontalPodAutoscalers.test.tsx new file mode 100644 index 0000000000..eb5d407c76 --- /dev/null +++ b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/HorizontalPodAutoscalers.test.tsx @@ -0,0 +1,52 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import * as hpaFixture from './__fixtures__/horizontalpodautoscalers.json'; +import { wrapInTestApp } from '@backstage/test-utils'; +import { HorizontalPodAutoscalers } from './HorizontalPodAutoscalers'; + +describe('HorizontalPodAutoscalers', () => { + it('should render horizontalpodautoscaler', async () => { + const { getByText, getAllByText } = render( + wrapInTestApp( + , + ), + ); + + // title + expect(getByText('dice-roller')).toBeInTheDocument(); + expect(getByText('Horizontal Pod Autoscaler')).toBeInTheDocument(); + + expect(getByText('Scaling Target')).toBeInTheDocument(); + expect(getByText('Api Version: apps/v1')).toBeInTheDocument(); + expect(getByText('Kind: Deployment')).toBeInTheDocument(); + expect(getByText('Name: dice-roller')).toBeInTheDocument(); + expect(getByText('Min Replicas')).toBeInTheDocument(); + expect(getByText('Max Replicas')).toBeInTheDocument(); + expect(getByText('15')).toBeInTheDocument(); + expect(getByText('Current Replicas')).toBeInTheDocument(); + expect(getByText('Desired Replicas')).toBeInTheDocument(); + expect(getByText('0')).toBeInTheDocument(); + expect(getByText('Target CPU Utilization Percentage')).toBeInTheDocument(); + expect(getByText('50')).toBeInTheDocument(); + expect(getByText('Current CPU Utilization Percentage')).toBeInTheDocument(); + expect(getByText('Last Scale Time')).toBeInTheDocument(); + expect(getAllByText('unknown')).toHaveLength(2); + expect(getAllByText('10')).toHaveLength(2); + }); +}); diff --git a/plugins/kubernetes/src/components/HorizontalPodAutoscalers/HorizontalPodAutoscalers.tsx b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/HorizontalPodAutoscalers.tsx new file mode 100644 index 0000000000..b4540840d2 --- /dev/null +++ b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/HorizontalPodAutoscalers.tsx @@ -0,0 +1,64 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Grid } from '@material-ui/core'; +import { V1HorizontalPodAutoscaler } from '@kubernetes/client-node'; +import { InfoCard, StructuredMetadataTable } from '@backstage/core'; +import { orUnknown } from '../../utils'; + +type HorizontalPodAutoscalersProps = { + hpas: V1HorizontalPodAutoscaler[]; + children?: React.ReactNode; +}; + +export const HorizontalPodAutoscalers = ({ + hpas, +}: HorizontalPodAutoscalersProps) => { + return ( + + {hpas.map((hpa, i) => { + return ( + + +
+ +
+
+
+ ); + })} +
+ ); +}; diff --git a/plugins/kubernetes/src/components/HorizontalPodAutoscalers/__fixtures__/horizontalpodautoscalers.json b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/__fixtures__/horizontalpodautoscalers.json new file mode 100644 index 0000000000..6bc6028246 --- /dev/null +++ b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/__fixtures__/horizontalpodautoscalers.json @@ -0,0 +1,81 @@ +[ + { + "metadata": { + "annotations": { + "autoscaling.alpha.kubernetes.io/conditions": "[{\"type\":\"AbleToScale\",\"status\":\"True\",\"lastTransitionTime\":\"2020-09-28T13:28:15Z\",\"reason\":\"SucceededGetScale\",\"message\":\"the HPA controller was able to get the target's current scale\"},{\"type\":\"ScalingActive\",\"status\":\"False\",\"lastTransitionTime\":\"2020-09-28T13:28:15Z\",\"reason\":\"FailedGetResourceMetric\",\"message\":\"the HPA was unable to compute the replica count: unable to get metrics for resource cpu: unable to fetch metrics from resource metrics API: the server could not find the requested resource (get pods.metrics.k8s.io)\"}]", + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"autoscaling/v1\",\"kind\":\"HorizontalPodAutoscaler\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"maxReplicas\":15,\"minReplicas\":10,\"scaleTargetRef\":{\"apiVersion\":\"apps/v1\",\"kind\":\"Deployment\",\"name\":\"dice-roller\"},\"targetCPUUtilizationPercentage\":50}}\n" + }, + "creationTimestamp": "2020-09-28T13:28:00.000Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "autoscaling/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + "f:autoscaling.alpha.kubernetes.io/conditions": {} + } + }, + "f:status": { + "f:currentReplicas": {} + } + }, + "manager": "kube-controller-manager", + "operation": "Update", + "time": "2020-09-28T13:28:15.000Z" + }, + { + "apiVersion": "autoscaling/v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:maxReplicas": {}, + "f:minReplicas": {}, + "f:scaleTargetRef": { + "f:apiVersion": {}, + "f:kind": {}, + "f:name": {} + }, + "f:targetCPUUtilizationPercentage": {} + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-28T13:28:21.000Z" + } + ], + "name": "dice-roller", + "namespace": "default", + "resourceVersion": "698957", + "selfLink": "/apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/dice-roller", + "uid": "a70c8a90-5605-4d7d-adea-05cfb8d9d446" + }, + "spec": { + "maxReplicas": 15, + "minReplicas": 10, + "scaleTargetRef": { + "apiVersion": "apps/v1", + "kind": "Deployment", + "name": "dice-roller" + }, + "targetCPUUtilizationPercentage": 50 + }, + "status": { + "currentReplicas": 10, + "desiredReplicas": 0 + } + } +] diff --git a/plugins/kubernetes/src/components/HorizontalPodAutoscalers/index.ts b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/index.ts new file mode 100644 index 0000000000..3eebbe9813 --- /dev/null +++ b/plugins/kubernetes/src/components/HorizontalPodAutoscalers/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { HorizontalPodAutoscalers } from './HorizontalPodAutoscalers'; diff --git a/plugins/kubernetes/src/components/Ingresses/Ingresses.test.tsx b/plugins/kubernetes/src/components/Ingresses/Ingresses.test.tsx new file mode 100644 index 0000000000..f2507a3f39 --- /dev/null +++ b/plugins/kubernetes/src/components/Ingresses/Ingresses.test.tsx @@ -0,0 +1,47 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import * as ingressesFixture from './__fixtures__/ingress.json'; +import { wrapInTestApp } from '@backstage/test-utils'; +import { Ingresses } from './Ingresses'; + +describe('Ingresses', () => { + it('should render ingress', async () => { + const { getByText } = render( + wrapInTestApp( + , + ), + ); + + // title + expect(getByText('dice-roller')).toBeInTheDocument(); + expect(getByText('Ingress')).toBeInTheDocument(); + + // values + expect(getByText('Backend')).toBeInTheDocument(); + expect(getByText('Ip: 192.168.64.2')).toBeInTheDocument(); + expect(getByText('Rules')).toBeInTheDocument(); + expect(getByText('Host: nginx')).toBeInTheDocument(); + expect(getByText('Http:')).toBeInTheDocument(); + expect(getByText('Paths:')).toBeInTheDocument(); + expect(getByText('Service Name: dice-roller')).toBeInTheDocument(); + expect(getByText('Service Port: 80')).toBeInTheDocument(); + expect(getByText('Path: /')).toBeInTheDocument(); + expect(getByText('Path Type: ImplementationSpecific')).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/Ingresses/Ingresses.tsx b/plugins/kubernetes/src/components/Ingresses/Ingresses.tsx new file mode 100644 index 0000000000..37932601a1 --- /dev/null +++ b/plugins/kubernetes/src/components/Ingresses/Ingresses.tsx @@ -0,0 +1,51 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Grid } from '@material-ui/core'; +import { ExtensionsV1beta1Ingress } from '@kubernetes/client-node'; +import { InfoCard, StructuredMetadataTable } from '@backstage/core'; + +type IngressesProps = { + ingresses: ExtensionsV1beta1Ingress[]; + children?: React.ReactNode; +}; + +export const Ingresses = ({ ingresses }: IngressesProps) => { + return ( + + {ingresses.map((ingress, i) => { + return ( + + +
+ +
+
+
+ ); + })} +
+ ); +}; diff --git a/plugins/kubernetes/src/components/Ingresses/__fixtures__/ingress.json b/plugins/kubernetes/src/components/Ingresses/__fixtures__/ingress.json new file mode 100644 index 0000000000..fd0bc5ec43 --- /dev/null +++ b/plugins/kubernetes/src/components/Ingresses/__fixtures__/ingress.json @@ -0,0 +1,87 @@ +[ + { + "metadata": { + "annotations": { + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"networking.k8s.io/v1beta1\",\"kind\":\"Ingress\",\"metadata\":{\"annotations\":{\"nginx.ingress.kubernetes.io/rewrite-target\":\"/$1\"},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"rules\":[{\"host\":\"nginx\",\"http\":{\"paths\":[{\"backend\":{\"serviceName\":\"dice-roller\",\"servicePort\":80},\"path\":\"/\"}]}}]}}\n", + "nginx.ingress.kubernetes.io/rewrite-target": "/$1" + }, + "creationTimestamp": "2020-09-28T13:28:00.000Z", + "generation": 1, + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "networking.k8s.io/v1beta1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {}, + "f:nginx.ingress.kubernetes.io/rewrite-target": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:rules": {} + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-28T13:28:21.000Z" + }, + { + "apiVersion": "networking.k8s.io/v1beta1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:status": { + "f:loadBalancer": { + "f:ingress": {} + } + } + }, + "manager": "nginx-ingress-controller", + "operation": "Update", + "time": "2020-09-28T13:28:40.000Z" + } + ], + "name": "dice-roller", + "namespace": "default", + "resourceVersion": "699017", + "selfLink": "/apis/networking.k8s.io/v1beta1/namespaces/default/ingresses/dice-roller", + "uid": "e96994c0-49b9-4c1c-8ce0-72c5336fe960" + }, + "spec": { + "rules": [ + { + "host": "nginx", + "http": { + "paths": [ + { + "backend": { + "serviceName": "dice-roller", + "servicePort": 80 + }, + "path": "/", + "pathType": "ImplementationSpecific" + } + ] + } + } + ] + }, + "status": { + "loadBalancer": { + "ingress": [ + { + "ip": "192.168.64.2" + } + ] + } + } + } +] diff --git a/plugins/kubernetes/src/components/Ingresses/index.ts b/plugins/kubernetes/src/components/Ingresses/index.ts new file mode 100644 index 0000000000..ecc67480db --- /dev/null +++ b/plugins/kubernetes/src/components/Ingresses/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Ingresses } from './Ingresses'; diff --git a/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx new file mode 100644 index 0000000000..6985423a10 --- /dev/null +++ b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.test.tsx @@ -0,0 +1,83 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import { wrapInTestApp } from '@backstage/test-utils'; +import { ErrorPanel } from './ErrorPanel'; + +describe('ErrorPanel', () => { + it('render with error message', async () => { + const { getByText } = render( + wrapInTestApp( + , + ), + ); + + // title + expect( + getByText( + 'There was an error retrieving some Kubernetes resources for the entity: THIS_ENTITY', + ), + ).toBeInTheDocument(); + + // message + expect(getByText('Errors: SOME_ERROR_MESSAGE')).toBeInTheDocument(); + }); + it('render with cluster errors', async () => { + const { getByText } = render( + wrapInTestApp( + , + ), + ); + + // title + expect( + getByText( + 'There was an error retrieving some Kubernetes resources for the entity: THIS_ENTITY', + ), + ).toBeInTheDocument(); + + // message + expect(getByText('Errors:')).toBeInTheDocument(); + expect(getByText('Cluster: THIS_CLUSTER')).toBeInTheDocument(); + expect( + getByText( + "Error fetching Kubernetes resource: 'some/resource', error: SYSTEM_ERROR", + ), + ).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx new file mode 100644 index 0000000000..1fe5714b09 --- /dev/null +++ b/plugins/kubernetes/src/components/KubernetesContent/ErrorPanel.tsx @@ -0,0 +1,65 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { WarningPanel } from '@backstage/core'; +import { Typography } from '@material-ui/core'; +import { ClusterObjects } from '../../../../kubernetes-backend/src'; + +const clustersWithErrorsToErrorMessage = ( + clustersWithErrors: ClusterObjects[], +): React.ReactNode => { + return clustersWithErrors.map((c, i) => { + return ( +
+ {`Cluster: ${c.cluster.name}`} + {c.errors.map((e, j) => { + return ( + + {`Error fetching Kubernetes resource: '${e.resourcePath}', error: ${e.errorType}`} + + ); + })} +
+
+ ); + }); +}; + +type ErrorPanelProps = { + entityName: string; + errorMessage?: string; + clustersWithErrors?: ClusterObjects[]; + children?: React.ReactNode; +}; + +export const ErrorPanel = ({ + entityName, + errorMessage, + clustersWithErrors, +}: ErrorPanelProps) => ( + + {clustersWithErrors && ( +
Errors: {clustersWithErrorsToErrorMessage(clustersWithErrors)}
+ )} + {errorMessage && ( + Errors: {errorMessage} + )} +
+); diff --git a/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx b/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx index d79454a5d1..6119884c43 100644 --- a/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx +++ b/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx @@ -14,26 +14,95 @@ * limitations under the License. */ -import React, { FC, useEffect, useState } from 'react'; -import { Typography, Grid } from '@material-ui/core'; +import React, { ReactElement, useEffect, useState } from 'react'; +import { Grid, TabProps } from '@material-ui/core'; import { - InfoCard, + CardTab, + Content, Page, pageTheme, - Content, - ContentHeader, + Progress, + TabbedCard, useApi, } from '@backstage/core'; import { Entity } from '@backstage/catalog-model'; import { kubernetesApiRef } from '../../api/types'; +import { + ClusterObjects, + FetchResponse, + ObjectsByServiceIdResponse, +} from '@backstage/plugin-kubernetes-backend'; +import { DeploymentTables } from '../DeploymentTables'; +import { DeploymentTriple } from '../../types/types'; +import { + ExtensionsV1beta1Ingress, + V1ConfigMap, + V1HorizontalPodAutoscaler, + V1Service, +} from '@kubernetes/client-node'; +import { Services } from '../Services'; +import { ConfigMaps } from '../ConfigMaps'; +import { Ingresses } from '../Ingresses'; +import { HorizontalPodAutoscalers } from '../HorizontalPodAutoscalers'; +import { ErrorPanel } from './ErrorPanel'; -// TODO this is a temporary component used to construct the Kubernetes plugin boilerplate +interface GroupedResponses extends DeploymentTriple { + services: V1Service[]; + configMaps: V1ConfigMap[]; + horizontalPodAutoscalers: V1HorizontalPodAutoscaler[]; + ingresses: ExtensionsV1beta1Ingress[]; +} -export const KubernetesContent: FC<{ entity: Entity }> = ({ entity }) => { - const kubernetesApi = useApi(kubernetesApiRef); - const [kubernetesObjects, setKubernetesObjects] = useState<{} | undefined>( - undefined, +// TODO this could probably be a lodash groupBy +const groupResponses = (fetchResponse: FetchResponse[]) => { + return fetchResponse.reduce( + (prev, next) => { + switch (next.type) { + case 'deployments': + prev.deployments.push(...next.resources); + break; + case 'pods': + prev.pods.push(...next.resources); + break; + case 'replicasets': + prev.replicaSets.push(...next.resources); + break; + case 'services': + prev.services.push(...next.resources); + break; + case 'configmaps': + prev.configMaps.push(...next.resources); + break; + case 'horizontalpodautoscalers': + prev.horizontalPodAutoscalers.push(...next.resources); + break; + case 'ingresses': + prev.ingresses.push(...next.resources); + break; + default: + } + return prev; + }, + { + pods: [], + replicaSets: [], + deployments: [], + services: [], + configMaps: [], + horizontalPodAutoscalers: [], + ingresses: [], + } as GroupedResponses, ); +}; + +type KubernetesContentProps = { entity: Entity; children?: React.ReactNode }; + +export const KubernetesContent = ({ entity }: KubernetesContentProps) => { + const kubernetesApi = useApi(kubernetesApiRef); + + const [kubernetesObjects, setKubernetesObjects] = useState< + ObjectsByServiceIdResponse | undefined + >(undefined); const [error, setError] = useState(undefined); useEffect(() => { @@ -47,26 +116,107 @@ export const KubernetesContent: FC<{ entity: Entity }> = ({ entity }) => { }); }, [entity.metadata.name, kubernetesApi]); + const clustersWithErrors = + kubernetesObjects?.items.filter(r => r.errors.length > 0) ?? []; + return ( - - - - - {kubernetesObjects === undefined &&
loading....
} - {error !== undefined &&
{error}
} - {kubernetesObjects !== undefined && ( -
- backend response: {JSON.stringify(kubernetesObjects)} -
- )} -
-
-
+ {kubernetesObjects === undefined && error === undefined && ( + + )} + + {/* errors retrieved from the kubernetes clusters */} + {clustersWithErrors.length > 0 && ( + + )} + + {/* other errors */} + {error !== undefined && ( + + )} + + {kubernetesObjects?.items.map((item, i) => ( + + + + ))}
); }; + +type ClusterProps = { + clusterObjects: ClusterObjects; + children?: React.ReactNode; +}; + +const Cluster = ({ clusterObjects }: ClusterProps) => { + const [selectedTab, setSelectedTab] = useState('one'); + + const handleChange = (_ev: any, newSelectedTab: string | number) => + setSelectedTab(newSelectedTab); + + const groupedResponses = groupResponses(clusterObjects.resources); + + const configMaps = groupedResponses.configMaps; + const hpas = groupedResponses.horizontalPodAutoscalers; + const ingresses = groupedResponses.ingresses; + + const tabs: ReactElement[] = [ + + + , + + + , + ]; + + if (configMaps.length > 0) { + tabs.push( + + + , + ); + } + if (hpas.length > 0) { + tabs.push( + + + , + ); + } + if (ingresses.length > 0) { + tabs.push( + + + , + ); + } + + return ( + <> + + {tabs} + + + ); +}; diff --git a/plugins/kubernetes/src/components/Services/Services.test.tsx b/plugins/kubernetes/src/components/Services/Services.test.tsx new file mode 100644 index 0000000000..5e74499bc5 --- /dev/null +++ b/plugins/kubernetes/src/components/Services/Services.test.tsx @@ -0,0 +1,54 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { render } from '@testing-library/react'; +import { Services } from './Services'; +import * as servicesFixture from './__fixtures__/services.json'; +import { wrapInTestApp } from '@backstage/test-utils'; + +describe('Services', () => { + it('should render 2 services', async () => { + const { getByText, getAllByText } = render( + wrapInTestApp(), + ); + + // common elements + expect(getAllByText('Service')).toHaveLength(2); + expect(getAllByText('Ports')).toHaveLength(2); + expect(getAllByText('Type')).toHaveLength(2); + expect(getAllByText('Protocol: TCP')).toHaveLength(3); + + // service 1 + expect(getByText('dice-roller')).toBeInTheDocument(); + expect(getByText('ClusterIP')).toBeInTheDocument(); + + expect(getByText('Name: port1')).toBeInTheDocument(); + expect(getByText('Port: 80')).toBeInTheDocument(); + expect(getByText('Target Port: 9376')).toBeInTheDocument(); + expect(getByText('Name: port1')).toBeInTheDocument(); + expect(getByText('Port: 81')).toBeInTheDocument(); + expect(getByText('Target Port: 9377')).toBeInTheDocument(); + expect(getByText('10.102.223.105')).toBeInTheDocument(); + + // service 2 + expect(getByText('dice-roller-lb')).toBeInTheDocument(); + expect(getByText('LoadBalancer')).toBeInTheDocument(); + expect(getByText('Node Port: 32276')).toBeInTheDocument(); + expect(getByText('Port: 8765')).toBeInTheDocument(); + expect(getByText('Target Port: 9378')).toBeInTheDocument(); + }); +}); diff --git a/plugins/kubernetes/src/components/Services/Services.tsx b/plugins/kubernetes/src/components/Services/Services.tsx new file mode 100644 index 0000000000..d0a4f71eae --- /dev/null +++ b/plugins/kubernetes/src/components/Services/Services.tsx @@ -0,0 +1,62 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import { Grid } from '@material-ui/core'; +import { V1Service } from '@kubernetes/client-node'; +import { InfoCard, StructuredMetadataTable } from '@backstage/core'; + +type ServicesProps = { + services: V1Service[]; + children?: React.ReactNode; +}; + +export const Services = ({ services }: ServicesProps) => { + return ( + + {services.map((s, i) => { + const metadata: any = {}; + + if (s.status?.loadBalancer?.ingress?.length ?? -1 > 0) { + metadata.loadbalancer = s.status?.loadBalancer; + } + + if (s.spec?.type === 'ClusterIP') { + metadata.clusterIP = s.spec.clusterIP; + } + + return ( + + +
+ +
+
+
+ ); + })} +
+ ); +}; diff --git a/plugins/kubernetes/src/components/Services/__fixtures__/services.json b/plugins/kubernetes/src/components/Services/__fixtures__/services.json new file mode 100644 index 0000000000..7f9b49a9f6 --- /dev/null +++ b/plugins/kubernetes/src/components/Services/__fixtures__/services.json @@ -0,0 +1,164 @@ +[ + { + "metadata": { + "annotations": { + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller\",\"namespace\":\"default\"},\"spec\":{\"ports\":[{\"name\":\"port1\",\"port\":80,\"protocol\":\"TCP\",\"targetPort\":9376},{\"name\":\"port2\",\"port\":81,\"protocol\":\"TCP\",\"targetPort\":9377}],\"selector\":{\"app\":\"dice-roller\"}}}\n" + }, + "creationTimestamp": "2020-09-23T12:00:55.000Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:ports": { + ".": {}, + "k:{\"port\":80,\"protocol\":\"TCP\"}": { + ".": {}, + "f:name": {}, + "f:port": {}, + "f:protocol": {}, + "f:targetPort": {} + }, + "k:{\"port\":81,\"protocol\":\"TCP\"}": { + ".": {}, + "f:name": {}, + "f:port": {}, + "f:protocol": {}, + "f:targetPort": {} + } + }, + "f:selector": { + ".": {}, + "f:app": {} + }, + "f:sessionAffinity": {}, + "f:type": {} + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-28T08:50:11.000Z" + } + ], + "name": "dice-roller", + "namespace": "default", + "resourceVersion": "665838", + "selfLink": "/api/v1/namespaces/default/services/dice-roller", + "uid": "ae9aff92-a525-4bc9-82dc-a0537bf8034c" + }, + "spec": { + "clusterIP": "10.102.223.105", + "ports": [ + { + "name": "port1", + "port": 80, + "protocol": "TCP", + "targetPort": 9376 + }, + { + "name": "port2", + "port": 81, + "protocol": "TCP", + "targetPort": 9377 + } + ], + "selector": { + "app": "dice-roller" + }, + "sessionAffinity": "None", + "type": "ClusterIP" + }, + "status": { + "loadBalancer": {} + } + }, + { + "metadata": { + "annotations": { + "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{},\"labels\":{\"backstage.io/kubernetes-id\":\"dice-roller\"},\"name\":\"dice-roller-lb\",\"namespace\":\"default\"},\"spec\":{\"ports\":[{\"port\":8765,\"targetPort\":9376}],\"selector\":{\"app\":\"dice-roller\"},\"type\":\"LoadBalancer\"}}\n" + }, + "creationTimestamp": "2020-09-28T08:51:21.000Z", + "labels": { + "backstage.io/kubernetes-id": "dice-roller" + }, + "managedFields": [ + { + "apiVersion": "v1", + "fieldsType": "FieldsV1", + "fieldsV1": { + "f:metadata": { + "f:annotations": { + ".": {}, + "f:kubectl.kubernetes.io/last-applied-configuration": {} + }, + "f:labels": { + ".": {}, + "f:backstage.io/kubernetes-id": {} + } + }, + "f:spec": { + "f:externalTrafficPolicy": {}, + "f:ports": { + ".": {}, + "k:{\"port\":8765,\"protocol\":\"TCP\"}": { + ".": {}, + "f:port": {}, + "f:protocol": {}, + "f:targetPort": {} + } + }, + "f:selector": { + ".": {}, + "f:app": {} + }, + "f:sessionAffinity": {}, + "f:type": {} + } + }, + "manager": "kubectl", + "operation": "Update", + "time": "2020-09-28T08:51:21.000Z" + } + ], + "name": "dice-roller-lb", + "namespace": "default", + "resourceVersion": "665998", + "selfLink": "/api/v1/namespaces/default/services/dice-roller-lb", + "uid": "5554da3b-2041-4403-8cf4-cd2ccae760f8" + }, + "spec": { + "clusterIP": "10.99.205.233", + "externalTrafficPolicy": "Cluster", + "ports": [ + { + "nodePort": 32276, + "port": 8765, + "protocol": "TCP", + "targetPort": 9378 + } + ], + "selector": { + "app": "dice-roller" + }, + "sessionAffinity": "None", + "type": "LoadBalancer" + }, + "status": { + "loadBalancer": {} + } + } +] diff --git a/plugins/kubernetes/src/components/Services/index.ts b/plugins/kubernetes/src/components/Services/index.ts new file mode 100644 index 0000000000..d52ebf5f14 --- /dev/null +++ b/plugins/kubernetes/src/components/Services/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Services } from './Services'; diff --git a/plugins/kubernetes/src/types/types.ts b/plugins/kubernetes/src/types/types.ts new file mode 100644 index 0000000000..09bff511a7 --- /dev/null +++ b/plugins/kubernetes/src/types/types.ts @@ -0,0 +1,23 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { V1Deployment, V1Pod, V1ReplicaSet } from '@kubernetes/client-node'; + +export interface DeploymentTriple { + pods: V1Pod[]; + replicaSets: V1ReplicaSet[]; + deployments: V1Deployment[]; +} diff --git a/plugins/kubernetes/src/utils.ts b/plugins/kubernetes/src/utils.ts new file mode 100644 index 0000000000..e038b1af8b --- /dev/null +++ b/plugins/kubernetes/src/utils.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Display the value unknown rather than 'undefined' +export function orUnknown(val: T | undefined): T | string { + return val ?? 'unknown'; +} diff --git a/plugins/lighthouse/package.json b/plugins/lighthouse/package.json index 622fec9d0c..6ca1495a05 100644 --- a/plugins/lighthouse/package.json +++ b/plugins/lighthouse/package.json @@ -42,7 +42,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/newrelic/package.json b/plugins/newrelic/package.json index da95e0e580..38a5c437a4 100644 --- a/plugins/newrelic/package.json +++ b/plugins/newrelic/package.json @@ -38,7 +38,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/proxy-backend/src/service/router.test.ts b/plugins/proxy-backend/src/service/router.test.ts index c7d7fff1d4..07737e9ea8 100644 --- a/plugins/proxy-backend/src/service/router.test.ts +++ b/plugins/proxy-backend/src/service/router.test.ts @@ -17,16 +17,20 @@ import { createRouter } from './router'; import * as winston from 'winston'; import { ConfigReader } from '@backstage/config'; -import { loadBackendConfig } from '@backstage/backend-common'; +import { + loadBackendConfig, + SingleHostDiscovery, +} from '@backstage/backend-common'; describe('createRouter', () => { it('works', async () => { const logger = winston.createLogger(); const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const discovery = SingleHostDiscovery.fromConfig(config); const router = await createRouter({ config, logger, - pathPrefix: '/proxy', + discovery, }); expect(router).toBeDefined(); }); diff --git a/plugins/proxy-backend/src/service/router.ts b/plugins/proxy-backend/src/service/router.ts index 7cd5f37598..8cec31719c 100644 --- a/plugins/proxy-backend/src/service/router.ts +++ b/plugins/proxy-backend/src/service/router.ts @@ -23,12 +23,12 @@ import createProxyMiddleware, { } from 'http-proxy-middleware'; import { Logger } from 'winston'; import http from 'http'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; export interface RouterOptions { logger: Logger; config: Config; - // The URL path prefix that the router itself is mounted as, commonly "/proxy" - pathPrefix: string; + discovery: PluginEndpointDiscovery; } export interface ProxyConfig extends ProxyMiddlewareConfig { @@ -76,16 +76,14 @@ export async function createRouter( ): Promise { const router = Router(); + const externalUrl = await options.discovery.getExternalBaseUrl('proxy'); + const { pathname: pathPrefix } = new URL(externalUrl); + const proxyConfig = options.config.getOptional('proxy') ?? {}; Object.entries(proxyConfig).forEach(([route, proxyRouteConfig]) => { router.use( route, - buildMiddleware( - options.pathPrefix, - options.logger, - route, - proxyRouteConfig, - ), + buildMiddleware(pathPrefix, options.logger, route, proxyRouteConfig), ); }); diff --git a/plugins/proxy-backend/src/service/standaloneServer.ts b/plugins/proxy-backend/src/service/standaloneServer.ts index 68e9ade183..83980729d8 100644 --- a/plugins/proxy-backend/src/service/standaloneServer.ts +++ b/plugins/proxy-backend/src/service/standaloneServer.ts @@ -17,6 +17,7 @@ import { createServiceBuilder, loadBackendConfig, + SingleHostDiscovery, } from '@backstage/backend-common'; import { Server } from 'http'; import { Logger } from 'winston'; @@ -37,10 +38,11 @@ export async function startStandaloneServer( logger.debug('Creating application...'); const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const discovery = SingleHostDiscovery.fromConfig(config); const router = await createRouter({ config, logger, - pathPrefix: '/proxy', + discovery, }); const service = createServiceBuilder(module) .enableCors({ origin: 'http://localhost:3000' }) diff --git a/plugins/register-component/package.json b/plugins/register-component/package.json index 5e801b42a9..9e3ef7e307 100644 --- a/plugins/register-component/package.json +++ b/plugins/register-component/package.json @@ -43,7 +43,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx b/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx index 0d90569574..933b67060a 100644 --- a/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx +++ b/plugins/register-component/src/components/RegisterComponentPage/RegisterComponentPage.tsx @@ -86,7 +86,7 @@ export const RegisterComponentPage = ({ const { scmType, componentLocation: target } = formData; try { const typeMapping = [ - { url: /^https:\/\/gitlab\.com\/.*/, type: 'gitlab' }, + { url: /^https:\/\/gitlab\.com\/.*/, type: 'gitlab/api' }, { url: /^https:\/\/bitbucket\.org\/.*/, type: 'bitbucket/api' }, { url: /^https:\/\/dev\.azure\.com\/.*/, type: 'azure/api' }, { url: /.*/, type: 'github' }, diff --git a/plugins/rollbar/package.json b/plugins/rollbar/package.json index ef386e50ea..18f13c3969 100644 --- a/plugins/rollbar/package.json +++ b/plugins/rollbar/package.json @@ -47,7 +47,9 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/react": "^16.9", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/scaffolder-backend/package.json b/plugins/scaffolder-backend/package.json index 90d1af4b5f..7a7938a483 100644 --- a/plugins/scaffolder-backend/package.json +++ b/plugins/scaffolder-backend/package.json @@ -28,6 +28,7 @@ "@octokit/rest": "^18.0.0", "@types/dockerode": "^2.5.32", "@types/express": "^4.17.6", + "azure-devops-node-api": "^10.1.1", "command-exists-promise": "^2.0.2", "compression": "^1.7.4", "cors": "^2.8.5", diff --git a/plugins/scaffolder-backend/sample-templates/react-ssr-template/{{cookiecutter.component_id}}/.github/workflows/build.yml b/plugins/scaffolder-backend/sample-templates/react-ssr-template/{{cookiecutter.component_id}}/.github/workflows/build.yml index 33dd3436d5..907da7e820 100644 --- a/plugins/scaffolder-backend/sample-templates/react-ssr-template/{{cookiecutter.component_id}}/.github/workflows/build.yml +++ b/plugins/scaffolder-backend/sample-templates/react-ssr-template/{{cookiecutter.component_id}}/.github/workflows/build.yml @@ -35,7 +35,7 @@ jobs: working-directory: . run: | yarn install - yarn build --if-present + yarn build yarn test env: CI: true diff --git a/plugins/scaffolder-backend/scripts/README.md b/plugins/scaffolder-backend/scripts/README.md new file mode 100644 index 0000000000..20d68e9c34 --- /dev/null +++ b/plugins/scaffolder-backend/scripts/README.md @@ -0,0 +1,4 @@ +The `Cookiecutter.dockerfile` is published to the +[`spotify/backstage-cookiecutter`](https://hub.docker.com/repository/docker/spotify/backstage-cookiecutter) +repository on DockerHub. This is handled by an integration between DockerHub and GitHub. +The integration handles updating the container image when a new release is made. diff --git a/plugins/scaffolder-backend/src/scaffolder/__mocks__/azure-devops-node-api/GitApi/index.ts b/plugins/scaffolder-backend/src/scaffolder/__mocks__/azure-devops-node-api/GitApi/index.ts new file mode 100644 index 0000000000..116f092866 --- /dev/null +++ b/plugins/scaffolder-backend/src/scaffolder/__mocks__/azure-devops-node-api/GitApi/index.ts @@ -0,0 +1,25 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const mockGitApi = { + createRepository: jest.fn(), +}; + +export class GitApi { + constructor() { + return mockGitApi; + } +} diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts new file mode 100644 index 0000000000..7a7973e981 --- /dev/null +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.test.ts @@ -0,0 +1,138 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const mocks = { + Clone: { clone: jest.fn() }, + CheckoutOptions: jest.fn(() => {}), +}; +jest.doMock('nodegit', () => mocks); + +import { AzurePreparer } from './azure'; +import { + TemplateEntityV1alpha1, + LOCATION_ANNOTATION, +} from '@backstage/catalog-model'; +import { ConfigReader } from '@backstage/config'; + +describe('AzurePreparer', () => { + let mockEntity: TemplateEntityV1alpha1; + beforeEach(() => { + jest.clearAllMocks(); + mockEntity = { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Template', + metadata: { + annotations: { + [LOCATION_ANNOTATION]: + 'azure/api:https://dev.azure.com/backstage-org/backstage-project/_git/template-repo?path=%2Ftemplate.yaml', + }, + name: 'graphql-starter', + title: 'GraphQL Service', + description: + 'A GraphQL starter template for backstage to get you up and running\nthe best pracices with GraphQL\n', + uid: '9cf16bad-16e0-4213-b314-c4eec773c50b', + etag: 'ZTkxMjUxMjUtYWY3Yi00MjU2LWFkYWMtZTZjNjU5ZjJhOWM2', + generation: 1, + }, + spec: { + type: 'website', + templater: 'cookiecutter', + path: './template', + schema: { + $schema: 'http://json-schema.org/draft-07/schema#', + required: ['storePath', 'owner'], + properties: { + owner: { + type: 'string', + title: 'Owner', + description: 'Who is going to own this component', + }, + storePath: { + type: 'string', + title: 'Store path', + description: 'GitHub store path in org/repo format', + }, + }, + }, + }, + }; + }); + + it('calls the clone command with the correct arguments for a repository', async () => { + const preparer = new AzurePreparer(ConfigReader.fromConfigs([])); + await preparer.prepare(mockEntity); + expect(mocks.Clone.clone).toHaveBeenNthCalledWith( + 1, + 'https://dev.azure.com/backstage-org/backstage-project/_git/template-repo', + expect.any(String), + {}, + ); + }); + + it('calls the clone command with the correct arguments if an access token is provided for a repository', async () => { + const preparer = new AzurePreparer( + ConfigReader.fromConfigs([ + { + context: '', + data: { + scaffolder: { + azure: { + api: { + token: 'fake-token', + }, + }, + }, + }, + }, + ]), + ); + await preparer.prepare(mockEntity); + expect(mocks.Clone.clone).toHaveBeenNthCalledWith( + 1, + 'https://dev.azure.com/backstage-org/backstage-project/_git/template-repo', + expect.any(String), + { + fetchOpts: { + callbacks: { + credentials: expect.anything(), + }, + }, + }, + ); + }); + + it('calls the clone command with the correct arguments for a repository when no path is provided', async () => { + const preparer = new AzurePreparer(ConfigReader.fromConfigs([])); + delete mockEntity.spec.path; + await preparer.prepare(mockEntity); + expect(mocks.Clone.clone).toHaveBeenNthCalledWith( + 1, + 'https://dev.azure.com/backstage-org/backstage-project/_git/template-repo', + expect.any(String), + {}, + ); + }); + + it('return the temp directory with the path to the folder if it is specified', async () => { + const preparer = new AzurePreparer(ConfigReader.fromConfigs([])); + mockEntity.spec.path = './template/test/1/2/3'; + const response = await preparer.prepare(mockEntity); + + expect(response.split('\\').join('/')).toMatch( + /\/template\/test\/1\/2\/3$/, + ); + }); +}); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts new file mode 100644 index 0000000000..c2cb97e505 --- /dev/null +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/azure.ts @@ -0,0 +1,76 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import fs from 'fs-extra'; +import path from 'path'; +import os from 'os'; +import { TemplateEntityV1alpha1 } from '@backstage/catalog-model'; +import { parseLocationAnnotation } from '../helpers'; +import { InputError } from '@backstage/backend-common'; +import { PreparerBase } from './types'; +import GitUriParser from 'git-url-parse'; +import { Clone, Cred } from 'nodegit'; +import { Config } from '@backstage/config'; + +export class AzurePreparer implements PreparerBase { + private readonly privateToken: string; + + constructor(config: Config) { + this.privateToken = + config.getOptionalString('scaffolder.azure.api.token') ?? ''; + } + + async prepare(template: TemplateEntityV1alpha1): Promise { + const { protocol, location } = parseLocationAnnotation(template); + + if (protocol !== 'azure/api') { + throw new InputError( + `Wrong location protocol: ${protocol}, should be 'azure/api'`, + ); + } + const templateId = template.metadata.name; + + const url = new URL(location); // Need to extract filepath from search parameter + const parsedGitLocation = GitUriParser(location); + const repositoryCheckoutUrl = parsedGitLocation.toString('https'); + + const tempDir = await fs.promises.mkdtemp( + path.join(os.tmpdir(), templateId), + ); + + const templateDirectory = path.join( + `${path + .dirname(url.searchParams.get('path') || '') + .replace(/^\/+/g, '')}`, // Strip leading slash + template.spec.path ?? '.', + ); + + const options = this.privateToken + ? { + fetchOpts: { + callbacks: { + credentials: () => + // Username can anything but the empty string according to: https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=preview-page#use-a-pat + Cred.userpassPlaintextNew('notempty', this.privateToken), + }, + }, + } + : {}; + + await Clone.clone(repositoryCheckoutUrl, tempDir, options); + + return path.resolve(tempDir, templateDirectory); + } +} diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/index.ts b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/index.ts index 80a7dc620d..f7bc535189 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/prepare/index.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/prepare/index.ts @@ -18,3 +18,4 @@ export * from './types'; export * from './file'; export * from './github'; export * from './gitlab'; +export * from './azure'; diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/publish/azure.test.ts b/plugins/scaffolder-backend/src/scaffolder/stages/publish/azure.test.ts new file mode 100644 index 0000000000..8b84eb0edf --- /dev/null +++ b/plugins/scaffolder-backend/src/scaffolder/stages/publish/azure.test.ts @@ -0,0 +1,179 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +jest.mock('nodegit'); +jest.mock('azure-devops-node-api/GitApi'); +jest.mock('azure-devops-node-api/interfaces/GitInterfaces'); + +import { AzurePublisher } from './azure'; +import { GitApi } from 'azure-devops-node-api/GitApi'; +import * as NodeGit from 'nodegit'; + +const { mockGitApi } = require('azure-devops-node-api/GitApi') as { + mockGitApi: { + createRepository: jest.MockedFunction; + }; +}; + +const { + Repository, + mockRepo, + mockIndex, + Signature, + Remote, + mockRemote, + Cred, +} = require('nodegit') as { + Repository: jest.Mocked<{ init: any }>; + Signature: jest.Mocked<{ now: any }>; + Cred: jest.Mocked<{ userpassPlaintextNew: any }>; + Remote: jest.Mocked<{ create: any }>; + + mockIndex: jest.Mocked; + mockRepo: jest.Mocked; + mockRemote: jest.Mocked; +}; + +describe('Azure Publisher', () => { + const publisher = new AzurePublisher(new GitApi('', []), 'fake-token'); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('publish: createRemoteInAzure', () => { + it('should use azure-devops-node-api to create a repo in the given project', async () => { + mockGitApi.createRepository.mockResolvedValue({ + remoteUrl: 'mockclone', + } as { remoteUrl: string }); + + await publisher.publish({ + values: { + storePath: 'project/repo', + owner: 'bob', + }, + directory: '/tmp/test', + }); + + expect(mockGitApi.createRepository).toHaveBeenCalledWith( + { + name: 'repo', + }, + 'project', + ); + }); + }); + + describe('publish: createGitDirectory', () => { + const values = { + isOrg: true, + storePath: 'blam/test', + owner: 'lols', + }; + + const mockDir = '/tmp/test/dir'; + + mockGitApi.createRepository.mockResolvedValue({ + remoteUrl: 'mockclone', + } as { remoteUrl: string }); + + it('should call init on the repo with the directory', async () => { + await publisher.publish({ + values, + directory: mockDir, + }); + + expect(Repository.init).toHaveBeenCalledWith(mockDir, 0); + }); + + it('should call refresh index on the index and write the new files', async () => { + await publisher.publish({ + values, + directory: mockDir, + }); + + expect(mockRepo.refreshIndex).toHaveBeenCalled(); + }); + + it('should call add all files and write', async () => { + await publisher.publish({ + values, + directory: mockDir, + }); + + expect(mockIndex.addAll).toHaveBeenCalled(); + expect(mockIndex.write).toHaveBeenCalled(); + expect(mockIndex.writeTree).toHaveBeenCalled(); + }); + + it('should create a commit with on head with the right name and commiter', async () => { + const mockSignature = { mockSignature: 'bloblly' }; + Signature.now.mockReturnValue(mockSignature); + + await publisher.publish({ + values, + directory: mockDir, + }); + + expect(Signature.now).toHaveBeenCalledTimes(2); + expect(Signature.now).toHaveBeenCalledWith( + 'Scaffolder', + 'scaffolder@backstage.io', + ); + + expect(mockRepo.createCommit).toHaveBeenCalledWith( + 'HEAD', + mockSignature, + mockSignature, + 'initial commit', + 'mockoid', + [], + ); + }); + + it('creates a remote with the repo and remote', async () => { + await publisher.publish({ + values, + directory: mockDir, + }); + + expect(Remote.create).toHaveBeenCalledWith( + mockRepo, + 'origin', + 'mockclone', + ); + }); + + it('shoud push to the remote repo', async () => { + await publisher.publish({ + values, + directory: mockDir, + }); + + const [remotes, { callbacks }] = mockRemote.push.mock + .calls[0] as NodeGit.PushOptions[]; + + expect(remotes).toEqual(['refs/heads/master:refs/heads/master']); + + callbacks?.credentials?.(); + + expect(Cred.userpassPlaintextNew).toHaveBeenCalledWith( + 'notempty', + 'fake-token', + ); + }); + }); +}); diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/publish/azure.ts b/plugins/scaffolder-backend/src/scaffolder/stages/publish/azure.ts new file mode 100644 index 0000000000..9dfc7b5b66 --- /dev/null +++ b/plugins/scaffolder-backend/src/scaffolder/stages/publish/azure.ts @@ -0,0 +1,82 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { PublisherBase } from './types'; +import { GitApi } from 'azure-devops-node-api/GitApi'; +import { GitRepositoryCreateOptions } from 'azure-devops-node-api/interfaces/GitInterfaces'; + +import { JsonValue } from '@backstage/config'; +import { RequiredTemplateValues } from '../templater'; +import { Repository, Remote, Signature, Cred } from 'nodegit'; + +export class AzurePublisher implements PublisherBase { + private readonly client: GitApi; + private readonly token: string; + + constructor(client: GitApi, token: string) { + this.client = client; + this.token = token; + } + + async publish({ + values, + directory, + }: { + values: RequiredTemplateValues & Record; + directory: string; + }): Promise<{ remoteUrl: string }> { + const remoteUrl = await this.createRemote(values); + await this.pushToRemote(directory, remoteUrl); + + return { remoteUrl }; + } + + private async createRemote( + values: RequiredTemplateValues & Record, + ) { + const [project, name] = values.storePath.split('/'); + + const createOptions: GitRepositoryCreateOptions = { name }; + const repo = await this.client.createRepository(createOptions, project); + + return repo.remoteUrl || ''; + } + + private async pushToRemote(directory: string, remote: string): Promise { + const repo = await Repository.init(directory, 0); + const index = await repo.refreshIndex(); + await index.addAll(); + await index.write(); + const oid = await index.writeTree(); + await repo.createCommit( + 'HEAD', + Signature.now('Scaffolder', 'scaffolder@backstage.io'), + Signature.now('Scaffolder', 'scaffolder@backstage.io'), + 'initial commit', + oid, + [], + ); + + const remoteRepo = await Remote.create(repo, 'origin', remote); + + await remoteRepo.push(['refs/heads/master:refs/heads/master'], { + callbacks: { + // Username can anything but the empty string according to: https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=preview-page#use-a-pat + credentials: () => Cred.userpassPlaintextNew('notempty', this.token), + }, + }); + } +} diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/publish/index.ts b/plugins/scaffolder-backend/src/scaffolder/stages/publish/index.ts index 1d89cd37f0..b37baa3246 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/publish/index.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/publish/index.ts @@ -16,4 +16,5 @@ export * from './publishers'; export * from './github'; export * from './gitlab'; +export * from './azure'; export * from './types'; diff --git a/plugins/scaffolder-backend/src/scaffolder/stages/types.ts b/plugins/scaffolder-backend/src/scaffolder/stages/types.ts index 13817ba190..938d906857 100644 --- a/plugins/scaffolder-backend/src/scaffolder/stages/types.ts +++ b/plugins/scaffolder-backend/src/scaffolder/stages/types.ts @@ -13,4 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -export type RemoteProtocol = 'file' | 'github' | 'gitlab' | 'gitlab/api'; +export type RemoteProtocol = + | 'file' + | 'github' + | 'gitlab' + | 'gitlab/api' + | 'azure/api'; diff --git a/plugins/scaffolder/package.json b/plugins/scaffolder/package.json index 26cf58c040..2abd3feb8f 100644 --- a/plugins/scaffolder/package.json +++ b/plugins/scaffolder/package.json @@ -49,7 +49,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/scaffolder/src/components/JobStatusModal/JobStatusModal.tsx b/plugins/scaffolder/src/components/JobStatusModal/JobStatusModal.tsx index 87b70a9553..c531e0ec2c 100644 --- a/plugins/scaffolder/src/components/JobStatusModal/JobStatusModal.tsx +++ b/plugins/scaffolder/src/components/JobStatusModal/JobStatusModal.tsx @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import React, { useEffect } from 'react'; +import React, { useState, useEffect } from 'react'; import { Dialog, LinearProgress, @@ -43,16 +43,19 @@ export const JobStatusModal = ({ entity, }: Props) => { const job = useJobPolling(jobId); + const [dialogTitle, setDialogTitle] = useState('Creating component...'); useEffect(() => { - if (job?.status === 'COMPLETED') onComplete(job); - }, [job, onComplete]); + if (job?.status === 'COMPLETED') { + setDialogTitle('Successfully created component'); + onComplete(job); + } else if (job?.status === 'FAILED') + setDialogTitle('Failed to create component'); + }, [job, onComplete, setDialogTitle]); return ( - - Creating Component... - + {dialogTitle} {!job ? ( diff --git a/plugins/sentry/package.json b/plugins/sentry/package.json index bddeff243c..143a2dfc12 100644 --- a/plugins/sentry/package.json +++ b/plugins/sentry/package.json @@ -43,7 +43,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/tech-radar/package.json b/plugins/tech-radar/package.json index 7b0bf4eb3a..c9950cdc95 100644 --- a/plugins/tech-radar/package.json +++ b/plugins/tech-radar/package.json @@ -45,7 +45,9 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "@types/react": "^16.9", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/techdocs-backend/README.md b/plugins/techdocs-backend/README.md index 2185c3b3e4..b7eca2c5cb 100644 --- a/plugins/techdocs-backend/README.md +++ b/plugins/techdocs-backend/README.md @@ -18,11 +18,11 @@ yarn start ## What techdocs-backend does -This plugin is the backend part of the techdocs plugin. It provides building and serving of your docs without having to use another service and hosting provider. To use it set your techdocs storageUrl in your `app-config.yml` to `http://localhost:7000/techdocs/static/docs`. +This plugin is the backend part of the techdocs plugin. It provides building and serving of your docs without having to use another service and hosting provider. To use it set your techdocs storageUrl in your `app-config.yml` to `http://localhost:7000/api/techdocs/static/docs`. ```yaml techdocs: - storageUrl: http://localhost:7000/techdocs/static/docs + storageUrl: http://localhost:7000/api/techdocs/static/docs ``` ## Extending techdocs-backend diff --git a/plugins/techdocs-backend/src/default-branch.ts b/plugins/techdocs-backend/src/default-branch.ts new file mode 100644 index 0000000000..05a8f666ce --- /dev/null +++ b/plugins/techdocs-backend/src/default-branch.ts @@ -0,0 +1,187 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import fetch, { RequestInit } from 'node-fetch'; +import parseGitUrl from 'git-url-parse'; +import { ConfigReader, Config } from '@backstage/config'; +import { loadBackendConfig } from '@backstage/backend-common'; + +interface IGitlabBranch { + name: string; + merged: boolean; + protected: boolean; + default: boolean; + developers_can_push: boolean; + developers_can_merge: boolean; + can_push: boolean; + web_url: string; + commit: { + author_email: string; + author_name: string; + authored_date: string; + committed_date: string; + committer_email: string; + committer_name: string; + id: string; + short_id: string; + title: string; + message: string; + parent_ids: string[]; + }; +} + +function getGithubApiUrl(url: string): URL { + const { protocol, owner, name } = parseGitUrl(url); + const apiBaseUrl = 'api.github.com'; + const apiRepos = 'repos'; + + return new URL(`${protocol}://${apiBaseUrl}/${apiRepos}/${owner}/${name}`); +} + +function getGitlabApiUrl(url: string): URL { + const { protocol, resource, full_name: fullName } = parseGitUrl(url); + const apiProjectsBasePath = 'api/v4/projects'; + const project = encodeURIComponent(fullName); + const branches = 'repository/branches'; + + return new URL( + `${protocol}://${resource}/${apiProjectsBasePath}/${project}/${branches}`, + ); +} + +function getGithubRequestOptions(config: Config): RequestInit { + const headers: HeadersInit = { + Accept: 'application/vnd.github.v3.raw', + }; + + const token = + config.getOptionalString('catalog.processors.github.privateToken') ?? + config.getOptionalString('catalog.processors.githubApi.privateToken') ?? + process.env.GITHUB_PRIVATE_TOKEN; + + if (token) { + headers.Authorization = `token ${token}`; + } + + return { + headers, + }; +} + +function getGitlabRequestOptions(config: Config): RequestInit { + const headers: HeadersInit = { + 'PRIVATE-TOKEN': '', + }; + + const token = + config.getOptionalString('catalog.processors.gitlab.privateToken') ?? + config.getOptionalString('catalog.processors.gitlabApi.privateToken') ?? + process.env.GITLAB_ACCESS_TOKEN; + + if (token) { + headers['PRIVATE-TOKEN'] = token; + } + + return { + headers, + }; +} + +async function getGithubDefaultBranch( + repositoryUrl: string, + config: Config, +): Promise { + const path = getGithubApiUrl(repositoryUrl).toString(); + const options = getGithubRequestOptions(config); + + try { + const raw = await fetch(path, options); + + if (!raw.ok) { + throw new Error( + `Failed to load url: ${raw.status} ${raw.statusText}. Make sure you have permission to repository: ${repositoryUrl}`, + ); + } + + const { default_branch: branch } = await raw.json(); + + if (!branch) { + throw new Error('Not found github default branch'); + } + + return branch; + } catch (error) { + throw new Error(`Failed to get github default branch: ${error}`); + } +} + +async function getGitlabDefaultBranch( + repositoryUrl: string, + config: Config, +): Promise { + const path = getGitlabApiUrl(repositoryUrl).toString(); + + const options = getGitlabRequestOptions(config); + + try { + const raw = await fetch(path, options); + + if (!raw.ok) { + throw new Error( + `Failed to load url: ${raw.status} ${raw.statusText}. Make sure you have permission to repository: ${repositoryUrl}`, + ); + } + + const result = await raw.json(); + const { name } = (result || []).find( + (branch: IGitlabBranch) => branch.default === true, + ); + + if (!name) { + throw new Error('Not found gitlab default branch'); + } + + return name; + } catch (error) { + throw new Error(`Failed to get gitlab default branch: ${error}`); + } +} + +export const getDefaultBranch = async ( + repositoryUrl: string, +): Promise => { + const config = ConfigReader.fromConfigs(await loadBackendConfig()); + const typeMapping = [ + { url: /github*/g, type: 'github' }, + { url: /gitlab*/g, type: 'gitlab' }, + ]; + + const type = typeMapping.filter(item => item.url.test(repositoryUrl))[0] + ?.type; + + try { + switch (type) { + case 'github': + return await getGithubDefaultBranch(repositoryUrl, config); + case 'gitlab': + return await getGitlabDefaultBranch(repositoryUrl, config); + + default: + throw new Error('Failed to get repository type'); + } + } catch (error) { + throw error; + } +}; diff --git a/plugins/techdocs-backend/src/helpers.ts b/plugins/techdocs-backend/src/helpers.ts index 8acd836cad..d6a275f183 100644 --- a/plugins/techdocs-backend/src/helpers.ts +++ b/plugins/techdocs-backend/src/helpers.ts @@ -19,8 +19,7 @@ import path from 'path'; import parseGitUrl from 'git-url-parse'; import NodeGit, { Clone, Repository } from 'nodegit'; import fs from 'fs-extra'; -// @ts-ignore -import defaultBranch from 'default-branch'; +import { getDefaultBranch } from './default-branch'; import { Entity } from '@backstage/catalog-model'; import { InputError } from '@backstage/backend-common'; import { RemoteProtocol } from './techdocs/stages/prepare/types'; @@ -76,6 +75,7 @@ export const getLocationForEntity = ( switch (type) { case 'github': + case 'gitlab': return { type, target }; case 'dir': if (path.isAbsolute(target)) return { type, target }; @@ -89,7 +89,7 @@ export const getLocationForEntity = ( } }; -export const getGitHubRepositoryTempFolder = async ( +export const getGitRepositoryTempFolder = async ( repositoryUrl: string, ): Promise => { const parsedGitLocation = parseGitUrl(repositoryUrl); @@ -97,7 +97,7 @@ export const getGitHubRepositoryTempFolder = async ( parsedGitLocation.git_suffix = false; if (!parsedGitLocation.ref) { - parsedGitLocation.ref = await defaultBranch( + parsedGitLocation.ref = await getDefaultBranch( parsedGitLocation.toString('https'), ); } @@ -113,16 +113,22 @@ export const getGitHubRepositoryTempFolder = async ( ); }; -export const checkoutGithubRepository = async ( +export const checkoutGitRepository = async ( repoUrl: string, logger: Logger, ): Promise => { const parsedGitLocation = parseGitUrl(repoUrl); - const repositoryTmpPath = await getGitHubRepositoryTempFolder(repoUrl); + const repositoryTmpPath = await getGitRepositoryTempFolder(repoUrl); // TODO: Should propably not be hardcoded names of env variables, but seems too hard to access config down here - const user = process.env.GITHUB_PRIVATE_TOKEN_USER || ''; - const token = process.env.GITHUB_PRIVATE_TOKEN || ''; + const user = + process.env.GITHUB_PRIVATE_TOKEN_USER || + process.env.GITLAB_PRIVATE_TOKEN_USER || + ''; + const token = + process.env.GITHUB_PRIVATE_TOKEN || + process.env.GITLAB_PRIVATE_TOKEN_USER || + ''; if (fs.existsSync(repositoryTmpPath)) { try { @@ -160,10 +166,7 @@ export const getLastCommitTimestamp = async ( repositoryUrl: string, logger: Logger, ): Promise => { - const repositoryLocation = await checkoutGithubRepository( - repositoryUrl, - logger, - ); + const repositoryLocation = await checkoutGitRepository(repositoryUrl, logger); const repository = await Repository.open(repositoryLocation); const commit = await repository.getReferenceCommit('HEAD'); diff --git a/plugins/techdocs-backend/src/service/helpers.ts b/plugins/techdocs-backend/src/service/helpers.ts index 60c76e6384..1b8e130ec0 100644 --- a/plugins/techdocs-backend/src/service/helpers.ts +++ b/plugins/techdocs-backend/src/service/helpers.ts @@ -108,8 +108,9 @@ export class DocsBuilder { ); const { type, target } = getLocationForEntity(this.entity); - // Should probably be broken out and handled per type later. Doing this for now since we only support github age checks - if (type === 'github') { + // Unless docs are stored locally + const nonAgeCheckTypes = ['dir', 'file']; + if (!nonAgeCheckTypes.includes(type)) { const lastCommit = await getLastCommitTimestamp(target, this.logger); const storageTimeStamp = buildMetadataStorage.getTimestamp(); diff --git a/plugins/techdocs-backend/src/service/metadata.ts b/plugins/techdocs-backend/src/service/metadata.ts new file mode 100644 index 0000000000..671fcdda17 --- /dev/null +++ b/plugins/techdocs-backend/src/service/metadata.ts @@ -0,0 +1,40 @@ +import fetch from 'node-fetch'; +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export class TechDocsMetadata { + private async getMetadataFile(docsUrl: String) { + const metadataURL = `${docsUrl}/techdocs_metadata.json`; + + try { + const req = await fetch(metadataURL); + + return await req.json(); + } catch (error) { + throw new Error(error); + } + } + + public async getMkDocsMetaData(docsUrl: any) { + const mkDocsMetadata = await this.getMetadataFile(docsUrl); + + if (!mkDocsMetadata) return null; + + return { + ...mkDocsMetadata, + }; + } +} diff --git a/plugins/techdocs-backend/src/service/router.ts b/plugins/techdocs-backend/src/service/router.ts index e0a066c168..365534b9d0 100644 --- a/plugins/techdocs-backend/src/service/router.ts +++ b/plugins/techdocs-backend/src/service/router.ts @@ -26,15 +26,20 @@ import { PublisherBase, LocalPublish, } from '../techdocs'; -import { resolvePackagePath } from '@backstage/backend-common'; +import { + PluginEndpointDiscovery, + resolvePackagePath, +} from '@backstage/backend-common'; import { Entity } from '@backstage/catalog-model'; import { DocsBuilder } from './helpers'; +import { getLocationForEntity } from '../helpers'; type RouterOptions = { preparers: PreparerBuilder; generators: GeneratorBuilder; publisher: PublisherBase; logger: Logger; + discovery: PluginEndpointDiscovery; database?: Knex; // TODO: Make database required when we're implementing database stuff. config: Config; dockerClient: Docker; @@ -52,20 +57,65 @@ export async function createRouter({ config, dockerClient, logger, + discovery, }: RouterOptions): Promise { const router = Router(); - router.get('/docs/:kind/:namespace/:name/*', async (req, res) => { + router.get('/metadata/mkdocs/*', async (req, res) => { + const storageUrl = config.getString('techdocs.storageUrl'); + const { '0': path } = req.params; + + const metadataURL = `${storageUrl}/${path}/techdocs_metadata.json`; + + try { + const mkDocsMetadata = await (await fetch(metadataURL)).json(); + res.send(mkDocsMetadata); + } catch (err) { + logger.info( + `[TechDocs] Unable to get metadata for ${path} with error ${err}`, + ); + throw new Error(`Unable to get metadata for ${path} with error ${err}`); + } + }); + + router.get('/metadata/entity/:kind/:namespace/:name', async (req, res) => { const baseUrl = config.getString('backend.baseUrl'); + const { kind, namespace, name } = req.params; + + try { + const entity = (await ( + await fetch( + `${baseUrl}/api/catalog/entities/by-name/${kind}/${namespace}/${name}`, + ) + ).json()) as Entity; + + const locationMetadata = getLocationForEntity(entity); + res.send({ ...entity, locationMetadata }); + } catch (err) { + logger.info( + `[TechDocs] Unable to get metadata for ${kind}/${namespace}/${name} with error ${err}`, + ); + throw new Error( + `Unable to get metadata for ${kind}/${namespace}/${name} with error ${err}`, + ); + } + }); + + router.get('/docs/:kind/:namespace/:name/*', async (req, res) => { const storageUrl = config.getString('techdocs.storageUrl'); const { kind, namespace, name } = req.params; - const entity = (await ( - await fetch( - `${baseUrl}/catalog/entities/by-name/${kind}/${namespace}/${name}`, - ) - ).json()) as Entity; + const catalogUrl = await discovery.getBaseUrl('catalog'); + const triple = [kind, namespace, name].map(encodeURIComponent).join('/'); + + const catalogRes = await fetch(`${catalogUrl}/entities/by-name/${triple}`); + if (!catalogRes.ok) { + catalogRes.body.pipe(res.status(catalogRes.status)); + return; + } + + const entity: Entity = await catalogRes.json(); const docsBuilder = new DocsBuilder({ preparers, @@ -80,7 +130,7 @@ export async function createRouter({ await docsBuilder.build(); } - return res.redirect(`${storageUrl}${req.path.replace('/docs', '')}`); + res.redirect(`${storageUrl}${req.path.replace('/docs', '')}`); }); if (publisher instanceof LocalPublish) { diff --git a/plugins/techdocs-backend/src/service/standaloneServer.ts b/plugins/techdocs-backend/src/service/standaloneServer.ts index 7a39742b80..79e8b0b945 100644 --- a/plugins/techdocs-backend/src/service/standaloneServer.ts +++ b/plugins/techdocs-backend/src/service/standaloneServer.ts @@ -14,7 +14,10 @@ * limitations under the License. */ -import { createServiceBuilder } from '@backstage/backend-common'; +import { + createServiceBuilder, + SingleHostDiscovery, +} from '@backstage/backend-common'; import { Server } from 'http'; import { Logger } from 'winston'; import { createRouter } from './router'; @@ -39,6 +42,7 @@ export async function startStandaloneServer( ): Promise { const logger = options.logger.child({ service: 'techdocs-backend' }); const config = ConfigReader.fromConfigs([]); + const discovery = SingleHostDiscovery.fromConfig(config); logger.debug('Creating application...'); const preparers = new Preparers(); @@ -61,6 +65,7 @@ export async function startStandaloneServer( publisher, dockerClient, config, + discovery, }); const service = createServiceBuilder(module) .enableCors({ origin: 'http://localhost:3000' }) diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.test.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.test.ts index e2b94d7e88..4412e6bf73 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.test.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.test.ts @@ -15,7 +15,7 @@ */ import { DirectoryPreparer } from './dir'; import { getVoidLogger } from '@backstage/backend-common'; -import { checkoutGithubRepository } from '../../../helpers'; +import { checkoutGitRepository } from '../../../helpers'; function normalizePath(path: string) { return path @@ -26,9 +26,7 @@ function normalizePath(path: string) { jest.mock('../../../helpers', () => ({ ...jest.requireActual<{}>('../../../helpers'), - checkoutGithubRepository: jest.fn( - () => '/tmp/backstage-repo/org/name/branch/', - ), + checkoutGitRepository: jest.fn(() => '/tmp/backstage-repo/org/name/branch/'), })); const logger = getVoidLogger(); @@ -87,6 +85,6 @@ describe('directory preparer', () => { expect(normalizePath(await directoryPreparer.prepare(mockEntity))).toEqual( '/tmp/backstage-repo/org/name/branch/docs', ); - expect(checkoutGithubRepository).toHaveBeenCalledTimes(1); + expect(checkoutGitRepository).toHaveBeenCalledTimes(1); }); }); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts index 5fd4abb4bd..cad8a7effa 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/dir.ts @@ -18,7 +18,7 @@ import { Entity } from '@backstage/catalog-model'; import path from 'path'; import { parseReferenceAnnotation, - checkoutGithubRepository, + checkoutGitRepository, } from '../../../helpers'; import { InputError } from '@backstage/backend-common'; import parseGitUrl from 'git-url-parse'; @@ -41,17 +41,16 @@ export class DirectoryPreparer implements PreparerBase { `[TechDocs] Building docs for entity with type 'dir' and managed-by-location '${type}'`, ); switch (type) { - case 'github': { + case 'github': + case 'gitlab': { const parsedGitLocation = parseGitUrl(target); - const repoLocation = await checkoutGithubRepository( - target, - this.logger, - ); + const repoLocation = await checkoutGitRepository(target, this.logger); return path.dirname( path.join(repoLocation, parsedGitLocation.filepath), ); } + case 'file': return path.dirname(target); default: diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts index a188e1c986..a657cd1697 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/github.test.ts @@ -16,7 +16,7 @@ import { getVoidLogger } from '@backstage/backend-common'; import { GithubPreparer } from './github'; -import { checkoutGithubRepository } from '../../../helpers'; +import { checkoutGitRepository } from '../../../helpers'; function normalizePath(path: string) { return path @@ -27,9 +27,7 @@ function normalizePath(path: string) { jest.mock('../../../helpers', () => ({ ...jest.requireActual<{}>('../../../helpers'), - checkoutGithubRepository: jest.fn( - () => '/tmp/backstage-repo/org/name/branch', - ), + checkoutGitRepository: jest.fn(() => '/tmp/backstage-repo/org/name/branch'), })); const createMockEntity = (annotations = {}) => { @@ -57,7 +55,7 @@ describe('github preparer', () => { }); const tempDocsPath = await preparer.prepare(mockEntity); - expect(checkoutGithubRepository).toHaveBeenCalledTimes(1); + expect(checkoutGitRepository).toHaveBeenCalledTimes(1); expect(normalizePath(tempDocsPath)).toEqual( '/tmp/backstage-repo/org/name/branch/plugins/techdocs-backend/examples/documented-component', ); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts index 03b0adcb88..a0f91a375a 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/github.ts @@ -20,7 +20,7 @@ import { PreparerBase } from './types'; import parseGitUrl from 'git-url-parse'; import { parseReferenceAnnotation, - checkoutGithubRepository, + checkoutGitRepository, } from '../../../helpers'; import { Logger } from 'winston'; @@ -43,7 +43,7 @@ export class GithubPreparer implements PreparerBase { } try { - const repoPath = await checkoutGithubRepository(target, this.logger); + const repoPath = await checkoutGitRepository(target, this.logger); const parsedGitLocation = parseGitUrl(target); return path.join(repoPath, parsedGitLocation.filepath); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.test.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.test.ts new file mode 100644 index 0000000000..75cad50224 --- /dev/null +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.test.ts @@ -0,0 +1,64 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getVoidLogger } from '@backstage/backend-common'; +import { GitlabPreparer } from './gitlab'; +import { checkoutGitRepository } from '../../../helpers'; + +function normalizePath(path: string) { + return path + .replace(/^[a-z]:/i, '') + .split('\\') + .join('/'); +} + +jest.mock('../../../helpers', () => ({ + ...jest.requireActual<{}>('../../../helpers'), + checkoutGitRepository: jest.fn(() => '/tmp/backstage-repo/org/name/branch'), +})); + +const createMockEntity = (annotations = {}) => { + return { + apiVersion: 'version', + kind: 'TestKind', + metadata: { + name: 'test-component-name', + annotations: { + ...annotations, + }, + }, + }; +}; + +const logger = getVoidLogger(); + +describe('gitlab preparer', () => { + it('should prepare temp docs path from gitlab repo', async () => { + const preparer = new GitlabPreparer(logger); + + // TODO: fix url repo + const mockEntity = createMockEntity({ + 'backstage.io/techdocs-ref': + 'gitlab:https://gitlab.com/xesjkeee/go-logger/blob/master/catalog-info.yaml', + }); + + const tempDocsPath = await preparer.prepare(mockEntity); + expect(checkoutGitRepository).toHaveBeenCalledTimes(1); + expect(normalizePath(tempDocsPath)).toEqual( + '/tmp/backstage-repo/org/name/branch/catalog-info.yaml', + ); + }); +}); diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.ts new file mode 100644 index 0000000000..56f3793fbb --- /dev/null +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/gitlab.ts @@ -0,0 +1,55 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import path from 'path'; +import { Entity } from '@backstage/catalog-model'; +import { InputError } from '@backstage/backend-common'; +import { PreparerBase } from './types'; +import parseGitUrl from 'git-url-parse'; +import { + parseReferenceAnnotation, + checkoutGitRepository, +} from '../../../helpers'; + +import { Logger } from 'winston'; + +export class GitlabPreparer implements PreparerBase { + private readonly logger: Logger; + + constructor(logger: Logger) { + this.logger = logger; + } + + async prepare(entity: Entity): Promise { + const { type, target } = parseReferenceAnnotation( + 'backstage.io/techdocs-ref', + entity, + ); + + if (type !== 'gitlab') { + throw new InputError(`Wrong target type: ${type}, should be 'gitlab'`); + } + + try { + const repoPath = await checkoutGitRepository(target, this.logger); + const parsedGitLocation = parseGitUrl(target); + + return path.join(repoPath, parsedGitLocation.filepath); + } catch (error) { + this.logger.debug(`Repo checkout failed with error ${error.message}`); + throw error; + } + } +} diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts index 48ffa75903..9e91958bd7 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/index.ts @@ -15,5 +15,6 @@ */ export { DirectoryPreparer } from './dir'; export { GithubPreparer } from './github'; +export { GitlabPreparer } from './gitlab'; export { Preparers } from './preparers'; export type { PreparerBuilder, PreparerBase } from './types'; diff --git a/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts b/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts index 1ceb884ea8..4cb1e1e006 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/prepare/types.ts @@ -30,4 +30,4 @@ export type PreparerBuilder = { get(entity: Entity): PreparerBase; }; -export type RemoteProtocol = 'dir' | 'github' | 'file'; +export type RemoteProtocol = 'dir' | 'github' | 'gitlab' | 'file'; diff --git a/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts b/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts index e33c6fa17d..f328443965 100644 --- a/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts +++ b/plugins/techdocs-backend/src/techdocs/stages/publish/local.ts @@ -64,7 +64,7 @@ export class LocalPublish implements PublisherBase { } resolve({ - remoteUrl: `http://localhost:7000/techdocs/static/docs/${entity.metadata.name}`, + remoteUrl: `http://localhost:7000/api/techdocs/static/docs/${entity.metadata.name}`, }); }); }); diff --git a/plugins/techdocs/package.json b/plugins/techdocs/package.json index 180a1b153a..e376202a41 100644 --- a/plugins/techdocs/package.json +++ b/plugins/techdocs/package.json @@ -48,7 +48,9 @@ "@types/jest": "^26.0.7", "@types/node": "^12.0.0", "canvas": "^2.6.1", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/plugins/techdocs/src/api.test.ts b/plugins/techdocs/src/api.test.ts index 0ab05d5ecd..f7c52f8a7d 100644 --- a/plugins/techdocs/src/api.test.ts +++ b/plugins/techdocs/src/api.test.ts @@ -28,7 +28,7 @@ describe('TechDocsStorageApi', () => { const storageApi = new TechDocsStorageApi({ apiOrigin: DOC_STORAGE_URL }); expect(storageApi.getBaseUrl('test.js', mockEntity, '')).toEqual( - `${DOC_STORAGE_URL}/${mockEntity.kind}/${mockEntity.namespace}/${mockEntity.name}/test.js`, + `${DOC_STORAGE_URL}/docs/${mockEntity.kind}/${mockEntity.namespace}/${mockEntity.name}/test.js`, ); }); @@ -36,7 +36,7 @@ describe('TechDocsStorageApi', () => { const storageApi = new TechDocsStorageApi({ apiOrigin: DOC_STORAGE_URL }); expect(storageApi.getBaseUrl('test/', mockEntity, '')).toEqual( - `${DOC_STORAGE_URL}/${mockEntity.kind}/${mockEntity.namespace}/${mockEntity.name}/test/`, + `${DOC_STORAGE_URL}/docs/${mockEntity.kind}/${mockEntity.namespace}/${mockEntity.name}/test/`, ); }); }); diff --git a/plugins/techdocs/src/api.ts b/plugins/techdocs/src/api.ts index 6fc913e5df..87a0a56a01 100644 --- a/plugins/techdocs/src/api.ts +++ b/plugins/techdocs/src/api.ts @@ -23,6 +23,11 @@ export const techdocsStorageApiRef = createApiRef({ description: 'Used to make requests towards the techdocs storage', }); +export const techdocsApiRef = createApiRef({ + id: 'plugin.techdocs.service', + description: 'Used to make requests towards techdocs API', +}); + export interface TechDocsStorage { getEntityDocs(entityId: ParsedEntityId, path: string): Promise; getBaseUrl( @@ -32,6 +37,31 @@ export interface TechDocsStorage { ): string; } +export interface TechDocs { + getMetadata(metadataType: string, entityId: ParsedEntityId): Promise; +} + +export class TechDocsApi implements TechDocs { + public apiOrigin: string; + + constructor({ apiOrigin }: { apiOrigin: string }) { + this.apiOrigin = apiOrigin; + } + + async getMetadata(metadataType: string, entityId: ParsedEntityId) { + const { kind, namespace, name } = entityId; + + const requestUrl = `${this.apiOrigin}/metadata/${metadataType}/${kind}/${ + namespace ? namespace : 'default' + }/${name}`; + + const request = await fetch(`${requestUrl}`); + const res = await request.json(); + + return res; + } +} + export class TechDocsStorageApi implements TechDocsStorage { public apiOrigin: string; @@ -42,7 +72,7 @@ export class TechDocsStorageApi implements TechDocsStorage { async getEntityDocs(entityId: ParsedEntityId, path: string) { const { kind, namespace, name } = entityId; - const url = `${this.apiOrigin}/${kind}/${ + const url = `${this.apiOrigin}/docs/${kind}/${ namespace ? namespace : 'default' }/${name}/${path}`; @@ -66,7 +96,7 @@ export class TechDocsStorageApi implements TechDocsStorage { return new URL( oldBaseUrl, - `${this.apiOrigin}/${kind}/${ + `${this.apiOrigin}/docs/${kind}/${ namespace ? namespace : 'default' }/${name}/${path}`, ).toString(); diff --git a/plugins/techdocs/src/plugin.ts b/plugins/techdocs/src/plugin.ts index 1f15e9ebd6..b197bdfb76 100644 --- a/plugins/techdocs/src/plugin.ts +++ b/plugins/techdocs/src/plugin.ts @@ -35,7 +35,12 @@ import { createApiFactory, configApiRef, } from '@backstage/core'; -import { techdocsStorageApiRef, TechDocsStorageApi } from './api'; +import { + techdocsStorageApiRef, + TechDocsStorageApi, + techdocsApiRef, + TechDocsApi, +} from './api'; export const rootRouteRef = createRouteRef({ path: '', @@ -63,5 +68,13 @@ export const plugin = createPlugin({ apiOrigin: configApi.getString('techdocs.requestUrl'), }), }), + createApiFactory({ + api: techdocsApiRef, + deps: { configApi: configApiRef }, + factory: ({ configApi }) => + new TechDocsApi({ + apiOrigin: configApi.getString('techdocs.requestUrl'), + }), + }), ], }); diff --git a/plugins/techdocs/src/reader/components/Reader.tsx b/plugins/techdocs/src/reader/components/Reader.tsx index 2aa87ea1ee..550b8df923 100644 --- a/plugins/techdocs/src/reader/components/Reader.tsx +++ b/plugins/techdocs/src/reader/components/Reader.tsx @@ -15,7 +15,7 @@ */ import React from 'react'; -import { useApi, Progress } from '@backstage/core'; +import { useApi } from '@backstage/core'; import { useShadowDom } from '..'; import { useAsync } from 'react-use'; import { techdocsStorageApiRef } from '../../api'; @@ -23,6 +23,7 @@ import { useParams, useNavigate } from 'react-router-dom'; import { ParsedEntityId } from '../../types'; import { useTheme } from '@material-ui/core'; import { BackstageTheme } from '@backstage/theme'; +import TechDocsProgressBar from './TechDocsProgressBar'; import transformer, { addBaseUrl, @@ -38,9 +39,10 @@ import { TechDocsNotFound } from './TechDocsNotFound'; type Props = { entityId: ParsedEntityId; + onReady?: () => void; }; -export const Reader = ({ entityId }: Props) => { +export const Reader = ({ entityId, onReady }: Props) => { const { kind, namespace, name } = entityId; const { '*': path } = useParams(); const theme = useTheme(); @@ -57,7 +59,9 @@ export const Reader = ({ entityId }: Props) => { if (!shadowRoot || loading || error) { return; // Shadow DOM isn't ready / It's not ready / Docs was not found } - + if (onReady) { + onReady(); + } // Pre-render const transformedElement = transformer(value as string, [ sanitizeDOM(), @@ -142,6 +146,7 @@ export const Reader = ({ entityId }: Props) => { navigate, techdocsStorageApi, theme, + onReady, ]); if (error) { @@ -150,7 +155,7 @@ export const Reader = ({ entityId }: Props) => { return ( <> - {loading ? : null} + {loading ? : null}
); diff --git a/plugins/techdocs/src/reader/components/TechDocsHome.tsx b/plugins/techdocs/src/reader/components/TechDocsHome.tsx index e51de8f57f..c478a52127 100644 --- a/plugins/techdocs/src/reader/components/TechDocsHome.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsHome.tsx @@ -18,8 +18,15 @@ import React from 'react'; import { useAsync } from 'react-use'; import { useNavigate, generatePath } from 'react-router-dom'; import { Grid } from '@material-ui/core'; -import { ItemCard, Progress, useApi } from '@backstage/core'; -import { TechDocsPageWrapper } from './TechDocsPageWrapper'; +import { + ItemCard, + Progress, + useApi, + Content, + Page, + pageTheme, + Header, +} from '@backstage/core'; import { catalogApiRef } from '@backstage/plugin-catalog'; import { rootDocsRouteRef } from '../../plugin'; @@ -36,53 +43,62 @@ export const TechDocsHome = () => { if (loading) { return ( - - - + +
+ + + + ); } if (error) { return ( - -

{error.message}

-
+ +
+ +

{error.message}

+
+ ); } return ( - - - {value?.length - ? value.map((entity, index: number) => ( - - - navigate( - generatePath(rootDocsRouteRef.path, { - entityId: `${entity.kind}:${ - entity.metadata.namespace ?? '' - }:${entity.metadata.name}`, - }), - ) - } - title={entity.metadata.name} - label="Read Docs" - description={entity.metadata.description} - /> - - )) - : null} - - + +
+ + + {value?.length + ? value.map((entity, index: number) => ( + + + navigate( + generatePath(rootDocsRouteRef.path, { + entityId: `${entity.kind}:${ + entity.metadata.namespace ?? '' + }:${entity.metadata.name}`, + }), + ) + } + title={entity.metadata.name} + label="Read Docs" + description={entity.metadata.description} + /> + + )) + : null} + + + ); }; diff --git a/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx b/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx new file mode 100644 index 0000000000..464115bab7 --- /dev/null +++ b/plugins/techdocs/src/reader/components/TechDocsPage.test.tsx @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { TechDocsPage } from './TechDocsPage'; +import { render, act } from '@testing-library/react'; +import { wrapInTestApp } from '@backstage/test-utils'; +import { ApiRegistry, ApiProvider } from '@backstage/core-api'; +import { + techdocsApiRef, + TechDocsApi, + techdocsStorageApiRef, + TechDocsStorageApi, +} from '../../api'; + +jest.mock('react-router-dom', () => { + const actual = jest.requireActual('react-router-dom'); + return { + ...actual, + useParams: jest.fn(), + }; +}); + +jest.mock('./TechDocsPageHeader', () => { + return { + __esModule: true, + TechDocsPageHeader: () =>
, + }; +}); + +const { useParams }: { useParams: jest.Mock } = jest.requireMock( + 'react-router-dom', +); + +describe('', () => { + it('should render techdocs page', async () => { + useParams.mockReturnValue({ + entityId: 'Component::backstage', + }); + + const techDocsApi: Partial = { + getMetadata: () => Promise.resolve([]), + }; + const techDocsStorageApi: Partial = { + getEntityDocs: (): Promise => Promise.resolve('String'), + getBaseUrl: (): string => '', + }; + + const apiRegistry = ApiRegistry.from([ + [techdocsApiRef, techDocsApi], + [techdocsStorageApiRef, techDocsStorageApi], + ]); + + await act(async () => { + const rendered = render( + wrapInTestApp( + + + , + ), + ); + expect(rendered.getByTestId('techdocs-content')).toBeInTheDocument(); + }); + }); +}); diff --git a/plugins/techdocs/src/reader/components/TechDocsPage.tsx b/plugins/techdocs/src/reader/components/TechDocsPage.tsx index 1328d13ee9..a70ce76191 100644 --- a/plugins/techdocs/src/reader/components/TechDocsPage.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsPage.tsx @@ -14,26 +14,60 @@ * limitations under the License. */ -import React from 'react'; +import React, { useState } from 'react'; import { useParams } from 'react-router-dom'; - -import { TechDocsPageWrapper } from './TechDocsPageWrapper'; +import { Content, Page, pageTheme, useApi } from '@backstage/core'; import { Reader } from './Reader'; +import { useAsync } from 'react-use'; +import { TechDocsPageHeader } from './TechDocsPageHeader'; +import { techdocsApiRef } from '../../api'; export const TechDocsPage = () => { + const [documentReady, setDocumentReady] = useState(false); const { entityId } = useParams(); - const [kind, namespace, name] = entityId.split(':'); + const techDocsApi = useApi(techdocsApiRef); + + const mkdocsMetadataRequest = useAsync(() => { + if (documentReady) { + return techDocsApi.getMetadata('mkdocs', { kind, namespace, name }); + } + + return Promise.resolve({ loading: true }); + }, [kind, namespace, name, techDocsApi, documentReady]); + + const entityMetadataRequest = useAsync(() => { + return techDocsApi.getMetadata('entity', { kind, namespace, name }); + }, [kind, namespace, name, techDocsApi]); + + const onReady = () => { + setDocumentReady(true); + }; + return ( - - + - + + + + ); }; diff --git a/plugins/techdocs/src/reader/components/TechDocsPageHeader.test.tsx b/plugins/techdocs/src/reader/components/TechDocsPageHeader.test.tsx new file mode 100644 index 0000000000..70388e81c2 --- /dev/null +++ b/plugins/techdocs/src/reader/components/TechDocsPageHeader.test.tsx @@ -0,0 +1,87 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import React from 'react'; +import { TechDocsPageHeader } from './TechDocsPageHeader'; +import { render, act } from '@testing-library/react'; +import { wrapInTestApp } from '@backstage/test-utils'; + +describe('', () => { + it('should render a techdocs page header', async () => { + await act(async () => { + const rendered = render( + wrapInTestApp( + , + ), + ); + expect(rendered.container.innerHTML).toContain('header'); + expect(rendered.getByText('test-site-name')).toBeDefined(); + expect(rendered.getByText('test-site-desc')).toBeDefined(); + }); + }); + + it('should render a techdocs page header even if metadata is missing', async () => { + await act(async () => { + const rendered = render( + wrapInTestApp( + , + ), + ); + + expect(rendered.container.innerHTML).toContain('header'); + }); + }); +}); diff --git a/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx b/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx new file mode 100644 index 0000000000..b01ace4994 --- /dev/null +++ b/plugins/techdocs/src/reader/components/TechDocsPageHeader.tsx @@ -0,0 +1,88 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React from 'react'; +import GitHubIcon from '@material-ui/icons/GitHub'; +import { Header, HeaderLabel, Link } from '@backstage/core'; +import { CircularProgress } from '@material-ui/core'; +import { ParsedEntityId } from '../../types'; +import { AsyncState } from 'react-use/lib/useAsync'; + +type TechDocsPageHeaderProps = { + entityId: ParsedEntityId; + metadataRequest: { + entity: AsyncState; + mkdocs: AsyncState; + }; +}; + +export const TechDocsPageHeader = ({ + entityId, + metadataRequest, +}: TechDocsPageHeaderProps) => { + const { mkdocs: mkdocsMetadata, entity: entityMetadata } = metadataRequest; + + const { value: mkDocsMetadataValues } = mkdocsMetadata; + const { value: entityMetadataValues } = entityMetadata; + + const { kind, name } = entityId; + + const { site_name: siteName, site_description: siteDescription } = + mkDocsMetadataValues || {}; + + const { + locationMetadata, + spec: { owner, lifecycle }, + } = entityMetadataValues || { spec: {} }; + + const labels = ( + <> + + {name} + + } + /> + {owner ? : null} + {lifecycle ? : null} + {locationMetadata && + locationMetadata.type !== 'dir' && + locationMetadata.type !== 'file' ? ( + + + + } + /> + ) : null} + + ); + + return ( +
} + subtitle={ + siteDescription && siteDescription !== 'None' ? siteDescription : '' + } + > + {labels} +
+ ); +}; diff --git a/plugins/techdocs/src/reader/components/TechDocsPageWrapper.test.tsx b/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx similarity index 56% rename from plugins/techdocs/src/reader/components/TechDocsPageWrapper.test.tsx rename to plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx index 5265492fb3..be464bd485 100644 --- a/plugins/techdocs/src/reader/components/TechDocsPageWrapper.test.tsx +++ b/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx @@ -13,21 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { TechDocsPageWrapper } from './TechDocsPageWrapper'; + +import TechDocsProgressBar from './TechDocsProgressBar'; import React from 'react'; import { render } from '@testing-library/react'; import { wrapInTestApp } from '@backstage/test-utils'; +import { act } from 'react-dom/test-utils'; -describe('TechDocs Page Wrapper', () => { - it('should render a TechDocs Page Wrapper', async () => { - const { queryByText } = render( - wrapInTestApp( - - Test - , - ), - ); - expect(queryByText(/test-title/i)).toBeInTheDocument(); - expect(queryByText(/test-subtitle/i)).toBeInTheDocument(); +jest.useFakeTimers(); + +describe('', () => { + it('should render a message if techdocs page takes more time to load', () => { + const rendered = render(wrapInTestApp()); + + expect(rendered.getByTestId('progress')).toBeDefined(); + expect(rendered.queryByTestId('delay-reason')).toBeNull(); + act(() => { + jest.advanceTimersByTime(5000); + }); + expect(rendered.getByTestId('delay-reason')).toBeDefined(); }); }); diff --git a/plugins/techdocs/src/reader/components/TechDocsProgressBar.tsx b/plugins/techdocs/src/reader/components/TechDocsProgressBar.tsx new file mode 100644 index 0000000000..c7caa125bc --- /dev/null +++ b/plugins/techdocs/src/reader/components/TechDocsProgressBar.tsx @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useState, useEffect } from 'react'; +import { useMountedState } from 'react-use'; +import { Progress } from '@backstage/core'; +import { Typography } from '@material-ui/core'; + +const TechDocsProgressBar = () => { + const isMounted = useMountedState(); + const [hasBeenDelayed, setHasBeenDelayed] = useState(false); + + const delayReason = `Docs are still loading...Backstage takes some extra time to load docs + for the first time. The subsequent loads are much faster.`; + + // Allowed time that docs can take to load (in milliseconds) + const allowedDelayTime = 5000; + + useEffect(() => { + setTimeout(() => { + if (isMounted()) { + setHasBeenDelayed(true); + } + }, allowedDelayTime); + }); + + return ( + <> + {hasBeenDelayed ? ( + {delayReason} + ) : null} + + + ); +}; + +export default TechDocsProgressBar; diff --git a/plugins/welcome/package.json b/plugins/welcome/package.json index 4dca91e503..d6c3a907b7 100644 --- a/plugins/welcome/package.json +++ b/plugins/welcome/package.json @@ -39,7 +39,9 @@ "@testing-library/user-event": "^12.0.7", "@types/jest": "^26.0.7", "@types/node": "^12.0.0", - "jest-fetch-mock": "^3.0.3" + "jest-fetch-mock": "^3.0.3", + "msw": "^0.20.5", + "node-fetch": "^2.6.1" }, "files": [ "dist" diff --git a/scripts/check-docs-quality.js b/scripts/check-docs-quality.js new file mode 100755 index 0000000000..61968a2ac0 --- /dev/null +++ b/scripts/check-docs-quality.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const { execSync, spawnSync } = require('child_process'); +const path = require('path'); + +const listFilesTrackedByGit = 'git ls-files'; + +const inheritStdIo = { + stdio: 'inherit', +}; + +const ERROR_MESSAGE = + 'Please install vale linter(https://docs.errata.ai/vale/install). Ignore this message if already installed.\n'; + +// xargs is not supported by shx. +if (process.platform === 'win32') { + const validMDFilesCommand = `${listFilesTrackedByGit} | .\\node_modules\\.bin\\shx grep ".md"`; + try { + // get list of all md files except in directories of gitignore. + let filesToLint = execSync(validMDFilesCommand, { + stdio: ['ignore', 'pipe', 'inherit'], + }); + + // set all file(s) path as absolute path + filesToLint = filesToLint + .toString() + .split('\n') + .map(filepath => (filepath ? path.join(process.cwd(), filepath) : null)) + .filter(Boolean); + + const output = spawnSync('vale', filesToLint, inheritStdIo); + + // if the command does not succeed + if (output.status !== 0) { + // if it contains system level error. [in this case vale does not exist] + if (output.error) { + console.error(ERROR_MESSAGE); + } + process.exit(1); + } + } catch (e) { + console.error(e.message); + process.exit(1); + } +} else { + const validMDFilesCommand = `${listFilesTrackedByGit} | ./node_modules/.bin/shx grep ".md"`; + // use xargs + try { + execSync(`${validMDFilesCommand} | xargs vale`, inheritStdIo); + } catch (e) { + console.error(ERROR_MESSAGE); + process.exit(1); + } +} diff --git a/yarn.lock b/yarn.lock index 33a1720a14..fe36f17fd2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2441,6 +2441,34 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz#9df03bbd7c696a5c58885c34aa06da41c8543796" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== +"@kubernetes/client-node@^0.12.1": + version "0.12.2" + resolved "https://registry.npmjs.org/@kubernetes/client-node/-/client-node-0.12.2.tgz#8728684bd57d1cbcbe14fe742e79be7021403eea" + integrity sha512-J0UwyFl1Iv/IZ6WMP7LaizBEoKPnqwtc8tIO2q/X+EuDT7eGpPPAMHXSEOC/EI9JGIf0FaJEcDHhB/Dio/mKhw== + dependencies: + "@types/js-yaml" "^3.12.1" + "@types/node" "^10.12.0" + "@types/request" "^2.47.1" + "@types/stream-buffers" "^3.0.3" + "@types/tar" "^4.0.3" + "@types/underscore" "^1.8.9" + "@types/ws" "^6.0.1" + byline "^5.0.0" + execa "1.0.0" + isomorphic-ws "^4.0.1" + js-yaml "^3.13.1" + jsonpath-plus "^0.19.0" + openid-client "^4.1.1" + request "^2.88.0" + rfc4648 "^1.3.0" + shelljs "^0.8.2" + stream-buffers "^3.0.2" + tar "^6.0.2" + tmp-promise "^3.0.2" + tslib "^1.9.3" + underscore "^1.9.1" + ws "^7.3.1" + "@kyleshockey/object-assign-deep@^0.4.2": version "0.4.2" resolved "https://registry.npmjs.org/@kyleshockey/object-assign-deep/-/object-assign-deep-0.4.2.tgz#84900f0eefc372798f4751b5262830b8208922ec" @@ -2453,10 +2481,10 @@ dependencies: stream "^0.0.2" -"@kyma-project/asyncapi-react@^0.11.0": - version "0.11.2" - resolved "https://registry.npmjs.org/@kyma-project/asyncapi-react/-/asyncapi-react-0.11.2.tgz#b523b0843da7c29a0d7569b3f31d7d8cbdf84b47" - integrity sha512-Wo6CgM3pzZaRMCVwXaEIrlXMuFtRNGli1GtFgMHQUB686daSCqSvRZUyitDHTZLofL3OI9JeYh5m6SjPji6bxg== +"@kyma-project/asyncapi-react@^0.13.1": + version "0.13.1" + resolved "https://registry.npmjs.org/@kyma-project/asyncapi-react/-/asyncapi-react-0.13.1.tgz#8a92ee2df996540240c0afa17adfa566e4cee18d" + integrity sha512-d+52fzfBHpcC32WvrfB6sSyQFgzda/lHrKSn5klXP6tEiOU5uaLEIQzvZLCL8kXtuHiknozHO3h/BfviqEkwww== dependencies: "@asyncapi/avro-schema-parser" "^0.1.2" "@asyncapi/openapi-schema-parser" "^2.0.0" @@ -3229,7 +3257,7 @@ react-transition-group "^4.0.0" rifm "^0.7.0" -"@material-ui/styles@^4.10.0": +"@material-ui/styles@^4.10.0", "@material-ui/styles@^4.9.6": version "4.10.0" resolved "https://registry.npmjs.org/@material-ui/styles/-/styles-4.10.0.tgz#2406dc23aa358217aa8cc772e6237bd7f0544071" integrity sha512-XPwiVTpd3rlnbfrgtEJ1eJJdFCXZkHxy8TrdieaTvwxNYj42VnnCyFzxYeNW9Lhj4V1oD8YtQ6S5Gie7bZDf7Q== @@ -3365,6 +3393,15 @@ "@octokit/types" "^5.0.0" universal-user-agent "^5.0.0" +"@octokit/graphql@^4.5.6": + version "4.5.6" + resolved "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.6.tgz#708143ba15cf7c1879ed6188266e7f270be805d4" + integrity sha512-Rry+unqKTa3svswT2ZAuqenpLrzJd+JTv89LTeVa5UM/5OX8o4KTkPL7/1ABq4f/ZkELb0XEK/2IEoYwykcLXg== + dependencies: + "@octokit/request" "^5.3.0" + "@octokit/types" "^5.0.0" + universal-user-agent "^6.0.0" + "@octokit/plugin-enterprise-rest@^6.0.1": version "6.0.1" resolved "https://registry.npmjs.org/@octokit/plugin-enterprise-rest/-/plugin-enterprise-rest-6.0.1.tgz#e07896739618dab8da7d4077c658003775f95437" @@ -3490,7 +3527,7 @@ dependencies: "@types/node" ">= 8" -"@open-draft/until@^1.0.0", "@open-draft/until@^1.0.3": +"@open-draft/until@^1.0.3": version "1.0.3" resolved "https://registry.npmjs.org/@open-draft/until/-/until-1.0.3.tgz#db9cc719191a62e7d9200f6e7bab21c5b848adca" integrity sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q== @@ -3616,13 +3653,16 @@ react-router-dom "6.0.0-beta.0" react-use "^15.3.3" -"@roadiehq/backstage-plugin-travis-ci@^0.1.4": - version "0.1.4" - resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-travis-ci/-/backstage-plugin-travis-ci-0.1.4.tgz#ddbb2ba5b9d47f474462ecbc8c769759578e8526" - integrity sha512-T1eJ0huhwZcRHjrDKWoAzlKBv8UbhXgrvE7wuHD7dCcmfQdln0jbn7cskOpTnVmrzGXWKQ6mDyKX3LfdEPYbAw== +"@roadiehq/backstage-plugin-travis-ci@^0.2.3": + version "0.2.3" + resolved "https://registry.npmjs.org/@roadiehq/backstage-plugin-travis-ci/-/backstage-plugin-travis-ci-0.2.3.tgz#2d1c5a7ed3eab4fdcf95243b73dee44c0cff5a57" + integrity sha512-Xi8vZFbcm+D4ykyU3I9hImAd22F1v6M1F/H9CJanRHqj5esJxnuCS2+Kf+w09bwb9DuM8/c68PuMlf3PMIsOwg== dependencies: - "@backstage/core" "^0.1.1-alpha.18" - "@backstage/theme" "^0.1.1-alpha.18" + "@backstage/catalog-model" "^0.1.1-alpha.22" + "@backstage/core" "^0.1.1-alpha.22" + "@backstage/core-api" "^0.1.1-alpha.22" + "@backstage/plugin-catalog" "^0.1.1-alpha.22" + "@backstage/theme" "^0.1.1-alpha.22" "@material-ui/core" "^4.9.1" "@material-ui/icons" "^4.9.1" "@material-ui/lab" "4.0.0-alpha.45" @@ -4638,6 +4678,11 @@ "@types/node" "*" "@types/responselike" "*" +"@types/caseless@*": + version "0.12.2" + resolved "https://registry.npmjs.org/@types/caseless/-/caseless-0.12.2.tgz#f65d3d6389e01eeb458bd54dc8f52b95a9463bc8" + integrity sha512-6ckxMjBBD8URvjB6J3NcnuAn5Pkl7t3TizAg+xdlzzQGSPSmBcXf8KoIH0ua/i+tio+ZRUHEXp0HEmvaR4kt0w== + "@types/classnames@^2.2.9": version "2.2.10" resolved "https://registry.npmjs.org/@types/classnames/-/classnames-2.2.10.tgz#cc658ca319b6355399efc1f5b9e818f1a24bf999" @@ -4710,11 +4755,6 @@ dependencies: "@types/express" "*" -"@types/cookie@^0.3.3": - version "0.3.3" - resolved "https://registry.npmjs.org/@types/cookie/-/cookie-0.3.3.tgz#85bc74ba782fb7aa3a514d11767832b0e3bc6803" - integrity sha512-LKVP3cgXBT9RYj+t+9FDKwS5tdI+rPBXaNSkma7hvqy35lc7mAokC2zsqWJH0LaqIt3B962nuYI77hsJoT1gow== - "@types/cookie@^0.4.0": version "0.4.0" resolved "https://registry.npmjs.org/@types/cookie/-/cookie-0.4.0.tgz#14f854c0f93d326e39da6e3b6f34f7d37513d108" @@ -4735,6 +4775,11 @@ "@types/keygrip" "*" "@types/node" "*" +"@types/core-js@^2.5.4": + version "2.5.4" + resolved "https://registry.npmjs.org/@types/core-js/-/core-js-2.5.4.tgz#fc42ebde7d9cfa7c5f2668f117449b02348e41fd" + integrity sha512-Xwy8o12ak+iYgFr/KCVaVK5Sy+jFMiiPAID3+ObvMlBzy26XQJw5xu+a6rlHsrJENXj/AwJOGsJpVohUjAzSKQ== + "@types/cors@^2.8.4", "@types/cors@^2.8.6": version "2.8.6" resolved "https://registry.npmjs.org/@types/cors/-/cors-2.8.6.tgz#cfaab33c49c15b1ded32f235111ce9123009bd02" @@ -4754,6 +4799,18 @@ resolved "https://registry.npmjs.org/@types/d3-force/-/d3-force-1.2.1.tgz#c28803ea36fe29788db69efa0ad6c2dc09544e83" integrity sha512-jqK+I36uz4kTBjyk39meed5y31Ab+tXYN/x1dn3nZEus9yOHCLc+VrcIYLc/aSQ0Y7tMPRlIhLetulME76EiiA== +"@types/d3-path@*": + version "1.0.8" + resolved "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.8.tgz#48e6945a8ff43ee0a1ce85c8cfa2337de85c7c79" + integrity sha512-AZGHWslq/oApTAHu9+yH/Bnk63y9oFOMROtqPAtxl5uB6qm1x2lueWdVEjsjjV3Qc2+QfuzKIwIR5MvVBakfzA== + +"@types/d3-shape@*": + version "1.3.2" + resolved "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-1.3.2.tgz#a41d9d6b10d02e221696b240caf0b5d0f5a588ec" + integrity sha512-LtD8EaNYCaBRzHzaAiIPrfcL3DdIysc81dkGlQvv7WQP3+YXV7b0JJTtR1U3bzeRieS603KF4wUo+ZkJVenh8w== + dependencies: + "@types/d3-path" "*" + "@types/diff@^4.0.2": version "4.0.2" resolved "https://registry.npmjs.org/@types/diff/-/diff-4.0.2.tgz#2e9bb89f9acc3ab0108f0f3dc4dbdcf2fff8a99c" @@ -4981,9 +5038,9 @@ "@types/istanbul-lib-report" "*" "@types/jest@*", "@types/jest@^26.0.7": - version "26.0.9" - resolved "https://registry.npmjs.org/@types/jest/-/jest-26.0.9.tgz#0543b57da5f0cd949c5f423a00c56c492289c989" - integrity sha512-k4qFfJ5AUKrWok5KYXp2EPm89b0P/KZpl7Vg4XuOTVVQEhLDBDBU3iBFrjjdgd8fLw96aAtmnwhXHl63bWeBQQ== + version "26.0.14" + resolved "https://registry.npmjs.org/@types/jest/-/jest-26.0.14.tgz#078695f8f65cb55c5a98450d65083b2b73e5a3f3" + integrity sha512-Hz5q8Vu0D288x3iWXePSn53W7hAjP0H7EQ6QvDO9c7t46mR0lNOLlfuwQ+JkVxuhygHzlzPX+0jKdA3ZgSh+Vg== dependencies: jest-diff "^25.2.1" pretty-format "^25.2.1" @@ -5000,7 +5057,7 @@ resolved "https://registry.npmjs.org/@types/js-cookie/-/js-cookie-2.2.6.tgz#f1a1cb35aff47bc5cfb05cb0c441ca91e914c26f" integrity sha512-+oY0FDTO2GYKEV0YPvSshGq9t7YozVkgvXLty7zogQNuCxBhT9/3INX9Q7H1aRZ4SUDRXAKlJuA4EA5nTt7SNw== -"@types/js-yaml@^3.12.5": +"@types/js-yaml@^3.12.1", "@types/js-yaml@^3.12.5": version "3.12.5" resolved "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-3.12.5.tgz#136d5e6a57a931e1cce6f9d8126aa98a9c92a6bb" integrity sha512-JCcp6J0GV66Y4ZMDAQCXot4xprYB+Zfd3meK9+INSJeVZwJmHAW30BBEEkPzXswMXuiyReUGOP3GxrADc9wPww== @@ -5144,6 +5201,11 @@ resolved "https://registry.npmjs.org/@types/node/-/node-10.17.28.tgz#0e36d718a29355ee51cec83b42d921299200f6d9" integrity sha512-dzjES1Egb4c1a89C7lKwQh8pwjYmlOAG9dW1pBgxEk57tMrLnssOfEthz8kdkNaBd7lIqQx7APm5+mZ619IiCQ== +"@types/node@^10.12.0": + version "10.17.35" + resolved "https://registry.npmjs.org/@types/node/-/node-10.17.35.tgz#58058f29b870e6ae57b20e4f6e928f02b7129f56" + integrity sha512-gXx7jAWpMddu0f7a+L+txMplp3FnHl53OhQIF9puXKq3hDGY/GjH+MF04oWnV/adPSCrbtHumDCFwzq2VhltWA== + "@types/node@^12.0.0": version "12.12.53" resolved "https://registry.npmjs.org/@types/node/-/node-12.12.53.tgz#be0d375933c3d15ef2380dafb3b0350ea7021129" @@ -5380,6 +5442,14 @@ dependencies: "@types/react" "*" +"@types/recharts@^1.8.14": + version "1.8.15" + resolved "https://registry.npmjs.org/@types/recharts/-/recharts-1.8.15.tgz#02bc06085c9a31a58c00194d15377b45cf506bbf" + integrity sha512-ApCfDT/R8RCbZTcl0iqLiKsxVdzE3GzoawTgJUHuQOz6ZXhsPVfp7CNSKI2s3zFwrRRsgmpv2AEcbcZceNHg4w== + dependencies: + "@types/d3-shape" "*" + "@types/react" "*" + "@types/recursive-readdir@^2.2.0": version "2.2.0" resolved "https://registry.npmjs.org/@types/recursive-readdir/-/recursive-readdir-2.2.0.tgz#b39cd5474fd58ea727fe434d5c68b7a20ba9121c" @@ -5392,6 +5462,16 @@ resolved "https://registry.npmjs.org/@types/relateurl/-/relateurl-0.2.28.tgz#6bda7db8653fa62643f5ee69e9f69c11a392e3a6" integrity sha1-a9p9uGU/piZD9e5p6facEaOS46Y= +"@types/request@^2.47.1": + version "2.48.5" + resolved "https://registry.npmjs.org/@types/request/-/request-2.48.5.tgz#019b8536b402069f6d11bee1b2c03e7f232937a0" + integrity sha512-/LO7xRVnL3DxJ1WkPGDQrp4VTV1reX9RkC85mJ+Qzykj2Bdw+mG15aAfDahc76HtknjzE16SX/Yddn6MxVbmGQ== + dependencies: + "@types/caseless" "*" + "@types/node" "*" + "@types/tough-cookie" "*" + form-data "^2.5.0" + "@types/resolve@1.17.1": version "1.17.1" resolved "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz#3afd6ad8967c77e4376c598a82ddd58f46ec45d6" @@ -5477,6 +5557,13 @@ dependencies: "@types/node" "*" +"@types/stream-buffers@^3.0.3": + version "3.0.3" + resolved "https://registry.npmjs.org/@types/stream-buffers/-/stream-buffers-3.0.3.tgz#34e565bf64e3e4bdeee23fd4aa58d4636014a02b" + integrity sha512-NeFeX7YfFZDYsCfbuaOmFQ0OjSmHreKBpp7MQ4alWQBHeh2USLsj7qyMyn9t82kjqIX516CR/5SRHnARduRtbQ== + dependencies: + "@types/node" "*" + "@types/styled-jsx@^2.2.8": version "2.2.8" resolved "https://registry.npmjs.org/@types/styled-jsx/-/styled-jsx-2.2.8.tgz#b50d13d8a3c34036282d65194554cf186bab7234" @@ -5555,6 +5642,11 @@ dependencies: "@types/node" "*" +"@types/tough-cookie@*": + version "4.0.0" + resolved "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.0.tgz#fef1904e4668b6e5ecee60c52cc6a078ffa6697d" + integrity sha512-I99sngh224D0M7XgW1s120zxCt3VYQ3IQsuw3P3jbq5GG4yc79+ZjyKznyOGIQrflfylLgcfekeZW/vk0yng6A== + "@types/uglify-js@*": version "3.0.4" resolved "https://registry.npmjs.org/@types/uglify-js/-/uglify-js-3.0.4.tgz#96beae23df6f561862a830b4288a49e86baac082" @@ -5562,6 +5654,11 @@ dependencies: source-map "^0.6.1" +"@types/underscore@^1.8.9": + version "1.10.23" + resolved "https://registry.npmjs.org/@types/underscore/-/underscore-1.10.23.tgz#cc672e8864000d288e1e39c609fd9cab84391ff3" + integrity sha512-vX1NPekXhrLquFWskH2thcvFAha187F/lM6xYOoEMZWwJ/6alSk0/ttmGP/YRqcqtCv0TMbZjYAdZyHAEcuU4g== + "@types/uuid@^8.0.0": version "8.0.0" resolved "https://registry.npmjs.org/@types/uuid/-/uuid-8.0.0.tgz#165aae4819ad2174a17476dbe66feebd549556c0" @@ -5579,9 +5676,9 @@ "@types/webpack" "*" "@types/webpack-env@^1.15.2": - version "1.15.2" - resolved "https://registry.npmjs.org/@types/webpack-env/-/webpack-env-1.15.2.tgz#927997342bb9f4a5185a86e6579a0a18afc33b0a" - integrity sha512-67ZgZpAlhIICIdfQrB5fnDvaKFcDxpKibxznfYRVAT4mQE41Dido/3Ty+E3xGBmTogc5+0Qb8tWhna+5B8z1iQ== + version "1.15.3" + resolved "https://registry.npmjs.org/@types/webpack-env/-/webpack-env-1.15.3.tgz#fb602cd4c2f0b7c0fb857e922075fdf677d25d84" + integrity sha512-5oiXqR7kwDGZ6+gmzIO2lTC+QsriNuQXZDWNYRV3l2XRN/zmPgnC21DLSx2D05zvD8vnXW6qUg7JnXZ4I6qLVQ== "@types/webpack-node-externals@^2.5.0": version "2.5.0" @@ -5623,6 +5720,13 @@ resolved "https://registry.npmjs.org/@types/whatwg-streams/-/whatwg-streams-0.0.7.tgz#28bfe73dc850562296367249c4b32a50db81e9d3" integrity sha512-6sDiSEP6DWcY2ZolsJ2s39ZmsoGQ7KVwBDI3sESQsEm9P2dHTcqnDIHRZFRNtLCzWp7hCFGqYbw5GyfpQnJ01A== +"@types/ws@^6.0.1": + version "6.0.4" + resolved "https://registry.npmjs.org/@types/ws/-/ws-6.0.4.tgz#7797707c8acce8f76d8c34b370d4645b70421ff1" + integrity sha512-PpPrX7SZW9re6+Ha8ojZG4Se8AZXgf0GK6zmfqEuCsY49LFDNXO3SByp44X3dFEqtB73lkCDAdUazhAjVPiNwg== + dependencies: + "@types/node" "*" + "@types/ws@^7.0.0": version "7.2.6" resolved "https://registry.npmjs.org/@types/ws/-/ws-7.2.6.tgz#516cbfb818310f87b43940460e065eb912a4178d" @@ -6755,6 +6859,15 @@ axobject-query@^2.0.2: resolved "https://registry.npmjs.org/axobject-query/-/axobject-query-2.1.2.tgz#2bdffc0371e643e5f03ba99065d5179b9ca79799" integrity sha512-ICt34ZmrVt8UQnvPl6TVyDTkmhXmAyAT4Jh5ugfGUX4MOrZ+U/ZY6/sdylRw3qGNr9Ub5AJsaHeDMzNLehRdOQ== +azure-devops-node-api@^10.1.1: + version "10.1.1" + resolved "https://registry.npmjs.org/azure-devops-node-api/-/azure-devops-node-api-10.1.1.tgz#9016d8935316fff260f5f8fafd81d0caff90a19e" + integrity sha512-P4Hyrh/+Nzc2KXQk73z72/GsenSWIH5o8uiyELqykJYs9TWTVCxVwghoR7lPeiY6QVoXkq2S2KtvAgi5fyjl9w== + dependencies: + tunnel "0.0.6" + typed-rest-client "^1.7.3" + underscore "1.8.3" + babel-code-frame@^6.22.0: version "6.26.0" resolved "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" @@ -7146,6 +7259,11 @@ bail@^1.0.0: resolved "https://registry.npmjs.org/bail/-/bail-1.0.5.tgz#b6fa133404a392cbc1f8c4bf63f5953351e7a776" integrity sha512-xFbRxM1tahm08yHBP16MMjVUAvDaBMD38zsM9EMAUN61omwLmKlOpB/Zku5QkjZ8TZ4vn53pj+t518cH0S03RQ== +balanced-match@^0.4.2: + version "0.4.2" + resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz#cb3f3e3c732dc0f01ee70b403f302e61d7709838" + integrity sha1-yz8+PHMtwPAe5wtAPzAuYddwmDg= + balanced-match@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" @@ -7161,7 +7279,7 @@ base64-js@^1.0.2, base64-js@^1.2.0: resolved "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz#58ece8cb75dd07e71ed08c736abc5fac4dbf8df1" integrity sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g== -base64url@3.x.x: +base64url@3.x.x, base64url@^3.0.1: version "3.0.1" resolved "https://registry.npmjs.org/base64url/-/base64url-3.0.1.tgz#6399d572e2bc3f90a9a8b22d5dbb0a32d33f788d" integrity sha512-ir1UPr3dkwexU7FdV8qBBbNDRUhMmIekYMFZfi+C/sLNnRESKPl23nB9b2pltqfOQNnGzsDdId90AEtG5tCx4A== @@ -7276,6 +7394,13 @@ bl@^4.0.1: inherits "^2.0.4" readable-stream "^3.4.0" +block-stream@*: + version "0.0.9" + resolved "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" + integrity sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo= + dependencies: + inherits "~2.0.0" + bluebird@3.7.2, bluebird@^3.3.5, bluebird@^3.5.1, bluebird@^3.5.3, bluebird@^3.5.5, bluebird@^3.7.2: version "3.7.2" resolved "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f" @@ -8217,6 +8342,16 @@ codemirror@^5.52.2: resolved "https://registry.npmjs.org/codemirror/-/codemirror-5.53.2.tgz#9799121cf8c50809cca487304e9de3a74d33f428" integrity sha512-wvSQKS4E+P8Fxn/AQ+tQtJnF1qH5UOlxtugFLpubEZ5jcdH2iXTVinb+Xc/4QjshuOxRm4fUsU2QPF1JJKiyXA== +codeowners-utils@^1.0.2: + version "1.0.2" + resolved "https://registry.npmjs.org/codeowners-utils/-/codeowners-utils-1.0.2.tgz#9d30148bf957c53d55f75df432cb1e3b4bc6ee28" + integrity sha512-4oLRCymV7azxGHMpM3F297D651VdwZa21hVfFCn/cOd8Fq8tFrpfpyRpSBQkaZCyFPkfOhEld9xceCF7btyiug== + dependencies: + cross-spawn "^7.0.2" + find-up "^4.1.0" + ignore "^5.1.4" + locate-path "^5.0.0" + collapse-white-space@^1.0.2: version "1.0.6" resolved "https://registry.npmjs.org/collapse-white-space/-/collapse-white-space-1.0.6.tgz#e63629c0016665792060dbbeb79c42239d2c5287" @@ -8696,7 +8831,7 @@ core-js-pure@^3.0.0, core-js-pure@^3.0.1: resolved "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.6.4.tgz#4bf1ba866e25814f149d4e9aaa08c36173506e3a" integrity sha512-epIhRLkXdgv32xIUFaaAry2wdxZYBi6bgM7cB136dzzXXa+dFyRLTZeLUJxnd8ShrmyVXBub63n2NHo2JAt8Cw== -core-js@^2.4.0, core-js@^2.4.1, core-js@^2.5.7, core-js@^2.6.11, core-js@^2.6.5: +core-js@^2.4.0, core-js@^2.4.1, core-js@^2.5.7, core-js@^2.6.10, core-js@^2.6.11, core-js@^2.6.5: version "2.6.11" resolved "https://registry.npmjs.org/core-js/-/core-js-2.6.11.tgz#38831469f9922bded8ee21c9dc46985e0399308c" integrity sha512-5wjnpaT/3dV+XB4borEsnAYQchn00XSgTAWKDkEqv+K8KevjbzmofK6hfJ9TZIlpj2N0xQpazy7PiRQiWHqzWg== @@ -9214,6 +9349,21 @@ cypress@*, cypress@^4.2.0: url "^0.11.0" yauzl "^2.10.0" +d3-array@^1.2.0: + version "1.2.4" + resolved "https://registry.npmjs.org/d3-array/-/d3-array-1.2.4.tgz#635ce4d5eea759f6f605863dbcfc30edc737f71f" + integrity sha512-KHW6M86R+FUPYGb3R5XiYjXPq7VzwxZ22buHhAEVG5ztoEcZZMLov530mmccaqA1GghZArjQV46fuc8kUqhhHw== + +d3-collection@1: + version "1.0.7" + resolved "https://registry.npmjs.org/d3-collection/-/d3-collection-1.0.7.tgz#349bd2aa9977db071091c13144d5e4f16b5b310e" + integrity sha512-ii0/r5f4sjKNTfh84Di+DpztYwqKhEyUlKoPrzUFfeSkWxjW49xU2QzO9qrPrNkpdI0XJkfzvmTu8V2Zylln6A== + +d3-color@1: + version "1.4.1" + resolved "https://registry.npmjs.org/d3-color/-/d3-color-1.4.1.tgz#c52002bf8846ada4424d55d97982fef26eb3bc8a" + integrity sha512-p2sTHSLCJI2QKunbGb7ocOh7DgTAn8IrLx21QRc/BSnodXM4sv6aLQlnfpvehFMLZEfBc6g9pH9SWQccFYfJ9Q== + "d3-dispatch@1 - 2": version "2.0.0" resolved "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-2.0.0.tgz#8a18e16f76dd3fcaef42163c97b926aa9b55e7cf" @@ -9228,11 +9378,59 @@ d3-force@^2.0.1: d3-quadtree "1 - 2" d3-timer "1 - 2" +d3-format@1: + version "1.4.5" + resolved "https://registry.npmjs.org/d3-format/-/d3-format-1.4.5.tgz#374f2ba1320e3717eb74a9356c67daee17a7edb4" + integrity sha512-J0piedu6Z8iB6TbIGfZgDzfXxUFN3qQRMofy2oPdXzQibYGqPB/9iMcxr/TGalU+2RsyDO+U4f33id8tbnSRMQ== + +d3-interpolate@1, d3-interpolate@^1.3.0: + version "1.4.0" + resolved "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-1.4.0.tgz#526e79e2d80daa383f9e0c1c1c7dcc0f0583e987" + integrity sha512-V9znK0zc3jOPV4VD2zZn0sDhZU3WAE2bmlxdIwwQPPzPjvyLkd8B3JUVdS1IDUFDkWZ72c9qnv1GK2ZagTZ8EA== + dependencies: + d3-color "1" + +d3-path@1: + version "1.0.9" + resolved "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz#48c050bb1fe8c262493a8caf5524e3e9591701cf" + integrity sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg== + "d3-quadtree@1 - 2": version "2.0.0" resolved "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-2.0.0.tgz#edbad045cef88701f6fee3aee8e93fb332d30f9d" integrity sha512-b0Ed2t1UUalJpc3qXzKi+cPGxeXRr4KU9YSlocN74aTzp6R/Ud43t79yLLqxHRWZfsvWXmbDWPpoENK1K539xw== +d3-scale@^2.1.0: + version "2.2.2" + resolved "https://registry.npmjs.org/d3-scale/-/d3-scale-2.2.2.tgz#4e880e0b2745acaaddd3ede26a9e908a9e17b81f" + integrity sha512-LbeEvGgIb8UMcAa0EATLNX0lelKWGYDQiPdHj+gLblGVhGLyNbaCn3EvrJf0A3Y/uOOU5aD6MTh5ZFCdEwGiCw== + dependencies: + d3-array "^1.2.0" + d3-collection "1" + d3-format "1" + d3-interpolate "1" + d3-time "1" + d3-time-format "2" + +d3-shape@^1.2.0: + version "1.3.7" + resolved "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz#df63801be07bc986bc54f63789b4fe502992b5d7" + integrity sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw== + dependencies: + d3-path "1" + +d3-time-format@2: + version "2.3.0" + resolved "https://registry.npmjs.org/d3-time-format/-/d3-time-format-2.3.0.tgz#107bdc028667788a8924ba040faf1fbccd5a7850" + integrity sha512-guv6b2H37s2Uq/GefleCDtbe0XZAuy7Wa49VGkPVPMfLL9qObgBST3lEHJBMUp8S7NdLQAGIvr2KXk8Hc98iKQ== + dependencies: + d3-time "1" + +d3-time@1: + version "1.1.0" + resolved "https://registry.npmjs.org/d3-time/-/d3-time-1.1.0.tgz#b1e19d307dae9c900b7e5b25ffc5dcc249a8a0f1" + integrity sha512-Xh0isrZ5rPYYdqhAVk8VLnMEidhz5aP7htAADH6MfzgmmicPkTo8LhkLxci61/lCB7n7UmE3bN0leRt+qvkLxA== + "d3-timer@1 - 2": version "2.0.0" resolved "https://registry.npmjs.org/d3-timer/-/d3-timer-2.0.0.tgz#055edb1d170cfe31ab2da8968deee940b56623e6" @@ -9359,6 +9557,11 @@ decamelize@^1.1.0, decamelize@^1.1.1, decamelize@^1.1.2, decamelize@^1.2.0: resolved "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= +decimal.js-light@^2.4.1: + version "2.5.0" + resolved "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.0.tgz#ca7faf504c799326df94b0ab920424fdfc125348" + integrity sha512-b3VJCbd2hwUpeRGG3Toob+CRo8W22xplipNhP3tN7TSVB/cyMX71P1vM2Xjc9H74uV6dS2hDDmo/rHq8L87Upg== + decimal.js@^10.2.0: version "10.2.0" resolved "https://registry.npmjs.org/decimal.js/-/decimal.js-10.2.0.tgz#39466113a9e036111d02f82489b5fd6b0b5ed231" @@ -9766,6 +9969,13 @@ dom-converter@^0.2: dependencies: utila "~0.4" +dom-helpers@^3.4.0: + version "3.4.0" + resolved "https://registry.npmjs.org/dom-helpers/-/dom-helpers-3.4.0.tgz#e9b369700f959f62ecde5a6babde4bccd9169af8" + integrity sha512-LnuPJ+dwqKDIyotW1VzmOZ5TONUN7CwkCR5hrgawTUbkBGYdeoNLZo6nNfGkCrjtE1nXXaj7iMMpDa8/d9WoIA== + dependencies: + "@babel/runtime" "^7.1.2" + dom-helpers@^5.0.0, dom-helpers@^5.0.1: version "5.1.4" resolved "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.1.4.tgz#4609680ab5c79a45f2531441f1949b79d6587f4b" @@ -10220,6 +10430,11 @@ es6-iterator@^2.0.3, es6-iterator@~2.0.3: es5-ext "^0.10.35" es6-symbol "^3.1.1" +es6-object-assign@^1.0.3: + version "1.1.0" + resolved "https://registry.npmjs.org/es6-object-assign/-/es6-object-assign-1.1.0.tgz#c2c3582656247c39ea107cb1e6652b6f9f24523c" + integrity sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw= + es6-promise@^4.0.3: version "4.2.8" resolved "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz#4eb21594c972bc40553d276e510539143db53e0a" @@ -10255,10 +10470,10 @@ es6-weak-map@^2.0.2: es6-iterator "^2.0.3" es6-symbol "^3.1.1" -esbuild@0.6.3: - version "0.6.3" - resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.6.3.tgz#a957e22f2503c745793514388110f9b55b3a6f83" - integrity sha512-4lHgz/EvGLRQnDYzzrvW+eilaPHim5pCLz4mP0k0QIalD/n8Ji2NwQwoIa1uX+yKkbn9R/FAZvaEbodjx55rDg== +esbuild@^0.7.7: + version "0.7.7" + resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.7.7.tgz#fd86332d1c0a047231bd6da930666028c40c14bf" + integrity sha512-1Ub4BBsWwPdxkwjyuXdKrgMIZROZ82ULIRFclOzXXVrqKOv9rMDoShRf23WEbPfeEA94z/BScKyUOyooyQ3XnQ== escalade@^3.0.1: version "3.0.2" @@ -10554,7 +10769,7 @@ estraverse@^5.1.0: resolved "https://registry.npmjs.org/estraverse/-/estraverse-5.1.0.tgz#374309d39fd935ae500e7b92e8a6b4c720e59642" integrity sha512-FyohXK+R0vE+y1nHLoBM7ZTyqRpqAlhdZHCWIWEviFLiGB8b04H6bQs8G+XTthacvT8VuwvteiP7RJSxMs8UEw== -estree-walker@^0.6.0, estree-walker@^0.6.1: +estree-walker@^0.6.1: version "0.6.1" resolved "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz#53049143f40c6eb918b23671d1fe3219f3a1b362" integrity sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w== @@ -10635,6 +10850,19 @@ exec-sh@^0.3.2: resolved "https://registry.npmjs.org/exec-sh/-/exec-sh-0.3.4.tgz#3a018ceb526cc6f6df2bb504b2bfe8e3a4934ec5" integrity sha512-sEFIkc61v75sWeOe72qyrqg2Qg0OuLESziUDk/O/z2qgS15y2gWVFrI6f2Qn/qw/0/NCfCEsmNA4zOjkwEZT1A== +execa@1.0.0, execa@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz#c6236a5bb4df6d6f15e88e7f017798216749ddd8" + integrity sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA== + dependencies: + cross-spawn "^6.0.0" + get-stream "^4.0.0" + is-stream "^1.1.0" + npm-run-path "^2.0.0" + p-finally "^1.0.0" + signal-exit "^3.0.0" + strip-eof "^1.0.0" + execa@3.4.0: version "3.4.0" resolved "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz#c08ed4550ef65d858fac269ffc8572446f37eb89" @@ -10664,19 +10892,6 @@ execa@^0.7.0: signal-exit "^3.0.0" strip-eof "^1.0.0" -execa@^1.0.0: - version "1.0.0" - resolved "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz#c6236a5bb4df6d6f15e88e7f017798216749ddd8" - integrity sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA== - dependencies: - cross-spawn "^6.0.0" - get-stream "^4.0.0" - is-stream "^1.1.0" - npm-run-path "^2.0.0" - p-finally "^1.0.0" - signal-exit "^3.0.0" - strip-eof "^1.0.0" - execa@^4.0.0, execa@^4.0.1: version "4.0.2" resolved "https://registry.npmjs.org/execa/-/execa-4.0.2.tgz#ad87fb7b2d9d564f70d2b62d511bee41d5cbb240" @@ -11149,7 +11364,7 @@ find-cache-dir@^2.0.0, find-cache-dir@^2.1.0: make-dir "^2.0.0" pkg-dir "^3.0.0" -find-cache-dir@^3.2.0, find-cache-dir@^3.3.1: +find-cache-dir@^3.3.1: version "3.3.1" resolved "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.1.tgz#89b33fad4a4670daa94f855f7fbe31d6d84fe880" integrity sha512-t2GDMt3oGC/v+BMwzmllWDuJF/xcDtE5j/fCGbqDD7OLuJkj0cfh1YSA5VKPvwMeLFLNDBkwOKZ2X85jGLVftQ== @@ -11342,7 +11557,7 @@ fork-ts-checker-webpack-plugin@^4.0.5, fork-ts-checker-webpack-plugin@^4.1.4: tapable "^1.0.0" worker-rpc "^0.1.0" -form-data@^2.3.1, form-data@^2.3.2: +form-data@^2.3.1, form-data@^2.3.2, form-data@^2.5.0: version "2.5.1" resolved "https://registry.npmjs.org/form-data/-/form-data-2.5.1.tgz#f2cbec57b5e59e23716e128fe44d4e5dd23895f4" integrity sha512-m21N3WOmEEURgk6B9GLOE4RuWOFf28Lhh9qGYeNlGq4VDXUlJy2th2slBNU8Gp8EzloYZOibZJ7t5ecIrFSjVA== @@ -11500,6 +11715,16 @@ fsevents@^2.1.2, fsevents@~2.1.2: resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.1.2.tgz#4c0a1fb34bc68e543b4b82a9ec392bfbda840805" integrity sha512-R4wDiBwZ0KzpgOWetKDug1FZcYhqYnUYKtfZYt4mD5SBz76q0KR4Q9o7GIPamsVPGmW3EYPPJ0dOOjvx32ldZA== +fstream@^1.0.0, fstream@^1.0.12: + version "1.0.12" + resolved "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz#4e8ba8ee2d48be4f7d0de505455548eae5932045" + integrity sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg== + dependencies: + graceful-fs "^4.1.2" + inherits "~2.0.0" + mkdirp ">=0.5 0" + rimraf "2" + function-bind@^1.1.1: version "1.1.1" resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" @@ -11987,6 +12212,23 @@ got@^11.5.2: p-cancelable "^2.0.0" responselike "^2.0.0" +got@^11.6.2: + version "11.7.0" + resolved "https://registry.npmjs.org/got/-/got-11.7.0.tgz#a386360305571a74548872e674932b4ef70d3b24" + integrity sha512-7en2XwH2MEqOsrK0xaKhbWibBoZqy+f1RSUoIeF1BLcnf+pyQdDsljWMfmOh+QKJwuvDIiKx38GtPh5wFdGGjg== + dependencies: + "@sindresorhus/is" "^3.1.1" + "@szmarczak/http-timer" "^4.0.5" + "@types/cacheable-request" "^6.0.1" + "@types/responselike" "^1.0.0" + cacheable-lookup "^5.0.3" + cacheable-request "^7.0.1" + decompress-response "^6.0.0" + http2-wrapper "^1.0.0-beta.5.2" + lowercase-keys "^2.0.0" + p-cancelable "^2.0.0" + responselike "^2.0.0" + got@^9.6.0: version "9.6.0" resolved "https://registry.npmjs.org/got/-/got-9.6.0.tgz#edf45e7d67f99545705de1f7bbeeeb121765ed85" @@ -12154,7 +12396,7 @@ graphql-upload@^8.0.2: http-errors "^1.7.3" object-path "^0.11.4" -graphql@15.3.0, graphql@^15.0.0, graphql@^15.3.0: +graphql@15.3.0, graphql@^15.3.0: version "15.3.0" resolved "https://registry.npmjs.org/graphql/-/graphql-15.3.0.tgz#3ad2b0caab0d110e3be4a5a9b2aa281e362b5278" integrity sha512-GTCJtzJmkFLWRfFJuoo9RWWa/FfamUHgiFosxi/X1Ani4AVWbeyBenZTNX6dM+7WSbbFfTo/25eh0LLkwHMw2w== @@ -12330,7 +12572,7 @@ he@^1.1.0, he@^1.2.0: resolved "https://registry.npmjs.org/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== -headers-utils@^1.1.9, headers-utils@^1.2.0: +headers-utils@^1.2.0: version "1.2.0" resolved "https://registry.npmjs.org/headers-utils/-/headers-utils-1.2.0.tgz#5e10d1bc9d2bccf789547afca5b991a3167241e8" integrity sha512-4/BMXcWrJErw7JpM87gF8MNEXcIMLzepYZjNRv/P9ctgupl2Ywa3u1PgHtNhSRq84bHH9Ndlkdy7bSi+bZ9I9A== @@ -12891,7 +13133,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@2.0.4, inherits@^2.0.0, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.1, inherits@~2.0.3, inherits@~2.0.4: +inherits@2, inherits@2.0.4, inherits@^2.0.0, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3, inherits@~2.0.4: version "2.0.4" resolved "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -13609,6 +13851,11 @@ isomorphic-form-data@~2.0.0: dependencies: form-data "^2.3.2" +isomorphic-ws@^4.0.1: + version "4.0.1" + resolved "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-4.0.1.tgz#55fd4cd6c5e6491e76dc125938dd863f5cd4f2dc" + integrity sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w== + isstream@~0.1.2: version "0.1.2" resolved "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" @@ -14115,6 +14362,13 @@ jose@^1.27.1: dependencies: "@panva/asn1.js" "^1.0.0" +jose@^2.0.2: + version "2.0.2" + resolved "https://registry.npmjs.org/jose/-/jose-2.0.2.tgz#fb22385b80c658cc7a0cae05b7086c04c6be49f4" + integrity sha512-yD93lsiMA1go/qxSY/vXWBodmIZJIxeB7QhFi8z1yQ3KUwKENqI9UA8VCHlQ5h3x1zWuWZjoY87ByQzkQbIrQg== + dependencies: + "@panva/asn1.js" "^1.0.0" + js-cookie@^2.2.1: version "2.2.1" resolved "https://registry.npmjs.org/js-cookie/-/js-cookie-2.2.1.tgz#69e106dc5d5806894562902aa5baec3744e9b2b8" @@ -14407,15 +14661,20 @@ jsonparse@^1.2.0: resolved "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz#3f4dae4a91fac315f71062f8521cc239f1366280" integrity sha1-P02uSpH6wxX3EGL4UhzCOfE2YoA= +jsonpath-plus@^0.19.0: + version "0.19.0" + resolved "https://registry.npmjs.org/jsonpath-plus/-/jsonpath-plus-0.19.0.tgz#b901e57607055933dc9a8bef0cc25160ee9dd64c" + integrity sha512-GSVwsrzW9LsA5lzsqe4CkuZ9wp+kxBb2GwNniaWzI2YFn5Ig42rSW8ZxVpWXaAfakXNrx5pgY5AbQq7kzX29kg== + jsonpointer@^4.0.1: version "4.0.1" resolved "https://registry.npmjs.org/jsonpointer/-/jsonpointer-4.0.1.tgz#4fd92cb34e0e9db3c89c8622ecf51f9b978c6cb9" integrity sha1-T9kss04OnbPInIYi7PUfm5eMbLk= jsonschema@^1.2.6: - version "1.2.6" - resolved "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.6.tgz#52b0a8e9dc06bbae7295249d03e4b9faee8a0c0b" - integrity sha512-SqhURKZG07JyKKeo/ir24QnS4/BV7a6gQy93bUSe4lUdNp0QNpIz2c9elWJQ9dpc5cQYY6cvCzgRwy0MQCLyqA== + version "1.2.7" + resolved "https://registry.npmjs.org/jsonschema/-/jsonschema-1.2.7.tgz#4e6d6dc4d83dc80707055ba22c00ec6152c0e6e9" + integrity sha512-3dFMg9hmI9LdHag/BRIhMefCfbq1hicvYMy8YhZQorAdzOzWz7NjniSpn39yjpzUAMIWtGyyZuH2KNBloH7ZLw== jsonwebtoken@^8.5.1: version "8.5.1" @@ -14995,7 +15254,7 @@ lodash.clonedeep@^4.5.0: resolved "https://registry.npmjs.org/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef" integrity sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8= -lodash.debounce@^4: +lodash.debounce@^4, lodash.debounce@^4.0.8: version "4.0.8" resolved "https://registry.npmjs.org/lodash.debounce/-/lodash.debounce-4.0.8.tgz#82d79bff30a67c4005ffd5e2515300ad9ca4d7af" integrity sha1-gteb/zCmfEAF/9XiUVMArZyk168= @@ -15090,6 +15349,11 @@ lodash.templatesettings@^4.0.0: dependencies: lodash._reinterpolate "^3.0.0" +lodash.throttle@^4.1.1: + version "4.1.1" + resolved "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz#c23e91b710242ac70c37f1e1cda9274cc39bf2f4" + integrity sha1-wj6RtxAkKscMN/HhzaknTMOb8vQ= + lodash.uniq@^4.5.0: version "4.5.0" resolved "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773" @@ -15105,7 +15369,7 @@ lodash@4.17.15: resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== -lodash@^4.0.1, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.20, lodash@^4.17.4, lodash@^4.2.1: +lodash@^4.0.1, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.20, lodash@^4.17.4, lodash@^4.17.5, lodash@^4.2.1, lodash@~4.17.4: version "4.17.20" resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== @@ -15302,7 +15566,7 @@ make-dir@^3.0.0, make-dir@^3.0.2: dependencies: semver "^6.0.0" -make-error@1.x, make-error@^1.1.1: +make-error@1.x, make-error@^1.1.1, make-error@^1.3.6: version "1.3.6" resolved "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== @@ -15433,6 +15697,11 @@ material-table@1.68.0: react-beautiful-dnd "^13.0.0" react-double-scrollbar "0.0.15" +math-expression-evaluator@^1.2.14: + version "1.2.22" + resolved "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.2.22.tgz#c14dcb3d8b4d150e5dcea9c68c8dad80309b0d5e" + integrity sha512-L0j0tFVZBQQLeEjmWOvDLoRciIY8gQGWahvkztXUal8jH8R5Rlqo9GCvgqvXcy9LQhEWdQCVvzqAbxgYNt4blQ== + md5.js@^1.3.4: version "1.3.5" resolved "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz#b5d07b8e3216e3e27cd728d72f70d1e6a342005f" @@ -15865,7 +16134,7 @@ mkdirp@*, mkdirp@1.x, mkdirp@^1.0.3, mkdirp@^1.0.4: resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@^0.5.3, mkdirp@^0.5.4, mkdirp@^0.5.5, mkdirp@~0.5.1: +"mkdirp@>=0.5 0", mkdirp@^0.5.0, mkdirp@^0.5.1, mkdirp@^0.5.3, mkdirp@^0.5.4, mkdirp@^0.5.5, mkdirp@~0.5.1: version "0.5.5" resolved "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== @@ -15939,22 +16208,6 @@ ms@^2.0.0, ms@^2.1.1: resolved "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== -msw@^0.19.5: - version "0.19.5" - resolved "https://registry.npmjs.org/msw/-/msw-0.19.5.tgz#7d2a1a852ccf1644d3db6735d69fff6777aac33f" - integrity sha512-J5eQ++gDVZoHPC8gVXtWcakLjgmPipvFj/sEnlRV/WViXuiq2CamSqO3Wbh6H8bAmj+k2vUWCfcVT1HjMdKB2Q== - dependencies: - "@open-draft/until" "^1.0.0" - "@types/cookie" "^0.3.3" - chalk "^4.0.0" - cookie "^0.4.1" - graphql "^15.0.0" - headers-utils "^1.1.9" - node-match-path "^0.4.2" - node-request-interceptor "^0.2.5" - statuses "^2.0.0" - yargs "^15.3.1" - msw@^0.20.5: version "0.20.5" resolved "https://registry.npmjs.org/msw/-/msw-0.20.5.tgz#b6141080c0d8b17c451d9ca36c28cc47b4ac487a" @@ -16102,6 +16355,11 @@ no-case@^3.0.3: lower-case "^2.0.1" tslib "^1.10.0" +node-addon-api@2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/node-addon-api/-/node-addon-api-2.0.0.tgz#f9afb8d777a91525244b01775ea0ddbe1125483b" + integrity sha512-ASCL5U13as7HhOExbT6OlWJJUV/lLzL2voOSP1UVehpRD8FbSrSDjfScK/KwAvVTI5AS6r4VwbOMlIqtvRidnA== + node-dir@^0.1.10: version "0.1.17" resolved "https://registry.npmjs.org/node-dir/-/node-dir-0.1.17.tgz#5f5665d93351335caabef8f1c554516cf5f1e4e5" @@ -16131,7 +16389,7 @@ node-fetch@^1.0.1: encoding "^0.1.11" is-stream "^1.0.1" -node-fetch@^2.1.2, node-fetch@^2.2.0, node-fetch@^2.3.0, node-fetch@^2.5.0, node-fetch@^2.6.0: +node-fetch@^2.1.2, node-fetch@^2.2.0, node-fetch@^2.3.0, node-fetch@^2.5.0, node-fetch@^2.6.0, node-fetch@^2.6.1: version "2.6.1" resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052" integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw== @@ -16146,6 +16404,24 @@ node-forge@^0.7.0: resolved "https://registry.npmjs.org/node-forge/-/node-forge-0.7.6.tgz#fdf3b418aee1f94f0ef642cd63486c77ca9724ac" integrity sha512-sol30LUpz1jQFBjOKwbjxijiE3b6pjd74YwfD0fJOKPjF+fONKb2Yg8rYgS6+bK6VDl+/wfr4IYpC7jDzLUIfw== +node-gyp@3.x: + version "3.8.0" + resolved "https://registry.npmjs.org/node-gyp/-/node-gyp-3.8.0.tgz#540304261c330e80d0d5edce253a68cb3964218c" + integrity sha512-3g8lYefrRRzvGeSowdJKAKyks8oUpLEd/DyPV4eMhVlhJ0aNaZqIrNUIPuEWWTAoPqyFkfGrM67MC69baqn6vA== + dependencies: + fstream "^1.0.0" + glob "^7.0.3" + graceful-fs "^4.1.2" + mkdirp "^0.5.0" + nopt "2 || 3" + npmlog "0 || 1 || 2 || 3 || 4" + osenv "0" + request "^2.87.0" + rimraf "2" + semver "~5.3.0" + tar "^2.0.0" + which "1" + node-gyp@^4.0.0: version "4.0.0" resolved "https://registry.npmjs.org/node-gyp/-/node-gyp-4.0.0.tgz#972654af4e5dd0cd2a19081b4b46fe0442ba6f45" @@ -16214,7 +16490,7 @@ node-libs-browser@^2.2.1: util "^0.11.0" vm-browserify "^1.0.1" -node-match-path@^0.4.2, node-match-path@^0.4.4: +node-match-path@^0.4.4: version "0.4.4" resolved "https://registry.npmjs.org/node-match-path/-/node-match-path-0.4.4.tgz#516a10926093c0cc6f237d020685b593b19baebb" integrity sha512-pBq9gp7TG0r0VXuy/oeZmQsjBSnYQo7G886Ly/B3azRwZuEtHCY155dzmfoKWcDPGgyfIGD8WKVC7h3+6y7yTg== @@ -16273,14 +16549,6 @@ node-releases@^1.1.52, node-releases@^1.1.58: resolved "https://registry.npmjs.org/node-releases/-/node-releases-1.1.60.tgz#6948bdfce8286f0b5d0e5a88e8384e954dfe7084" integrity sha512-gsO4vjEdQaTusZAEebUWp2a5d7dF5DYoIpDG7WySnk7BuZDW+GPpHXoXXuYawRBr/9t5q54tirPz79kFIWg4dA== -node-request-interceptor@^0.2.5: - version "0.2.6" - resolved "https://registry.npmjs.org/node-request-interceptor/-/node-request-interceptor-0.2.6.tgz#541278d7033bb6a8befb5dd793f83428cf6446a2" - integrity sha512-aJW1tPSM7nzuZFRe+C/KSz22GJO3CVFMxHHmMGX8Z+tjP7TCIVbzeckLFVfJG68BdVgrdOOP7Ejc57ag820eyA== - dependencies: - debug "^4.1.1" - headers-utils "^1.2.0" - node-request-interceptor@^0.3.5: version "0.3.5" resolved "https://registry.npmjs.org/node-request-interceptor/-/node-request-interceptor-0.3.5.tgz#4b26159617829c9a70643012c0fdc3ae4c78ae43" @@ -16529,6 +16797,11 @@ object-copy@^0.1.0: define-property "^0.2.5" kind-of "^3.0.3" +object-hash@^2.0.1: + version "2.0.3" + resolved "https://registry.npmjs.org/object-hash/-/object-hash-2.0.3.tgz#d12db044e03cd2ca3d77c0570d87225b02e1e6ea" + integrity sha512-JPKn0GMu+Fa3zt3Bmr66JhokJU5BaNBIh4ZeTlaCBzrBsOeXzwcKKAK1tbLiPKgvwmPXsDvvLHoWh5Bm7ofIYg== + object-inspect@^1.7.0: version "1.7.0" resolved "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz#f4f6bd181ad77f006b5ece60bd0b6f398ff74a67" @@ -16644,6 +16917,11 @@ octokit-pagination-methods@^1.1.0: resolved "https://registry.npmjs.org/octokit-pagination-methods/-/octokit-pagination-methods-1.1.0.tgz#cf472edc9d551055f9ef73f6e42b4dbb4c80bea4" integrity sha512-fZ4qZdQ2nxJvtcasX7Ghl+WlWS/d9IgnBIwFZXVNNZUmzpno91SX5bc5vuxiuKoCtK78XxGGNuSCrDC7xYB3OQ== +oidc-token-hash@^5.0.0: + version "5.0.0" + resolved "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.0.0.tgz#acdfb1f4310f58e64d5d74a4e8671a426986e888" + integrity sha512-8Yr4CZSv+Tn8ZkN3iN2i2w2G92mUKClp4z7EGUfdsERiYSbj7P4i/NHm72ft+aUdsiFx9UdIPSTwbyzQ6C4URg== + omggif@1.0.7: version "1.0.7" resolved "https://registry.npmjs.org/omggif/-/omggif-1.0.7.tgz#59d2eecb0263de84635b3feb887c0c9973f1e49d" @@ -16712,6 +16990,20 @@ opencollective-postinstall@^2.0.2: resolved "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.2.tgz#5657f1bede69b6e33a45939b061eb53d3c6c3a89" integrity sha512-pVOEP16TrAO2/fjej1IdOyupJY8KDUM1CvsaScRbw6oddvpQoOfGk4ywha0HKKVAD6RkW4x6Q+tNBwhf3Bgpuw== +openid-client@^4.1.1: + version "4.1.1" + resolved "https://registry.npmjs.org/openid-client/-/openid-client-4.1.1.tgz#3e8a25584c4292e9b9b03e60358f5549fb85197a" + integrity sha512-/qch3I3v8UtO0A7wVgyXJJjGX/knR8bv06DQpLuKQqLG5u4AHcgusGuVKPKAcneLZvHKbKovF2+3e2ngXyuudA== + dependencies: + base64url "^3.0.1" + got "^11.6.2" + jose "^2.0.2" + lru-cache "^6.0.0" + make-error "^1.3.6" + object-hash "^2.0.1" + oidc-token-hash "^5.0.0" + p-any "^3.0.0" + opn@^5.5.0: version "5.5.0" resolved "https://registry.npmjs.org/opn/-/opn-5.5.0.tgz#fc7164fab56d235904c51c3b27da6758ca3b9bfc" @@ -16817,6 +17109,14 @@ overlayscrollbars@^1.10.2: resolved "https://registry.npmjs.org/overlayscrollbars/-/overlayscrollbars-1.13.0.tgz#1edb436328133b94877b558f77966d5497ca36a7" integrity sha512-p8oHrMeRAKxXDMPI/EBNITj/zTVHKNnAnM59Im+xnoZUlV07FyTg46wom2286jJlXGGfcPFG/ba5NUiCwWNd4w== +p-any@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/p-any/-/p-any-3.0.0.tgz#79847aeed70b5d3a10ea625296c0c3d2e90a87b9" + integrity sha512-5rqbqfsRWNb0sukt0awwgJMlaep+8jV45S15SKKB34z4UuzjcofIfnriCBhWjZP2jbVtjt9yRl7buB6RlKsu9w== + dependencies: + p-cancelable "^2.0.0" + p-some "^5.0.0" + p-cancelable@^1.0.0: version "1.1.0" resolved "https://registry.npmjs.org/p-cancelable/-/p-cancelable-1.1.0.tgz#d078d15a3af409220c886f1d9a0ca2e441ab26cc" @@ -16963,6 +17263,14 @@ p-retry@^3.0.1: dependencies: retry "^0.12.0" +p-some@^5.0.0: + version "5.0.0" + resolved "https://registry.npmjs.org/p-some/-/p-some-5.0.0.tgz#8b730c74b4fe5169d7264a240ad010b6ebc686a4" + integrity sha512-Js5XZxo6vHjB9NOYAzWDYAIyyiPvva0DWESAIWIK7uhSpGsyg5FwUPxipU/SOQx5x9EqhOh545d1jo6cVkitig== + dependencies: + aggregate-error "^3.0.0" + p-cancelable "^2.0.0" + p-timeout@^3.1.0: version "3.2.0" resolved "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz#c7e17abc971d2a7962ef83626b35d635acf23dfe" @@ -18428,7 +18736,7 @@ qs@6.7.0: resolved "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz#41dc1a015e3d581f1621776be31afb2876a9b1bc" integrity sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ== -qs@^6.5.1, qs@^6.6.0, qs@^6.9.4: +qs@^6.5.1, qs@^6.6.0, qs@^6.9.1, qs@^6.9.4: version "6.9.4" resolved "https://registry.npmjs.org/qs/-/qs-6.9.4.tgz#9090b290d1f91728d3c22e54843ca44aea5ab687" integrity sha512-A1kFqHekCTM7cz0udomYUoYNWjBebHm/5wzU/XqrBRBNWectVH0QIiN+NEcZ0Dte5hvzHwbr8+XQmguPhJ6WdQ== @@ -18495,7 +18803,7 @@ raf-schd@^4.0.2: resolved "https://registry.npmjs.org/raf-schd/-/raf-schd-4.0.2.tgz#bd44c708188f2e84c810bf55fcea9231bcaed8a0" integrity sha512-VhlMZmGy6A6hrkJWHLNTGl5gtgMUm+xfGza6wbwnE914yeQ5Ybm18vgM734RZhMgfw4tacUrWseGZlpUrrakEQ== -raf@^3.1.0, raf@^3.4.1: +raf@^3.1.0, raf@^3.4.0, raf@^3.4.1: version "3.4.1" resolved "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz#0742e99a4a6552f445d73e3ee0328af0ff1ede39" integrity sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA== @@ -18918,6 +19226,16 @@ react-redux@^7.1.1: prop-types "^15.7.2" react-is "^16.9.0" +react-resize-detector@^2.3.0: + version "2.3.0" + resolved "https://registry.npmjs.org/react-resize-detector/-/react-resize-detector-2.3.0.tgz#57bad1ae26a28a62a2ddb678ba6ffdf8fa2b599c" + integrity sha512-oCAddEWWeFWYH5FAcHdBYcZjAw9fMzRUK9sWSx6WvSSOPVRxcHd5zTIGy/mOus+AhN/u6T4TMiWxvq79PywnJQ== + dependencies: + lodash.debounce "^4.0.8" + lodash.throttle "^4.1.1" + prop-types "^15.6.0" + resize-observer-polyfill "^1.5.0" + react-router-dom@6.0.0-beta.0: version "6.0.0-beta.0" resolved "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.0.0-beta.0.tgz#9dcc8555365f22f7fbd09f26b6b82543f3eb97d6" @@ -18977,6 +19295,16 @@ react-sizeme@^2.6.7: shallowequal "^1.1.0" throttle-debounce "^2.1.0" +react-smooth@^1.0.5: + version "1.0.5" + resolved "https://registry.npmjs.org/react-smooth/-/react-smooth-1.0.5.tgz#94ae161d7951cdd893ccb7099d031d342cb762ad" + integrity sha512-eW057HT0lFgCKh8ilr0y2JaH2YbNcuEdFpxyg7Gf/qDKk9hqGMyXryZJ8iMGJEuKH0+wxS0ccSsBBB3W8yCn8w== + dependencies: + lodash "~4.17.4" + prop-types "^15.6.0" + raf "^3.4.0" + react-transition-group "^2.5.0" + react-sparklines@^1.7.0: version "1.7.0" resolved "https://registry.npmjs.org/react-sparklines/-/react-sparklines-1.7.0.tgz#9b1d97e8c8610095eeb2ad658d2e1fcf91f91a60" @@ -19032,6 +19360,16 @@ react-textarea-autosize@^8.1.1: use-composed-ref "^1.0.0" use-latest "^1.0.0" +react-transition-group@^2.5.0: + version "2.9.0" + resolved "https://registry.npmjs.org/react-transition-group/-/react-transition-group-2.9.0.tgz#df9cdb025796211151a436c69a8f3b97b5b07c8d" + integrity sha512-+HzNTCHpeQyl4MJ/bdE0u6XRMe9+XG/+aL4mCxVN4DnPBQ0/5bfHWPDuOZUzYdMj94daZaZdCCc1Dzt9R/xSSg== + dependencies: + dom-helpers "^3.4.0" + loose-envify "^1.4.0" + prop-types "^15.6.2" + react-lifecycles-compat "^3.0.4" + react-transition-group@^4.0.0, react-transition-group@^4.4.0: version "4.4.1" resolved "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.1.tgz#63868f9325a38ea5ee9535d828327f85773345c9" @@ -19299,6 +19637,30 @@ recast@^0.14.7: private "~0.1.5" source-map "~0.6.1" +recharts-scale@^0.4.2: + version "0.4.3" + resolved "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.3.tgz#040b4f638ed687a530357292ecac880578384b59" + integrity sha512-t8p5sccG9Blm7c1JQK/ak9O8o95WGhNXD7TXg/BW5bYbVlr6eCeRBNpgyigD4p6pSSMehC5nSvBUPj6F68rbFA== + dependencies: + decimal.js-light "^2.4.1" + +recharts@^1.8.5: + version "1.8.5" + resolved "https://registry.npmjs.org/recharts/-/recharts-1.8.5.tgz#ca94a3395550946334a802e35004ceb2583fdb12" + integrity sha512-tM9mprJbXVEBxjM7zHsIy6Cc41oO/pVYqyAsOHLxlJrbNBuLs0PHB3iys2M+RqCF0//k8nJtZF6X6swSkWY3tg== + dependencies: + classnames "^2.2.5" + core-js "^2.6.10" + d3-interpolate "^1.3.0" + d3-scale "^2.1.0" + d3-shape "^1.2.0" + lodash "^4.17.5" + prop-types "^15.6.0" + react-resize-detector "^2.3.0" + react-smooth "^1.0.5" + recharts-scale "^0.4.2" + reduce-css-calc "^1.3.0" + rechoir@^0.6.2: version "0.6.2" resolved "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" @@ -19337,6 +19699,22 @@ redent@^3.0.0: indent-string "^4.0.0" strip-indent "^3.0.0" +reduce-css-calc@^1.3.0: + version "1.3.0" + resolved "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-1.3.0.tgz#747c914e049614a4c9cfbba629871ad1d2927716" + integrity sha1-dHyRTgSWFKTJz7umKYca0dKSdxY= + dependencies: + balanced-match "^0.4.2" + math-expression-evaluator "^1.2.14" + reduce-function-call "^1.0.1" + +reduce-function-call@^1.0.1: + version "1.0.3" + resolved "https://registry.npmjs.org/reduce-function-call/-/reduce-function-call-1.0.3.tgz#60350f7fb252c0a67eb10fd4694d16909971300f" + integrity sha512-Hl/tuV2VDgWgCSEeWMLwxLZqX7OK59eU1guxXsRKTAyeYimivsKdtcV4fu3r710tpG5GmDKDhQ0HSZLExnNmyQ== + dependencies: + balanced-match "^1.0.0" + redux-immutable@3.1.0: version "3.1.0" resolved "https://registry.npmjs.org/redux-immutable/-/redux-immutable-3.1.0.tgz#cafbd686e0711261119b9c28960935dc47a49d0a" @@ -19664,7 +20042,7 @@ reselect@^4.0.0: resolved "https://registry.npmjs.org/reselect/-/reselect-4.0.0.tgz#f2529830e5d3d0e021408b246a206ef4ea4437f7" integrity sha512-qUgANli03jjAyGlnbYVAV5vvnOmJnODyABz51RdBN7M4WaVu8mecZWgyQNkG8Yqe3KRGRt0l4K4B3XVEULC4CA== -resize-observer-polyfill@^1.5.1: +resize-observer-polyfill@^1.5.0, resize-observer-polyfill@^1.5.1: version "1.5.1" resolved "https://registry.npmjs.org/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz#0e9020dd3d21024458d4ebd27e23e40269810464" integrity sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg== @@ -19721,14 +20099,7 @@ resolve-url@^0.2.1: resolved "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= -resolve@1.15.1: - version "1.15.1" - resolved "https://registry.npmjs.org/resolve/-/resolve-1.15.1.tgz#27bdcdeffeaf2d6244b95bb0f9f4b4653451f3e8" - integrity sha512-84oo6ZTtoTUpjgNEr5SJyzQhzL72gaRodsSfyxC/AXRvwu0Yse9H8eF9IpGo7b8YetZhlI6v7ZQ6bKBFV/6S7w== - dependencies: - path-parse "^1.0.6" - -resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.11.0, resolve@^1.12.0, resolve@^1.13.1, resolve@^1.15.1, resolve@^1.16.1, resolve@^1.17.0, resolve@^1.3.2: +resolve@1.17.0, resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.11.0, resolve@^1.12.0, resolve@^1.13.1, resolve@^1.15.1, resolve@^1.16.1, resolve@^1.17.0, resolve@^1.3.2: version "1.17.0" resolved "https://registry.npmjs.org/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== @@ -19793,6 +20164,11 @@ reusify@^1.0.4: resolved "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz#90da382b1e126efc02146e90845a88db12925d76" integrity sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw== +rfc4648@^1.3.0: + version "1.4.0" + resolved "https://registry.npmjs.org/rfc4648/-/rfc4648-1.4.0.tgz#c75b2856ad2e2d588b6ddb985d556f1f7f2a2abd" + integrity sha512-3qIzGhHlMHA6PoT6+cdPKZ+ZqtxkIvg8DZGKA5z6PQ33/uuhoJ+Ws/D/J9rXW6gXodgH8QYlz2UCl+sdUDmNIg== + rgb-regex@^1.0.1: version "1.0.1" resolved "https://registry.npmjs.org/rgb-regex/-/rgb-regex-1.0.1.tgz#c0e0d6882df0e23be254a475e8edd41915feaeb1" @@ -19858,14 +20234,6 @@ rollup-plugin-esbuild@^2.0.0: dependencies: "@rollup/pluginutils" "^3.1.0" -rollup-plugin-image-files@^1.4.2: - version "1.4.2" - resolved "https://registry.npmjs.org/rollup-plugin-image-files/-/rollup-plugin-image-files-1.4.2.tgz#0a329723bace95168a9a6efdacb51370c14fbfe5" - integrity sha512-tlydpQdGFssMWhPdWA9SFh4IGVSCzceNgJarJDID+km151IeIVzjATl8ZERNGS/QwMty25iammQqauxl1VUqDQ== - dependencies: - rollup "0.64.1" - rollup-pluginutils "2.4.1" - rollup-plugin-peer-deps-external@^2.2.2: version "2.2.3" resolved "https://registry.npmjs.org/rollup-plugin-peer-deps-external/-/rollup-plugin-peer-deps-external-2.2.3.tgz#059a8aec1eefb48a475e9fcedc3b9e3deb521213" @@ -19891,40 +20259,24 @@ rollup-plugin-postcss@^3.1.1: safe-identifier "^0.4.1" style-inject "^0.3.0" -rollup-plugin-typescript2@^0.26.0: - version "0.26.0" - resolved "https://registry.npmjs.org/rollup-plugin-typescript2/-/rollup-plugin-typescript2-0.26.0.tgz#cee2b44d51d9623686656d76dc30a73c4de91672" - integrity sha512-lUK7XZVG77tu8dmv1L/0LZFlavED/5Yo6e4iMMl6fdox/yKdj4IFRRPPJEXNdmEaT1nDQQeCi7b5IwKHffMNeg== +rollup-plugin-typescript2@^0.27.3: + version "0.27.3" + resolved "https://registry.npmjs.org/rollup-plugin-typescript2/-/rollup-plugin-typescript2-0.27.3.tgz#cd9455ac026d325b20c5728d2cc54a08a771b68b" + integrity sha512-gmYPIFmALj9D3Ga1ZbTZAKTXq1JKlTQBtj299DXhqYz9cL3g/AQfUvbb2UhH+Nf++cCq941W2Mv7UcrcgLzJJg== dependencies: - find-cache-dir "^3.2.0" + "@rollup/pluginutils" "^3.1.0" + find-cache-dir "^3.3.1" fs-extra "8.1.0" - resolve "1.15.1" - rollup-pluginutils "2.8.2" - tslib "1.10.0" + resolve "1.17.0" + tslib "2.0.1" -rollup-pluginutils@2.4.1: - version "2.4.1" - resolved "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.4.1.tgz#de43ab54965bbf47843599a7f3adceb723de38db" - integrity sha512-wesMQ9/172IJDIW/lYWm0vW0LiKe5Ekjws481R7z9WTRtmO59cqyM/2uUlxvf6yzm/fElFmHUobeQOYz46dZJw== - dependencies: - estree-walker "^0.6.0" - micromatch "^3.1.10" - -rollup-pluginutils@2.8.2, rollup-pluginutils@^2.8.2: +rollup-pluginutils@^2.8.2: version "2.8.2" resolved "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz#72f2af0748b592364dbd3389e600e5a9444a351e" integrity sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ== dependencies: estree-walker "^0.6.1" -rollup@0.64.1: - version "0.64.1" - resolved "https://registry.npmjs.org/rollup/-/rollup-0.64.1.tgz#9188ee368e5fcd43ffbc00ec414e72eeb5de87ba" - integrity sha512-+ThdVXrvonJdOTzyybMBipP0uz605Z8AnzWVY3rf+cSGnLO7uNkJBlN+9jXqWOomkvumXfm/esmBpA5d53qm7g== - dependencies: - "@types/estree" "0.0.39" - "@types/node" "*" - rollup@2.23.x: version "2.23.0" resolved "https://registry.npmjs.org/rollup/-/rollup-2.23.0.tgz#b7ab1fee0c0e60132fd0553c4df1e9cdacfada9d" @@ -20332,7 +20684,7 @@ shell-quote@1.7.2: resolved "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.2.tgz#67a7d02c76c9da24f99d20808fcaded0e0e04be2" integrity sha512-mRz/m/JVscCrkMyPqHc/bczi3OQHkLTqXHEFu0zDhK/qfv3UcOA4SVmRCLmos4bhjr9ekVQubj/R7waKapmiQg== -shelljs@^0.8.3: +shelljs@^0.8.1, shelljs@^0.8.2, shelljs@^0.8.3: version "0.8.4" resolved "https://registry.npmjs.org/shelljs/-/shelljs-0.8.4.tgz#de7684feeb767f8716b326078a8a00875890e3c2" integrity sha512-7gk3UZ9kOfPLIAbslLzyWeGiEqx9e3rxwZM0KE6EL8GlGwjym9Mrlx5/p33bWTu9YG6vcS4MBxYZDHYr5lr8BQ== @@ -20353,6 +20705,15 @@ shortid@^2.2.14: dependencies: nanoid "^2.1.0" +shx@^0.3.2: + version "0.3.2" + resolved "https://registry.npmjs.org/shx/-/shx-0.3.2.tgz#40501ce14eb5e0cbcac7ddbd4b325563aad8c123" + integrity sha512-aS0mWtW3T2sHAenrSrip2XGv39O9dXIFUqxAEWHEOS1ePtGIBavdPJY1kE2IHl14V/4iCbUiNDPGdyYTtmhSoA== + dependencies: + es6-object-assign "^1.0.3" + minimist "^1.2.0" + shelljs "^0.8.1" + side-channel@^1.0.2: version "1.0.2" resolved "https://registry.npmjs.org/side-channel/-/side-channel-1.0.2.tgz#df5d1abadb4e4bf4af1cd8852bf132d2f7876947" @@ -20710,13 +21071,15 @@ sprintf-js@~1.0.2: resolved "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= -sqlite3@^4.2.0: - version "4.2.0" - resolved "https://registry.npmjs.org/sqlite3/-/sqlite3-4.2.0.tgz#49026d665e9fc4f922e56fb9711ba5b4c85c4901" - integrity sha512-roEOz41hxui2Q7uYnWsjMOTry6TcNUNmp8audCx18gF10P2NknwdpF+E+HKvz/F2NvPKGGBF4NGc+ZPQ+AABwg== +sqlite3@^5.0.0: + version "5.0.0" + resolved "https://registry.npmjs.org/sqlite3/-/sqlite3-5.0.0.tgz#1bfef2151c6bc48a3ab1a6c126088bb8dd233566" + integrity sha512-rjvqHFUaSGnzxDy2AHCwhHy6Zp6MNJzCPGYju4kD8yi6bze4d1/zMTg6C7JI49b7/EM7jKMTvyfN/4ylBKdwfw== dependencies: - nan "^2.12.1" + node-addon-api "2.0.0" node-pre-gyp "^0.11.0" + optionalDependencies: + node-gyp "3.x" srcset@^2.0.1: version "2.0.1" @@ -20881,9 +21244,9 @@ store2@^2.7.1: integrity sha512-tWEpK0snS2RPUq1i3R6OahfJNjWCQYNxq0+by1amCSuw0mXtymJpzmZIeYpA1UAa+7B0grCpNYIbDcd7AgTbFg== storybook-dark-mode@^1.0.2: - version "1.0.2" - resolved "https://registry.npmjs.org/storybook-dark-mode/-/storybook-dark-mode-1.0.2.tgz#963007e72b628e0efe29bdc5ee8449513bc056b8" - integrity sha512-HBeXTUzYaRgdGJ6YbmcJ3RXw47xp2b5kegZwtcqnSvRblNUZlAKSKsD6UQTWA30hPJ+u3O/5OE5bXk8+H4Zdqg== + version "1.0.3" + resolved "https://registry.npmjs.org/storybook-dark-mode/-/storybook-dark-mode-1.0.3.tgz#8d58a874b6107ff1a7f29ebb0e6726b8036eee08" + integrity sha512-mjHLrv/dwtqKmbOoQ2CMtGKDttWSnUybutujsIPxLcEC77EujjWiRBFv46LtXAZEyZLm8sGFUz0s6HJJfJ3tSw== dependencies: fast-deep-equal "^3.0.0" memoizerific "^1.11.3" @@ -20896,6 +21259,11 @@ stream-browserify@^2.0.1: inherits "~2.0.1" readable-stream "^2.0.2" +stream-buffers@^3.0.2: + version "3.0.2" + resolved "https://registry.npmjs.org/stream-buffers/-/stream-buffers-3.0.2.tgz#5249005a8d5c2d00b3a32e6e0a6ea209dc4f3521" + integrity sha512-DQi1h8VEBA/lURbSwFtEHnSTb9s2/pwLEaFuNhXwy1Dx3Sa0lOuYT2yNUr4/j2fs8oCAMANtrZ5OrPZtyVs3MQ== + stream-combiner@~0.0.4: version "0.0.4" resolved "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14" @@ -21483,6 +21851,15 @@ tar-stream@^2.0.0: inherits "^2.0.3" readable-stream "^3.1.1" +tar@^2.0.0: + version "2.2.2" + resolved "https://registry.npmjs.org/tar/-/tar-2.2.2.tgz#0ca8848562c7299b8b446ff6a4d60cdbb23edc40" + integrity sha512-FCEhQ/4rE1zYv9rYXJw/msRqsnmlje5jHP6huWeBZ704jUTy02c5AZyWujpMR1ax6mVw9NyJMfuK2CMDWVIfgA== + dependencies: + block-stream "*" + fstream "^1.0.12" + inherits "2" + tar@^4, tar@^4.4.10, tar@^4.4.12, tar@^4.4.8: version "4.4.13" resolved "https://registry.npmjs.org/tar/-/tar-4.4.13.tgz#43b364bc52888d555298637b10d60790254ab525" @@ -21760,6 +22137,13 @@ tinycolor2@^1.4.1: resolved "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.4.1.tgz#f4fad333447bc0b07d4dc8e9209d8f39a8ac77e8" integrity sha1-9PrTM0R7wLB9TcjpIJ2POaisd+g= +tmp-promise@^3.0.2: + version "3.0.2" + resolved "https://registry.npmjs.org/tmp-promise/-/tmp-promise-3.0.2.tgz#6e933782abff8b00c3119d63589ca1fb9caaa62a" + integrity sha512-OyCLAKU1HzBjL6Ev3gxUeraJNlbNingmi8IrHHEsYH8LTmEuhvYfqvhn2F/je+mjf4N58UmZ96OMEy1JanSCpA== + dependencies: + tmp "^0.2.0" + tmp@^0.0.33: version "0.0.33" resolved "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz#6d34335889768d21b2bcda0aa277ced3b1bfadf9" @@ -21767,6 +22151,13 @@ tmp@^0.0.33: dependencies: os-tmpdir "~1.0.2" +tmp@^0.2.0: + version "0.2.1" + resolved "https://registry.npmjs.org/tmp/-/tmp-0.2.1.tgz#8457fc3037dcf4719c251367a1af6500ee1ccf14" + integrity sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ== + dependencies: + rimraf "^3.0.0" + tmp@~0.1.0: version "0.1.0" resolved "https://registry.npmjs.org/tmp/-/tmp-0.1.0.tgz#ee434a4e22543082e294ba6201dcc6eafefa2877" @@ -22034,22 +22425,22 @@ tsconfig-paths@^3.9.0: minimist "^1.2.0" strip-bom "^3.0.0" -tslib@1.10.0: - version "1.10.0" - resolved "https://registry.npmjs.org/tslib/-/tslib-1.10.0.tgz#c3c19f95973fb0a62973fb09d90d961ee43e5c8a" - integrity sha512-qOebF53frne81cf0S9B41ByenJ3/IuH8yJKngAX35CmiZySA0khhkovshKK+jGCaMnVomla7gVlIcc3EvKPbTQ== - -tslib@1.11.1, tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: +tslib@1.11.1: version "1.11.1" resolved "https://registry.npmjs.org/tslib/-/tslib-1.11.1.tgz#eb15d128827fbee2841549e171f45ed338ac7e35" integrity sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA== -tslib@2.0.0, tslib@^2.0.0, tslib@~2.0.0: +tslib@2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/tslib/-/tslib-2.0.0.tgz#18d13fc2dce04051e20f074cc8387fd8089ce4f3" integrity sha512-lTqkx847PI7xEDYJntxZH89L2/aXInsyF2luSafe/+0fHOMjlBNXdH6th7f70qxLDhul7KZK0zC8V5ZIyHl0/g== -tslib@^1.11.1: +tslib@2.0.1, tslib@^2.0.0, tslib@~2.0.0: + version "2.0.1" + resolved "https://registry.npmjs.org/tslib/-/tslib-2.0.1.tgz#410eb0d113e5b6356490eec749603725b021b43e" + integrity sha512-SgIkNheinmEBgx1IUNirK0TUD4X9yjjBRTqqjggWCU3pUEqIk3/Uwl3yRixYKT6WjQuGiwDv4NomL3wqRCj+CQ== + +tslib@^1.10.0, tslib@^1.11.1, tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: version "1.13.0" resolved "https://registry.npmjs.org/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043" integrity sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q== @@ -22085,6 +22476,11 @@ tunnel-agent@^0.6.0: dependencies: safe-buffer "^5.0.1" +tunnel@0.0.6: + version "0.0.6" + resolved "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c" + integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg== + tweetnacl@^0.14.3, tweetnacl@~0.14.0: version "0.14.5" resolved "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" @@ -22152,6 +22548,15 @@ type@^2.0.0: resolved "https://registry.npmjs.org/type/-/type-2.0.0.tgz#5f16ff6ef2eb44f260494dae271033b29c09a9c3" integrity sha512-KBt58xCHry4Cejnc2ISQAF7QY+ORngsWfxezO68+12hKV6lQY8P/psIkcbjeHWn7MqcgciWJyCCevFMJdIXpow== +typed-rest-client@^1.7.3: + version "1.7.3" + resolved "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.7.3.tgz#1beb263b86b14d34596f6127c6172dd5fd652e7b" + integrity sha512-CwTpx/TkRHGZoHkJhBcp4X8K3/WtlzSHVQR0OIFnt10j4tgy4ypgq/SrrgVpA1s6tAL49Q6J3R5C0Cgfh2ddqA== + dependencies: + qs "^6.9.1" + tunnel "0.0.6" + underscore "1.8.3" + typed-styles@^0.0.7: version "0.0.7" resolved "https://registry.npmjs.org/typed-styles/-/typed-styles-0.0.7.tgz#93392a008794c4595119ff62dde6809dbc40a3d9" @@ -22219,6 +22624,16 @@ undefsafe@^2.0.2: dependencies: debug "^2.2.0" +underscore@1.8.3: + version "1.8.3" + resolved "https://registry.npmjs.org/underscore/-/underscore-1.8.3.tgz#4f3fb53b106e6097fcf9cb4109f2a5e9bdfa5022" + integrity sha1-Tz+1OxBuYJf8+ctBCfKl6b36UCI= + +underscore@^1.9.1: + version "1.11.0" + resolved "https://registry.npmjs.org/underscore/-/underscore-1.11.0.tgz#dd7c23a195db34267186044649870ff1bab5929e" + integrity sha512-xY96SsN3NA461qIRKZ/+qox37YXPtSBswMGfiNptr+wrt6ds4HaMw23TP612fEyGekRE6LNRiLYr/aqbHXNedw== + unfetch@^4.1.0: version "4.1.0" resolved "https://registry.npmjs.org/unfetch/-/unfetch-4.1.0.tgz#6ec2dd0de887e58a4dee83a050ded80ffc4137db" @@ -22358,6 +22773,11 @@ universal-user-agent@^5.0.0: dependencies: os-name "^3.1.0" +universal-user-agent@^6.0.0: + version "6.0.0" + resolved "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee" + integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w== + universalify@^0.1.0: version "0.1.2" resolved "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" @@ -23272,6 +23692,11 @@ ws@^7.2.3: resolved "https://registry.npmjs.org/ws/-/ws-7.3.0.tgz#4b2f7f219b3d3737bc1a2fbf145d825b94d38ffd" integrity sha512-iFtXzngZVXPGgpTlP1rBqsUK82p9tKqsWRPg5L56egiljujJT3vGAYnHANvFxBieXrTFavhzhxW52jnaWV+w2w== +ws@^7.3.1: + version "7.3.1" + resolved "https://registry.npmjs.org/ws/-/ws-7.3.1.tgz#d0547bf67f7ce4f12a72dfe31262c68d7dc551c8" + integrity sha512-D3RuNkynyHmEJIpD2qrgVkc9DQ23OrN/moAwZX4L8DfvszsJxpjQuUq3LMx6HoYji9fbIOBY18XWBsAux1ZZUA== + x-is-string@^0.1.0: version "0.1.0" resolved "https://registry.npmjs.org/x-is-string/-/x-is-string-0.1.0.tgz#474b50865af3a49a9c4657f05acd145458f77d82"