-
Notifications
You must be signed in to change notification settings - Fork 273
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(enterprise): add utility commands to manage enterprise resources
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
Showing
19 changed files
with
1,339 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
Oops, something went wrong.