Skip to content

Commit

Permalink
feat(cmd/influx): add profile management
Browse files Browse the repository at this point in the history
  • Loading branch information
kelwang committed Mar 10, 2020
1 parent 9e8da7c commit be975a1
Show file tree
Hide file tree
Showing 21 changed files with 881 additions and 49 deletions.
2 changes: 1 addition & 1 deletion cmd/influx/authorization.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func authCreateCmd() *cobra.Command {
Short: "Create authorization",
RunE: checkSetupRunEMiddleware(&flags)(authorizationCreateF),
}
authCreateFlags.org.register(cmd, false)
authCreateFlags.org.register(cmd, &flags, false)

cmd.Flags().StringVarP(&authCreateFlags.user, "user", "u", "", "The user name")

Expand Down
4 changes: 2 additions & 2 deletions cmd/influx/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ func init() {

func newBackupService() (influxdb.BackupService, error) {
return &http.BackupService{
Addr: flags.host,
Token: flags.token,
Addr: flags.Host,
Token: flags.Token,
}, nil
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/influx/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (b *cmdBucketBuilder) cmdCreate() *cobra.Command {

cmd.Flags().StringVarP(&b.description, "description", "d", "", "Description of bucket that will be created")
cmd.Flags().DurationVarP(&b.retention, "retention", "r", 0, "Duration bucket will retain data. 0 is infinite. Default is 0.")
b.org.register(cmd, false)
b.org.register(cmd, b.globalFlags, false)

return cmd
}
Expand Down Expand Up @@ -175,7 +175,7 @@ func (b *cmdBucketBuilder) cmdFind() *cobra.Command {
}
opts.mustRegister(cmd)

b.org.register(cmd, false)
b.org.register(cmd, b.globalFlags, false)
cmd.Flags().StringVarP(&b.id, "id", "i", "", "The bucket ID")
cmd.Flags().BoolVar(&b.headers, "headers", true, "To print the table headers; defaults true")

Expand Down
2 changes: 1 addition & 1 deletion cmd/influx/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ in the following ways:
inspectReportTSMCommand.Flags().BoolVarP(&inspectReportTSMFlags.exact, "exact", "", false, "calculate and exact cardinality count. Warning, may use significant memory...")
inspectReportTSMCommand.Flags().BoolVarP(&inspectReportTSMFlags.detailed, "detailed", "", false, "emit series cardinality segmented by measurements, tag keys and fields. Warning, may take a while.")

inspectReportTSMFlags.organization.register(inspectReportTSMCommand, false)
inspectReportTSMFlags.organization.register(inspectReportTSMCommand, &flags, false)
inspectReportTSMCommand.Flags().StringVarP(&inspectReportTSMFlags.bucketID, "bucket-id", "", "", "process only data belonging to bucket ID. Requires org flag to be set.")

dir, err := fs.InfluxDir()
Expand Down
4 changes: 2 additions & 2 deletions cmd/influx/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ func fluxDeleteF(cmd *cobra.Command, args []string) error {
}

s := &http.DeleteService{
Addr: flags.host,
Token: flags.token,
Addr: flags.Host,
Token: flags.Token,
InsecureSkipVerify: flags.skipVerify,
}

Expand Down
76 changes: 54 additions & 22 deletions cmd/influx/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func newHTTPClient() (*httpc.Client, error) {
return httpClient, nil
}

c, err := http.NewHTTPClient(flags.host, flags.token, flags.skipVerify)
c, err := http.NewHTTPClient(flags.Host, flags.Token, flags.skipVerify)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -95,8 +95,7 @@ func out(w io.Writer) genericCLIOptFn {
}

type globalFlags struct {
token string
host string
influxdb.Profile
local bool
skipVerify bool
}
Expand Down Expand Up @@ -141,14 +140,14 @@ func (b *cmdInfluxBuilder) cmd(childCmdFns ...func(f *globalFlags, opt genericCL

fOpts := flagOpts{
{
DestP: &flags.token,
DestP: &flags.Token,
Flag: "token",
Short: 't',
Desc: "API token to be used throughout client calls",
Persistent: true,
},
{
DestP: &flags.host,
DestP: &flags.Host,
Flag: "host",
Default: "http://localhost:9999",
Desc: "HTTP address of Influx",
Expand All @@ -157,11 +156,14 @@ func (b *cmdInfluxBuilder) cmd(childCmdFns ...func(f *globalFlags, opt genericCL
}
fOpts.mustRegister(cmd)

if flags.token == "" {
if flags.Token == "" {
// migration credential token
migrateOldCredential()

// this is after the flagOpts register b/c we don't want to show the default value
// in the usage display. This will add it as the token value, then if a token flag
// in the usage display. This will add it as the profile, then if a token flag
// is provided too, the flag will take precedence.
flags.token = getTokenFromDefaultPath()
flags.Profile = getProfileFromDefaultPath()
}

cmd.PersistentFlags().BoolVar(&flags.local, "local", false, "Run commands locally against the filesystem")
Expand All @@ -185,6 +187,7 @@ func influxCmd(opts ...genericCLIOptFn) *cobra.Command {
cmdOrganization,
cmdPing,
cmdPkg,
cmdProfile,
cmdQuery,
cmdTranspile,
cmdREPL,
Expand Down Expand Up @@ -224,31 +227,57 @@ func seeHelp(c *cobra.Command, args []string) {
c.Printf("See '%s -h' for help\n", c.CommandPath())
}

func defaultTokenPath() (string, string, error) {
func defaultProfilePath() (string, string, error) {
dir, err := fs.InfluxDir()
if err != nil {
return "", "", err
}
return filepath.Join(dir, http.DefaultTokenFile), dir, nil
return filepath.Join(dir, http.DefaultProfilesFile), dir, nil
}

func getTokenFromDefaultPath() string {
path, _, err := defaultTokenPath()
func getProfileFromDefaultPath() influxdb.Profile {
path, _, err := defaultProfilePath()
if err != nil {
return ""
return influxdb.DefaultProfile
}
b, err := ioutil.ReadFile(path)
r, err := os.Open(path)
if err != nil {
return ""
return influxdb.DefaultProfile
}
return strings.TrimSpace(string(b))
activated, _ := influxdb.ParseActiveProfile(r)

return activated
}

func writeTokenToPath(tok, path, dir string) error {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
func migrateOldCredential() {
dir, err := fs.InfluxDir()
if err != nil {
return // no need for migration
}
tokB, err := ioutil.ReadFile(filepath.Join(dir, http.DefaultTokenFile))
if err != nil {
return // no need for migration
}
return ioutil.WriteFile(path, []byte(tok), 0600)
err = writeProfileToPath(strings.TrimSpace(string(tokB)), "", filepath.Join(dir, http.DefaultProfilesFile), dir)
if err != nil {
return
}
// ignore the remove err
_ = os.Remove(filepath.Join(dir, http.DefaultTokenFile))
}

func writeProfileToPath(tok, org, path, dir string) error {
p := &influxdb.DefaultProfile
p.Token = tok
p.Org = org
pp := map[string]influxdb.Profile{
"default": *p,
}

return influxdb.LocalProfilesSVC{
Path: path,
Dir: dir,
}.WriteProfiles(pp)
}

func checkSetup(host string, skipVerify bool) error {
Expand Down Expand Up @@ -277,7 +306,7 @@ func checkSetupRunEMiddleware(f *globalFlags) cobraRuneEMiddleware {
return nil
}

if setupErr := checkSetup(f.host, f.skipVerify); setupErr != nil && influxdb.EUnauthorized != influxdb.ErrorCode(setupErr) {
if setupErr := checkSetup(f.Host, f.skipVerify); setupErr != nil && influxdb.EUnauthorized != influxdb.ErrorCode(setupErr) {
return internal.ErrorFmt(setupErr)
}

Expand Down Expand Up @@ -312,7 +341,7 @@ type organization struct {
id, name string
}

func (o *organization) register(cmd *cobra.Command, persistent bool) {
func (o *organization) register(cmd *cobra.Command, f *globalFlags, persistent bool) {
opts := flagOpts{
{
DestP: &o.id,
Expand All @@ -329,6 +358,9 @@ func (o *organization) register(cmd *cobra.Command, persistent bool) {
},
}
opts.mustRegister(cmd)
if o.id == "" && o.name == "" && f != nil {
o.name = f.Org
}
}

func (o *organization) getID(orgSVC influxdb.OrganizationService) (influxdb.ID, error) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/influx/ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func cmdPing(f *globalFlags, opts genericCLIOpts) *cobra.Command {
c := http.Client{
Timeout: 5 * time.Second,
}
url := flags.host + "/health"
url := flags.Host + "/health"
resp, err := c.Get(url)
if err != nil {
return err
Expand Down
4 changes: 2 additions & 2 deletions cmd/influx/pkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func (b *cmdPkgBuilder) cmdPkgApply() *cobra.Command {
cmd := b.newCmd("pkg", b.pkgApplyRunEFn)
cmd.Short = "Apply a pkg to create resources"

b.org.register(cmd, false)
b.org.register(cmd, &flags, false)
b.registerPkgFileFlags(cmd)
cmd.Flags().BoolVarP(&b.quiet, "quiet", "q", false, "Disable output printing")
cmd.Flags().StringVar(&b.applyOpts.force, "force", "", `TTY input, if package will have destructive changes, proceed if set "true"`)
Expand Down Expand Up @@ -264,7 +264,7 @@ func (b *cmdPkgBuilder) cmdPkgExportAll() *cobra.Command {
cmd.Flags().StringVarP(&b.file, "file", "f", "", "output file for created pkg; defaults to std out if no file provided; the extension of provided file (.yml/.json) will dictate encoding")
cmd.Flags().StringArrayVar(&b.filters, "filter", nil, "Filter exported resources by labelName or resourceKind (format: --filter=labelName=example)")

b.org.register(cmd, false)
b.org.register(cmd, &flags, false)

return cmd
}
Expand Down
Loading

0 comments on commit be975a1

Please sign in to comment.