Skip to content

Commit

Permalink
feat(enterprise): add utility commands to manage enterprise resources
Browse files Browse the repository at this point in the history
This PR contains a handful of experimental utility commands to manage
enterprise resources such as users and secrets. This is flagged as
experimental for now, since it requires GE 1.13.1 or higher and probably
some more iteration from our end. But the core functionality is all
there.
  • Loading branch information
eysi09 committed Mar 23, 2021
1 parent f5abdd4 commit 9ac421c
Show file tree
Hide file tree
Showing 19 changed files with 1,339 additions and 3 deletions.
1 change: 1 addition & 0 deletions core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@
"devDependencies": {
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
"@garden-io/platform-api-types": "1.14.0",
"@google-cloud/kms": "^2.0.0",
"@types/analytics-node": "^3.1.3",
"@types/async": "^3.2.4",
Expand Down
2 changes: 1 addition & 1 deletion core/src/cli/params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export class StringsParameter extends Parameter<string[] | undefined> {
} else if (!isArray(input)) {
input = [input]
}
return input.flatMap((v) => v.split(this.delimiter))
return input.flatMap((v) => String(v).split(this.delimiter))
}
}

Expand Down
2 changes: 2 additions & 0 deletions core/src/commands/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { DeleteCommand } from "./delete"
import { DeployCommand } from "./deploy"
import { DevCommand } from "./dev"
import { GetCommand } from "./get/get"
import { EnterpriseCommand } from "./enterprise/enterprise"
import { LinkCommand } from "./link/link"
import { LogsCommand } from "./logs"
import { MigrateCommand } from "./migrate"
Expand Down Expand Up @@ -44,6 +45,7 @@ export const getCoreCommands = (): (Command | CommandGroup)[] => [
new DeployCommand(),
new DevCommand(),
new ExecCommand(),
new EnterpriseCommand(),
new GetCommand(),
new LinkCommand(),
new LoginCommand(),
Expand Down
23 changes: 23 additions & 0 deletions core/src/commands/enterprise/enterprise.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright (C) 2018-2021 Garden Technologies, Inc. <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import { dedent } from "../../util/string"
import { CommandGroup } from "../base"
import { GroupsCommand } from "./groups/groups"
import { SecretsCommand } from "./secrets/secrets"
import { UsersCommand } from "./users/users"

export class EnterpriseCommand extends CommandGroup {
name = "enterprise"
help = dedent`
[EXPERIMENTAL] Manage Garden Enterprise resources such as users, groups and secrets. Requires
Garden Enterprise 1.14.0 or higher.
`

subCommands = [SecretsCommand, UsersCommand, GroupsCommand]
}
99 changes: 99 additions & 0 deletions core/src/commands/enterprise/groups/groups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2018-2021 Garden Technologies, Inc. <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import { GetAllGroupsResponse } from "@garden-io/platform-api-types"
import chalk from "chalk"
import { sortBy } from "lodash"
import { StringsParameter } from "../../../cli/params"
import { ConfigurationError } from "../../../exceptions"
import { printHeader } from "../../../logger/util"
import { dedent, deline, renderTable } from "../../../util/string"
import { Command, CommandGroup, CommandParams, CommandResult } from "../../base"
import { noApiMsg, applyFilter } from "../helpers"

// TODO: Add created at and updated at timestamps. Need to add it to the API response first.
interface Groups {
id: number
name: string
description: string
defaultAdminGroup: boolean
}

export class GroupsCommand extends CommandGroup {
name = "groups"
help = "[EXPERIMENTAL] List groups."

subCommands = [GroupsListCommand]
}

export const groupsListOpts = {
"filter-names": new StringsParameter({
help: deline`Filter on group name. Use comma as a separator to filter on multiple names. Accepts glob patterns.`,
}),
}

type Opts = typeof groupsListOpts

export class GroupsListCommand extends Command<{}, Opts> {
name = "list"
help = "[EXPERIMENTAL] List groups."
description = dedent`
List all groups from Garden Enterprise. This is useful for getting the group IDs when creating
users via the \`garden enterprise users create\` coomand.
Examples:
garden enterprise groups list # list all groups
garden enterprise groups list --filter-names dev-* # list all groups that start with 'dev-'
`

options = groupsListOpts

printHeader({ headerLog }) {
printHeader(headerLog, "List groups", "balloon")
}

async action({ garden, log, opts }: CommandParams<{}, Opts>): Promise<CommandResult<Groups[]>> {
const nameFilter = opts["filter-names"] || []

const api = garden.enterpriseApi
if (!api) {
throw new ConfigurationError(noApiMsg("list", "users"), {})
}

const res = await api.get<GetAllGroupsResponse>(`/groups`)
const groups: Groups[] = res.data.map((group) => ({
name: group.name,
id: group.id,
description: group.description,
defaultAdminGroup: group.defaultAdminGroup,
}))

log.info("")

if (groups.length === 0) {
log.info("No groups found in project.")
return { result: [] }
}

const filtered = sortBy(groups, "name").filter((user) => applyFilter(nameFilter, user.name))

if (filtered.length === 0) {
log.info("No groups found in project that match filters.")
return { result: [] }
}

const heading = ["Name", "ID", "Default Admin Group"].map((s) => chalk.bold(s))
const rows: string[][] = filtered.map((g) => {
return [chalk.cyan.bold(g.name), String(g.id), String(g.defaultAdminGroup)]
})

log.info(renderTable([heading].concat(rows)))

return { result: filtered }
}
}
113 changes: 113 additions & 0 deletions core/src/commands/enterprise/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* Copyright (C) 2018-2021 Garden Technologies, Inc. <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

import { GetProjectResponse } from "@garden-io/platform-api-types"
import { EnterpriseApi } from "../../enterprise/api"
import { dedent } from "../../util/string"

import { LogEntry } from "../../logger/log-entry"
import { capitalize } from "lodash"
import minimatch from "minimatch"
import pluralize from "pluralize"
import chalk from "chalk"
import inquirer from "inquirer"

export interface ApiCommandError {
identifier: string | number
message?: string
}

export const noApiMsg = (action: string, resource: string) => dedent`
Unable to ${action} ${resource}. Make sure the project is configured for Garden Enterprise and that you're logged in.
`

export async function getProject(api: EnterpriseApi, projectUid: string) {
const res = await api.get<GetProjectResponse>(`/projects/uid/${projectUid}`)
return res.data
}

export function handleBulkOperationResult({
log,
errors,
action,
cmdLog,
resource,
successCount,
}: {
log: LogEntry
cmdLog: LogEntry
errors: ApiCommandError[]
action: "create" | "delete"
successCount: number
resource: "secret" | "user"
}) {
const totalCount = errors.length + successCount

log.info("")

if (errors.length > 0) {
cmdLog.setError({ msg: "Error", append: true })

const actionVerb = action === "create" ? "creating" : "deleting"
const errorMsgs = errors
.map((e) => {
// Identifier could be an ID, a name or empty.
const identifier = Number.isInteger(e.identifier)
? `with ID ${e.identifier} `
: e.identifier === ""
? ""
: `"${e.identifier} "`
return `→ ${capitalize(actionVerb)} ${resource} ${identifier}failed with error: ${e.message}`
})
.join("\n")
log.error(dedent`
Failed ${actionVerb} ${errors.length}/${totalCount} ${pluralize(resource)}.
See errors below:
${errorMsgs}\n
`)
} else {
cmdLog.setSuccess()
}

if (successCount > 0) {
const resourceStr = successCount === 1 ? resource : pluralize(resource)
log.info({
msg: `Successfully ${action === "create" ? "created" : "deleted"} ${successCount} ${resourceStr}!`,
})
}
}

export function applyFilter(filter: string[], val?: string | string[]) {
if (filter.length === 0) {
return true
}
if (Array.isArray(val)) {
return filter.find((f) => val.some((v) => minimatch(v.toLowerCase(), f.toLowerCase())))
}
return val && filter.find((f) => minimatch(val.toLowerCase(), f.toLowerCase()))
}

export async function confirmDelete(resource: string, count: number) {
const msg = chalk.yellow(dedent`
Warning: you are about to delete ${count} ${
count === 1 ? resource : pluralize(resource)
}. This operation cannot be undone.
Are you sure you want to continue? (run the command with the "--yes" flag to skip this check).
`)

const answer: any = await inquirer.prompt({
name: "continue",
message: msg,
type: "confirm",
default: false,
})

return answer.continue
}
Loading

0 comments on commit 9ac421c

Please sign in to comment.