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/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/.github/CODEOWNERS b/.github/CODEOWNERS index de0655cdbc..0aebb18a41 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,6 +6,7 @@ * @spotify/backstage-core /docs/features/techdocs @spotify/techdocs-core +/plugins/cost-insights @spotify/silver-lining /plugins/techdocs @spotify/techdocs-core /plugins/techdocs-backend @spotify/techdocs-core /packages/techdocs-cli @spotify/techdocs-core 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/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..0b614509f2 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index d360dd995d..bf2638cfe9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,13 +8,33 @@ If you encounter issues while upgrading to a newer version, don't hesitate to re > Collect changes for the next release below -### @backstage/core +### Backend (example-backend, or backends created with @backstage/create-app) -- 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). +- 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. The default base path is `/api/auth`, but you need to set this to `/auth` if you want to keep using the old path. 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 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). ## v0.1.1-alpha.22 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3c2780967..2b6b49e1f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ 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. 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 01925c21dd..e080b0bdb9 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,6 +28,15 @@ 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 @@ -130,6 +138,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: @@ -213,3 +227,23 @@ 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 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..c59470e2ee 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. @@ -142,10 +142,9 @@ can browse and search for all available plugins. 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/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/extending-the-model.md b/docs/features/software-catalog/extending-the-model.md index 4e8a357ea7..7e2a4c3867 100644 --- a/docs/features/software-catalog/extending-the-model.md +++ b/docs/features/software-catalog/extending-the-model.md @@ -18,7 +18,7 @@ Backstage natively supports tracking of the following component 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 +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. @@ -30,7 +30,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..8be6a00579 100644 --- a/docs/features/software-catalog/index.md +++ b/docs/features/software-catalog/index.md @@ -84,7 +84,7 @@ 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 diff --git a/docs/features/software-catalog/references.md b/docs/features/software-catalog/references.md index 5093ecc49e..e438ddc977 100644 --- a/docs/features/software-catalog/references.md +++ b/docs/features/software-catalog/references.md @@ -67,7 +67,7 @@ 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 -need to specify a kind since we know from the context that that's the only kind +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 @@ -79,7 +79,7 @@ there to exist three API kind entities in the catalog matching those 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 contain +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. diff --git a/docs/features/software-catalog/well-known-annotations.md b/docs/features/software-catalog/well-known-annotations.md index ba5b491e07..e0fc10ff1e 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 diff --git a/docs/features/software-templates/adding-templates.md b/docs/features/software-templates/adding-templates.md index 59019e754e..4283af7c72 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/ @@ -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..e354c0941e 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 @@ -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..eff7e53ad3 100644 --- a/docs/features/software-templates/installation.md +++ b/docs/features/software-templates/installation.md @@ -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/getting-started.md b/docs/features/techdocs/getting-started.md index 03494564c3..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 diff --git a/docs/overview/roadmap.md b/docs/overview/roadmap.md index d6c1d2d641..c6b822ad62 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,24 +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 @@ -96,10 +97,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 +115,15 @@ 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 ✅ +- [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/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..bb5a577c7d 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 @@ -170,7 +170,7 @@ input changes 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/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 00494c7768..44de2a1310 100644 --- a/docs/tutorials/quickstart-app-auth.md +++ b/docs/tutorials/quickstart-app-auth.md @@ -155,39 +155,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..020c43a294 100644 --- a/docs/tutorials/quickstart-app-plugin.md +++ b/docs/tutorials/quickstart-app-plugin.md @@ -210,7 +210,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 +312,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/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/package.json b/package.json index 3a77fe6880..45e13d30f4 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\"", diff --git a/packages/app/package.json b/packages/app/package.json index 77b1882b47..5d3e6534f6 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -10,6 +10,7 @@ "@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-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 +33,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/apis.ts b/packages/app/src/apis.ts index 581a591152..c129bebfa2 100644 --- a/packages/app/src/apis.ts +++ b/packages/app/src/apis.ts @@ -29,11 +29,15 @@ 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 = [ createApiFactory({ api: graphQlBrowseApiRef, @@ -54,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 }) => ( + { return ; case isCircleCIAvailable(entity): return ; + case isTravisCIAvailable(entity): + return ; default: return ( @@ -60,16 +68,37 @@ const CICDSwitcher = ({ entity }: { entity: Entity }) => { } }; +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..e936354bd3 100644 --- a/packages/app/src/plugins.ts +++ b/packages/app/src/plugins.ts @@ -34,3 +34,4 @@ 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 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/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..7074040655 100644 --- a/packages/backend-common/src/index.ts +++ b/packages/backend-common/src/index.ts @@ -16,6 +16,7 @@ export * from './config'; export * from './database'; +export * from './discovery'; export * from './errors'; export * from './logging'; export * from './middleware'; 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/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 5bfaf2ee46..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,6 +33,7 @@ "@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", @@ -41,7 +41,7 @@ "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 9d4a738ecf..dbd7842f8b 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -30,12 +30,12 @@ import { getRootLogger, useHotMemoize, notFoundHandler, + SingleHostDiscovery, } 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'; @@ -59,7 +59,8 @@ function makeCreateEnv(loadedConfigs: AppConfig[]) { }, }, ); - return { logger, database, config }; + const discovery = SingleHostDiscovery.fromConfig(config); + return { logger, database, config, discovery }; }; } @@ -71,7 +72,6 @@ async function main() { 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')); @@ -85,11 +85,10 @@ async function main() { apiRouter.use('/rollbar', await rollbar(rollbarEnv)); apiRouter.use('/scaffolder', await scaffolder(scaffolderEnv)); apiRouter.use('/sentry', await sentry(sentryEnv)); - apiRouter.use('/auth', await auth(authEnv, '/api/auth')); - apiRouter.use('/identity', await identity(identityEnv)); + apiRouter.use('/auth', await auth(authEnv)); apiRouter.use('/techdocs', await techdocs(techdocsEnv)); apiRouter.use('/kubernetes', await kubernetes(kubernetesEnv)); - apiRouter.use('/proxy', await proxy(proxyEnv, '/api/proxy')); + apiRouter.use('/proxy', await proxy(proxyEnv)); apiRouter.use('/graphql', await graphql(graphqlEnv)); apiRouter.use(notFoundHandler()); diff --git a/packages/backend/src/plugins/auth.ts b/packages/backend/src/plugins/auth.ts index 60baaff6b7..913c8b783d 100644 --- a/packages/backend/src/plugins/auth.ts +++ b/packages/backend/src/plugins/auth.ts @@ -17,9 +17,11 @@ import { createRouter } from '@backstage/plugin-auth-backend'; import { PluginEnvironment } from '../types'; -export default async function createPlugin( - { logger, database, config }: PluginEnvironment, - basePath: string, -) { - return await createRouter({ logger, config, database, basePath }); +export default async function createPlugin({ + logger, + database, + config, + discovery, +}: PluginEnvironment) { + return await createRouter({ logger, config, database, discovery }); } 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..9f66cbe2ff 100644 --- a/packages/backend/src/plugins/techdocs.ts +++ b/packages/backend/src/plugins/techdocs.ts @@ -29,6 +29,7 @@ import Docker from 'dockerode'; export default async function createPlugin({ logger, config, + discovery, }: PluginEnvironment) { const generators = new Generators(); const techdocsGenerator = new TechdocsGenerator(logger, config); @@ -51,5 +52,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..3709fc8d9a 100644 --- a/packages/backend/src/types.ts +++ b/packages/backend/src/types.ts @@ -17,9 +17,11 @@ import Knex from 'knex'; import { Logger } from 'winston'; import { Config } from '@backstage/config'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; export type PluginEnvironment = { logger: Logger; database: Knex; config: Config; + 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/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 a6e90e6975..759a94ca67 100644 --- a/packages/catalog-model/src/entity/index.ts +++ b/packages/catalog-model/src/entity/index.ts @@ -14,10 +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 { parseEntityName, serializeEntityRef } from './ref'; +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 index b76f01f1f9..d9787fe675 100644 --- a/packages/catalog-model/src/entity/ref.test.ts +++ b/packages/catalog-model/src/entity/ref.test.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +import { ENTITY_DEFAULT_NAMESPACE } from './constants'; import { parseEntityName, parseEntityRef, serializeEntityRef } from './ref'; describe('ref', () => { @@ -27,7 +28,7 @@ describe('ref', () => { expect(() => parseEntityName('b/c')).toThrow(/kind/); expect(parseEntityName('a:c')).toEqual({ kind: 'a', - namespace: 'default', + namespace: ENTITY_DEFAULT_NAMESPACE, name: 'c', }); expect(() => parseEntityName('c')).toThrow(/kind/); @@ -116,7 +117,7 @@ describe('ref', () => { ).toEqual({ kind: 'a', namespace: 'y', name: 'c' }); expect(parseEntityName('a:c', { defaultKind: 'x' })).toEqual({ kind: 'a', - namespace: 'default', + namespace: ENTITY_DEFAULT_NAMESPACE, name: 'c', }); expect( @@ -124,7 +125,7 @@ describe('ref', () => { ).toEqual({ kind: 'x', namespace: 'y', name: 'c' }); expect(parseEntityName('c', { defaultKind: 'x' })).toEqual({ kind: 'x', - namespace: 'default', + namespace: ENTITY_DEFAULT_NAMESPACE, name: 'c', }); }); @@ -150,7 +151,7 @@ describe('ref', () => { ).toEqual({ kind: 'a', namespace: 'y', name: 'c' }); expect( parseEntityName({ kind: 'a', name: 'c' }, { defaultKind: 'x' }), - ).toEqual({ kind: 'a', namespace: 'default', name: 'c' }); + ).toEqual({ kind: 'a', namespace: ENTITY_DEFAULT_NAMESPACE, name: 'c' }); expect( parseEntityName( { name: 'c' }, @@ -159,7 +160,7 @@ describe('ref', () => { ).toEqual({ kind: 'x', namespace: 'y', name: 'c' }); expect(parseEntityName({ name: 'c' }, { defaultKind: 'x' })).toEqual({ kind: 'x', - namespace: 'default', + namespace: ENTITY_DEFAULT_NAMESPACE, name: 'c', }); // empty strings are errors, not defaults diff --git a/packages/catalog-model/src/entity/ref.ts b/packages/catalog-model/src/entity/ref.ts index b9320a5ac7..c4c86b176c 100644 --- a/packages/catalog-model/src/entity/ref.ts +++ b/packages/catalog-model/src/entity/ref.ts @@ -15,6 +15,23 @@ */ 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. @@ -43,7 +60,7 @@ export function parseEntityName( context: EntityRefContext = {}, ): EntityName { const { kind, namespace, name } = parseEntityRef(ref, { - defaultNamespace: 'default', + defaultNamespace: ENTITY_DEFAULT_NAMESPACE, ...context, }); 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/cli/package.json b/packages/cli/package.json index 6f65658539..46b02fe0c3 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", 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/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/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..181eddcad2 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,13 @@ export const DismissableBanner: FC = ({ variant, message, id }) => { return ( ( - - {!dense && ( - - - - - )} +
{children}
); 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/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') && ( - 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 b70f36650e..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}}", 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 457b95a7a9..07f1b1c99a 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 @@ -14,11 +14,11 @@ import { getRootLogger, useHotMemoize, notFoundHandler, + SingleHostDiscovery, } 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'; @@ -37,7 +37,8 @@ function makeCreateEnv(loadedConfigs: AppConfig[]) { }, }, ); - return { logger, database, config }; + const discovery = SingleHostDiscovery.fromConfig(config); + return { logger, database, config, discovery }; }; } @@ -49,7 +50,6 @@ async function main() { 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')); @@ -57,9 +57,8 @@ async function main() { apiRouter.use('/catalog', await catalog(catalogEnv)) apiRouter.use('/scaffolder', await scaffolder(scaffolderEnv)) apiRouter.use('/auth', await auth(authEnv)) - apiRouter.use('/identity', await identity(identityEnv)) apiRouter.use('/techdocs', await techdocs(techdocsEnv)) - apiRouter.use('/proxy', await proxy(proxyEnv, '/api/proxy')) + apiRouter.use('/proxy', await proxy(proxyEnv)) apiRouter.use(notFoundHandler()); const service = createServiceBuilder(module) 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/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..d145255390 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,11 @@ import Knex from 'knex'; import { Logger } from 'winston'; import { Config } from '@backstage/config'; +import { PluginEndpointDiscovery } from '@backstage/backend-common'; export type PluginEnvironment = { logger: Logger; database: Knex; config: Config; + discovery: PluginEndpointDiscovery; }; diff --git a/packages/theme/src/themes.ts b/packages/theme/src/themes.ts index 72a1df716f..5ac8e76101 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', @@ -100,6 +102,8 @@ export const darkTheme = createTheme({ banner: { info: '#2E77D0', error: '#E22134', + text: '#FFFFFF', + link: '#000000', }, border: '#E6E6E6', textContrast: '#FFFFFF', 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/auth-backend/package.json b/plugins/auth-backend/package.json index 8a9bfadca1..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,6 +55,7 @@ "@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", 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..b09dfaa268 --- /dev/null +++ b/plugins/auth-backend/src/lib/catalog/CatalogIdentityClient.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 fetch from 'node-fetch'; +import { UserEntity } from '@backstage/catalog-model'; +import { 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; + } + + 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}`, + ); + } + + return response.json(); + } +} 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..a93c964dbc 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,44 @@ 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]; + const users = await this.identityClient.findUser({ + annotations: { + 'google.com/email': profile.email, + }, + }); + if (users.length !== 1) { + if (users.length > 1) { + this.logger.info( + `Multiple identities found for Google user ${profile.email}`, + ); + } else { + this.logger.info(`No identity found for Google user ${profile.email}`); + } - return { ...response, backstageIdentity: { id } }; + this.logger.warn( + `Falling back to allowing login based on email pattern, this will probably break in the future`, + ); + return { + ...response, + backstageIdentity: { id: profile.email.split('@')[0] }, + }; + } + + return { + ...response, + backstageIdentity: { + id: users[0].metadata.name, + }, + }; } } export const createGoogleProvider: AuthProviderFactory = ({ globalConfig, config, + logger, tokenIssuer, + discovery, }) => OAuthEnvironmentHandler.mapConfig(config, envConfig => { const providerId = 'google'; @@ -160,6 +198,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 e70e687879..bcd1fc1794 100644 --- a/plugins/auth-backend/src/service/router.ts +++ b/plugins/auth-backend/src/service/router.ts @@ -19,34 +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; - basePath?: string; + 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'); - // TODO(Rugvip): Replace with service discovery of external URL - const authUrl = backendUrl + (options.basePath ?? '/api/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, @@ -58,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..6e2aa096d3 100644 --- a/plugins/catalog-backend/package.json +++ b/plugins/catalog-backend/package.json @@ -32,7 +32,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", 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/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..dd3f9eacda 100644 --- a/plugins/catalog-backend/src/ingestion/LocationReaders.ts +++ b/plugins/catalog-backend/src/ingestion/LocationReaders.ts @@ -15,26 +15,28 @@ */ import { getVoidLogger } from '@backstage/backend-common'; -import { Config, ConfigReader } from '@backstage/config'; import { Entity, EntityPolicies, EntityPolicy, 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 { 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 * as result from './processors/results'; +import { StaticLocationProcessor } from './processors/StaticLocationProcessor'; import { LocationProcessor, LocationProcessorDataResult, @@ -44,9 +46,9 @@ 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; @@ -85,6 +87,8 @@ export class LocationReaders implements LocationReader { new AzureApiReaderProcessor(config), new UrlReaderProcessor(), new YamlProcessor(), + PlaceholderProcessor.default(), + new ApiDefinitionAtLocationProcessor(), new EntityPolicyProcessor(entityPolicy), new LocationRefProcessor(), new AnnotateLocationEntityProcessor(), @@ -218,7 +222,12 @@ 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}`; emit(result.generalError(item.location, message)); @@ -248,4 +257,40 @@ export class LocationReaders implements LocationReader { } } } + + 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/PlaceholderProcessor.test.ts b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.test.ts new file mode 100644 index 0000000000..d00e4b7b6f --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.test.ts @@ -0,0 +1,313 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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', + }); + }); +}); + +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..65433b1849 --- /dev/null +++ b/plugins/catalog-backend/src/ingestion/processors/PlaceholderProcessor.ts @@ -0,0 +1,211 @@ +/* + * Copyright 2020 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 (e) { + 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/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/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/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/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/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..21156c10b3 --- /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/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/plugins/cost-insights/types/Icon.ts) for supported types and Material UI icon [mappings](https://github.com/spotify/backstage/plugins/cost-insights/utils/navigation.ts). + +**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 overriden 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/index.ts b/plugins/cost-insights/src/api/index.ts similarity index 94% rename from plugins/identity-backend/src/index.ts rename to plugins/cost-insights/src/api/index.ts index 7612c392a2..d231570e9b 100644 --- a/plugins/identity-backend/src/index.ts +++ b/plugins/cost-insights/src/api/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './service/router'; +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/identity-backend/src/adapters/index.ts b/plugins/cost-insights/src/components/BarChart/index.ts similarity index 93% rename from plugins/identity-backend/src/adapters/index.ts rename to plugins/cost-insights/src/components/BarChart/index.ts index 357391a25b..255bd2b3d8 100644 --- a/plugins/identity-backend/src/adapters/index.ts +++ b/plugins/cost-insights/src/components/BarChart/index.ts @@ -14,4 +14,4 @@ * limitations under the License. */ -export * from './StaticJsonAdapter'; +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/identity-backend/src/adapters/userGroups.ts b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx similarity index 56% rename from plugins/identity-backend/src/adapters/userGroups.ts rename to plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx index 806ca1f43f..03920887b8 100644 --- a/plugins/identity-backend/src/adapters/userGroups.ts +++ b/plugins/cost-insights/src/components/CostOverviewCard/CostOverviewFooter.tsx @@ -13,23 +13,24 @@ * 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 React from 'react'; +import { Box } from '@material-ui/core'; + +type CostOverviewFooterProps = { + children?: React.ReactNode; }; + +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/identity-backend/src/index.test.ts b/plugins/cost-insights/src/plugin.test.ts similarity index 81% rename from plugins/identity-backend/src/index.test.ts rename to plugins/cost-insights/src/plugin.test.ts index 4fca4ca746..6210e11d4c 100644 --- a/plugins/identity-backend/src/index.test.ts +++ b/plugins/cost-insights/src/plugin.test.ts @@ -14,10 +14,10 @@ * limitations under the License. */ -import '@backstage/backend-common'; +import { plugin } from './plugin'; -describe('test', () => { - it('unbreaks the test runner', () => { - expect(true).toBeTruthy(); +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/identity-backend/src/run.ts b/plugins/cost-insights/src/utils/sort.test.ts similarity index 53% rename from plugins/identity-backend/src/run.ts rename to plugins/cost-insights/src/utils/sort.test.ts index a2c2601258..2f4ca87c7e 100644 --- a/plugins/identity-backend/src/run.ts +++ b/plugins/cost-insights/src/utils/sort.test.ts @@ -14,20 +14,19 @@ * limitations under the License. */ -import yn from 'yn'; -import { getRootLogger } from '@backstage/backend-common'; -import { startStandaloneServer } from './service/standaloneServer'; +import { aggregationSort } from './sort'; -const port = process.env.PLUGIN_PORT ? Number(process.env.PLUGIN_PORT) : 3003; -const enableCors = yn(process.env.PLUGIN_CORS, { default: false }); -const logger = getRootLogger(); +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 }, + ]; -startStandaloneServer({ port, enableCors, logger }).catch(err => { - logger.error(err); - process.exit(1); -}); - -process.on('SIGINT', () => { - logger.info('CTRL+C pressed; exiting.'); - process.exit(0); + 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/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/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..014aed1633 --- /dev/null +++ b/plugins/github-actions/src/components/Cards/RecentWorkflowRunsCard.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 { 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 { Table } from '@backstage/core'; +import { WorkflowRunStatus } from '../WorkflowRunStatus'; +import { 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 ( + + ( + + {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/useWorkflowRuns.ts b/plugins/github-actions/src/components/useWorkflowRuns.ts index f935d57810..25ede3f997 100644 --- a/plugins/github-actions/src/components/useWorkflowRuns.ts +++ b/plugins/github-actions/src/components/useWorkflowRuns.ts @@ -24,10 +24,12 @@ export function useWorkflowRuns({ owner, repo, branch, + initialPageSize = 5, }: { owner: string; repo: string; branch?: string; + initialPageSize?: number; }) { const api = useApi(githubActionsApiRef); const auth = useApi(githubAuthApiRef); @@ -36,7 +38,7 @@ export function useWorkflowRuns({ const [total, setTotal] = useState(0); const [page, setPage] = useState(0); - const [pageSize, setPageSize] = useState(5); + const [pageSize, setPageSize] = useState(initialPageSize); const { loading, value: runs, retry, error } = useAsyncRetry< WorkflowRun[] diff --git a/plugins/identity-backend/.eslintrc.js b/plugins/identity-backend/.eslintrc.js deleted file mode 100644 index 16a033dbc6..0000000000 --- a/plugins/identity-backend/.eslintrc.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - extends: [require.resolve('@backstage/cli/config/eslint.backend')], -}; diff --git a/plugins/identity-backend/README.md b/plugins/identity-backend/README.md deleted file mode 100644 index c95fed0698..0000000000 --- a/plugins/identity-backend/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Identity Backend - -WORK IN PROGRESS - -This is the backend part of the identity plugin. - -It responds to identity requests from the frontend. - -## Links - -- [The Backstage homepage](https://backstage.io) diff --git a/plugins/identity-backend/package.json b/plugins/identity-backend/package.json deleted file mode 100644 index 63ecb65d1e..0000000000 --- a/plugins/identity-backend/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "@backstage/plugin-identity-backend", - "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.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": "^0.1.1-alpha.23", - "@types/express": "^4.17.6", - "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", - "morgan": "^1.10.0", - "winston": "^3.2.1", - "yn": "^4.0.0" - }, - "devDependencies": { - "@backstage/cli": "^0.1.1-alpha.23", - "jest-fetch-mock": "^3.0.3", - "msw": "^0.20.5" - }, - "files": [ - "dist" - ] -} diff --git a/plugins/identity-backend/src/adapters/StaticJsonAdapter.ts b/plugins/identity-backend/src/adapters/StaticJsonAdapter.ts deleted file mode 100644 index 9a58da2e85..0000000000 --- a/plugins/identity-backend/src/adapters/StaticJsonAdapter.ts +++ /dev/null @@ -1,82 +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 { - Group, - GroupsResponse, - IdentityApi, - GroupsRequest, - GroupsJson, -} from './types'; - -export class StaticJsonAdapter implements IdentityApi { - private readonly groups: Group[]; - - constructor(userGroups: GroupsJson) { - this.groups = userGroups.groups; - } - - getUserGroups(req: GroupsRequest): Promise { - 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/router.ts b/plugins/identity-backend/src/service/router.ts deleted file mode 100644 index 9d16e8f332..0000000000 --- a/plugins/identity-backend/src/service/router.ts +++ /dev/null @@ -1,50 +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 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; - - logger.info('Initializing identity API backend'); - const adapter = new StaticJsonAdapter(userGroups); - return makeRouter(adapter); -} 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/identity-backend/src/service/standaloneServer.ts b/plugins/identity-backend/src/service/standaloneServer.ts deleted file mode 100644 index 42231b45a9..0000000000 --- a/plugins/identity-backend/src/service/standaloneServer.ts +++ /dev/null @@ -1,50 +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 { Server } from 'http'; -import { Logger } from 'winston'; -import { createStandaloneApplication } from './standaloneApplication'; - -export interface ServerOptions { - port: number; - enableCors: boolean; - logger: Logger; -} - -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, - 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; - } - - logger.info(`Listening on port ${options.port}`); - resolve(server); - }); - }); -} 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/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 index b64e2df37f..47fc345c73 100644 --- a/plugins/kubernetes-backend/examples/dice-roller/README.md +++ b/plugins/kubernetes-backend/examples/dice-roller/README.md @@ -7,7 +7,9 @@ An app to roll dice (it doesn't actually do that). ## Prerequisites - kubectl installed -- Minikube installed +- Minikube installed, with the following addons + - metrics-server + - ingress - jq installed - Backstage locally built and ready to run diff --git a/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml b/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml index ef448c1688..50956bd7d3 100644 --- a/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml +++ b/plugins/kubernetes-backend/examples/dice-roller/dice-roller-manifests.yaml @@ -8,7 +8,7 @@ spec: selector: matchLabels: app: dice-roller - replicas: 2 + replicas: 10 template: metadata: labels: @@ -21,6 +21,73 @@ spec: 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 @@ -56,6 +123,26 @@ spec: - 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 diff --git a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts index c3986e3ff7..8b12d53afc 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesClientProvider.ts @@ -15,7 +15,13 @@ */ import { ClusterDetails } from '..'; -import { AppsV1Api, CoreV1Api, KubeConfig } from '@kubernetes/client-node'; +import { + AppsV1Api, + AutoscalingV1Api, + CoreV1Api, + KubeConfig, + NetworkingV1beta1Api, +} from '@kubernetes/client-node'; export class KubernetesClientProvider { private readonly coreClientMap: { @@ -26,9 +32,19 @@ export class KubernetesClientProvider { [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 @@ -93,4 +109,36 @@ export class KubernetesClientProvider { 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 index 359e7c5806..0109b12f36 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.test.ts @@ -31,6 +31,8 @@ describe('KubernetesClientProvider', () => { const kubernetesClientProvider: any = { getCoreClientByClusterDetails: jest.fn(() => clientMock), getAppsClientByClusterDetails: jest.fn(() => clientMock), + getAutoscalingClientByClusterDetails: jest.fn(() => clientMock), + getNetworkingBeta1Client: jest.fn(() => clientMock), }; const sut = new KubernetesClientBasedFetcher({ diff --git a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts index f6d3edb5e9..8890db7b13 100644 --- a/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts +++ b/plugins/kubernetes-backend/src/service/KubernetesFetcher.ts @@ -16,12 +16,15 @@ import { AppsV1Api, + AutoscalingV1Api, CoreV1Api, + ExtensionsV1beta1Ingress, + NetworkingV1beta1Api, V1ConfigMap, V1Deployment, + V1HorizontalPodAutoscaler, V1Pod, V1ReplicaSet, - V1Secret, } from '@kubernetes/client-node'; import { KubernetesClientProvider } from './KubernetesClientProvider'; import { V1Service } from '@kubernetes/client-node/dist/gen/model/v1Service'; @@ -36,6 +39,8 @@ import { export interface Clients { core: CoreV1Api; apps: AppsV1Api; + autoscaling: AutoscalingV1Api; + networkingBeta1: NetworkingV1beta1Api; } export interface KubernetesClientBasedFetcherOptions { @@ -67,6 +72,7 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { ); } + // TODO could probably do with a tidy up private fetchByObjectType( serviceId: string, clusterDetails: ClusterDetails, @@ -93,13 +99,18 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { serviceId, clusterDetails, ).then(r => ({ type: type, resources: r })); - case 'secrets': - return this.fetchSecretsByServiceId( + case 'services': + return this.fetchServicesByServiceId( serviceId, clusterDetails, ).then(r => ({ type: type, resources: r })); - case 'services': - return this.fetchServicesByServiceId( + 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 })); @@ -119,9 +130,15 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { 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 }).then(result => { + return fn({ core, apps, autoscaling, networkingBeta1 }).then(result => { return result.body.items; }); } @@ -168,20 +185,6 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { ); } - private fetchSecretsByServiceId( - serviceId: string, - clusterDetails: ClusterDetails, - ): Promise> { - return this.singleClusterFetch(clusterDetails, ({ core }) => - core.listSecretForAllNamespaces( - false, - '', - '', - `backstage.io/kubernetes-id=${serviceId}`, - ), - ); - } - private fetchDeploymentsByServiceId( serviceId: string, clusterDetails: ClusterDetails, @@ -209,4 +212,36 @@ export class KubernetesClientBasedFetcher implements KubernetesFetcher { ), ); } + + 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.ts b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts index 52968d4c20..552e083bd7 100644 --- a/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts +++ b/plugins/kubernetes-backend/src/service/getKubernetesObjectsByServiceIdHandler.ts @@ -34,9 +34,10 @@ const DEFAULT_OBJECTS = new Set([ 'pods', 'services', 'configmaps', - 'secrets', 'deployments', 'replicasets', + 'horizontalpodautoscalers', + 'ingresses', ]); export const handleGetKubernetesObjectsByServiceId: GetKubernetesObjectsByServiceIdHandler = async ( diff --git a/plugins/kubernetes-backend/src/types/types.ts b/plugins/kubernetes-backend/src/types/types.ts index 2c69fd67a0..e469b2b1b5 100644 --- a/plugins/kubernetes-backend/src/types/types.ts +++ b/plugins/kubernetes-backend/src/types/types.ts @@ -15,11 +15,12 @@ */ import { + ExtensionsV1beta1Ingress, V1ConfigMap, V1Deployment, + V1HorizontalPodAutoscaler, V1Pod, V1ReplicaSet, - V1Secret, V1Service, } from '@kubernetes/client-node'; @@ -43,9 +44,10 @@ export type FetchResponse = | PodFetchResponse | ServiceFetchResponse | ConfigMapFetchResponse - | SecretFetchResponse | DeploymentFetchResponse - | ReplicaSetsFetchResponse; + | ReplicaSetsFetchResponse + | HorizontalPodAutoscalersFetchResponse + | IngressesFetchResponse; // TODO fairly sure there's a easier way to do this @@ -53,9 +55,10 @@ export type KubernetesObjectTypes = | 'pods' | 'services' | 'configmaps' - | 'secrets' | 'deployments' - | 'replicasets'; + | 'replicasets' + | 'horizontalpodautoscalers' + | 'ingresses'; export interface PodFetchResponse { type: 'pods'; @@ -72,11 +75,6 @@ export interface ConfigMapFetchResponse { resources: Array; } -export interface SecretFetchResponse { - type: 'secrets'; - resources: Array; -} - export interface DeploymentFetchResponse { type: 'deployments'; resources: Array; @@ -87,6 +85,16 @@ export interface ReplicaSetsFetchResponse { 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 { diff --git a/plugins/kubernetes/package.json b/plugins/kubernetes/package.json index d1f3d5e7ba..6d177c8326 100644 --- a/plugins/kubernetes/package.json +++ b/plugins/kubernetes/package.json @@ -24,6 +24,7 @@ "@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", @@ -35,6 +36,7 @@ "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", 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/KubernetesContent.tsx b/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx index bbcef6a0d0..b926d92dc7 100644 --- a/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx +++ b/plugins/kubernetes/src/components/KubernetesContent/KubernetesContent.tsx @@ -14,17 +14,93 @@ * limitations under the License. */ -import React, { FC, useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { Grid } from '@material-ui/core'; -import { InfoCard, Page, pageTheme, Content, useApi } from '@backstage/core'; +import { + CardTab, + Content, + Page, + pageTheme, + Progress, + TabbedCard, + useApi, +} from '@backstage/core'; import { Entity } from '@backstage/catalog-model'; import { kubernetesApiRef } from '../../api/types'; -import { ObjectsByServiceIdResponse } from '@backstage/plugin-kubernetes-backend'; +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'; -// 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 }) => { +// 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, + ); +}; + +// TODO proper error handling + +type KubernetesContentProps = { entity: Entity; children?: React.ReactNode }; + +export const KubernetesContent = ({ entity }: KubernetesContentProps) => { const kubernetesApi = useApi(kubernetesApiRef); + const [kubernetesObjects, setKubernetesObjects] = useState< ObjectsByServiceIdResponse | undefined >(undefined); @@ -45,29 +121,71 @@ export const KubernetesContent: FC<{ entity: Entity }> = ({ entity }) => { - {kubernetesObjects === undefined &&
loading....
} + {kubernetesObjects === undefined && } {error !== undefined &&
{error}
} - {kubernetesObjects !== undefined && ( -
- {kubernetesObjects.items.map((item, i) => ( - - - {item.resources.map((fr, j) => ( -
-
- {fr.type}:{' '} - {(fr.resources as any) - .map((v: any) => v.metadata.name) - .join(' ')} -
- ))} -
-
- ))} -
- )} + {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; + + return ( + <> + + + + + + + + {configMaps && ( + + + + )} + {hpas && ( + + + + )} + {ingresses && ( + + + + )} + + + ); +}; 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/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/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/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/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/techdocs-backend/src/service/router.ts b/plugins/techdocs-backend/src/service/router.ts index 14820da4e9..bd9e71cb8b 100644 --- a/plugins/techdocs-backend/src/service/router.ts +++ b/plugins/techdocs-backend/src/service/router.ts @@ -26,7 +26,10 @@ 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'; @@ -35,6 +38,7 @@ type RouterOptions = { 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 +56,25 @@ export async function createRouter({ config, dockerClient, logger, + discovery, }: RouterOptions): Promise { const router = Router(); router.get('/docs/:kind/:namespace/:name/*', async (req, res) => { - const baseUrl = config.getString('backend.baseUrl'); const storageUrl = config.getString('techdocs.storageUrl'); const { kind, namespace, name } = req.params; - const entity = (await ( - await fetch( - `${baseUrl}/api/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 +89,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/src/reader/components/Reader.tsx b/plugins/techdocs/src/reader/components/Reader.tsx index 2aa87ea1ee..f2c6d1e2da 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, @@ -150,7 +151,7 @@ export const Reader = ({ entityId }: Props) => { return ( <> - {loading ? : null} + {loading ? : null}
); diff --git a/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx b/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.tsx new file mode 100644 index 0000000000..be464bd485 --- /dev/null +++ b/plugins/techdocs/src/reader/components/TechDocsProgressBar.test.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 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'; + +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/yarn.lock b/yarn.lock index 46402a9815..74761d70ba 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3257,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== @@ -3644,13 +3644,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" @@ -4782,6 +4785,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" @@ -5413,6 +5428,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" @@ -5639,9 +5662,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" @@ -6822,6 +6845,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" @@ -7213,6 +7245,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" @@ -7343,6 +7380,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" @@ -8763,7 +8807,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== @@ -9281,6 +9325,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" @@ -9295,11 +9354,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" @@ -9426,6 +9533,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" @@ -9833,6 +9945,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" @@ -10322,10 +10441,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" @@ -11567,6 +11686,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" @@ -12975,7 +13104,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== @@ -15096,7 +15225,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= @@ -15191,6 +15320,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" @@ -15206,7 +15340,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== @@ -15534,6 +15668,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" @@ -15966,7 +16105,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== @@ -16187,6 +16326,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" @@ -16231,6 +16375,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" @@ -18545,7 +18707,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== @@ -18612,7 +18774,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== @@ -19035,6 +19197,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" @@ -19094,6 +19266,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" @@ -19149,6 +19331,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" @@ -19416,6 +19608,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" @@ -19454,6 +19670,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" @@ -19781,7 +20013,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== @@ -20832,13 +21064,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" @@ -21003,9 +21237,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" @@ -21610,6 +21844,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" @@ -22226,6 +22469,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" @@ -22293,6 +22541,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" @@ -22360,6 +22617,11 @@ 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"