github.com/nats-io/nsc@v0.0.0-20221206222106-35db9400b257/cmd/pubtool.go (about)

     1  /*
     2   * Copyright 2018-2022 The NATS Authors
     3   * Licensed under the Apache License, Version 2.0 (the "License");
     4   * you may not use this file except in compliance with the License.
     5   * You may obtain a copy of the License at
     6   *
     7   * http://www.apache.org/licenses/LICENSE-2.0
     8   *
     9   * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License.
    14   */
    15  
    16  package cmd
    17  
    18  import (
    19  	"fmt"
    20  	"os"
    21  	"strings"
    22  
    23  	"github.com/nats-io/nsc/cmd/store"
    24  
    25  	nats "github.com/nats-io/nats.go"
    26  	"github.com/spf13/cobra"
    27  )
    28  
    29  func createPubCmd() *cobra.Command {
    30  	var params PubParams
    31  	var cmd = &cobra.Command{
    32  		Use:     "pub",
    33  		Short:   "Publish to a subject from a NATS account",
    34  		Example: "nsc tool pub <subject> <opt_payload>",
    35  		Args:    cobra.MinimumNArgs(1),
    36  		RunE: func(cmd *cobra.Command, args []string) error {
    37  			if err := RunAction(cmd, args, &params); err != nil {
    38  				return err
    39  			}
    40  			return nil
    41  		},
    42  	}
    43  	params.BindFlags(cmd)
    44  	return cmd
    45  }
    46  
    47  func init() {
    48  	toolCmd.AddCommand(createPubCmd())
    49  	hidden := createPubCmd()
    50  	hidden.Hidden = true
    51  	hidden.Example = "nsc pub <subject> <opt_payload>"
    52  	GetRootCmd().AddCommand(hidden)
    53  }
    54  
    55  // ToolPubParams is the driving struct for the list plans action
    56  type PubParams struct {
    57  	AccountUserContextParams
    58  	credsPath string
    59  	natsURLs  []string
    60  }
    61  
    62  func (p *PubParams) SetDefaults(ctx ActionCtx) error {
    63  	return p.AccountUserContextParams.SetDefaults(ctx)
    64  }
    65  
    66  func (p *PubParams) PreInteractive(ctx ActionCtx) error {
    67  	return p.AccountUserContextParams.Edit(ctx)
    68  }
    69  
    70  func (p *PubParams) Load(ctx ActionCtx) error {
    71  	p.credsPath = ctx.StoreCtx().KeyStore.CalcUserCredsPath(p.AccountContextParams.Name, p.UserContextParams.Name)
    72  	if natsURLFlag != "" {
    73  		p.natsURLs = []string{natsURLFlag}
    74  		return nil
    75  	}
    76  
    77  	oc, err := ctx.StoreCtx().Store.ReadOperatorClaim()
    78  	if err != nil {
    79  		return err
    80  	}
    81  	p.natsURLs = oc.OperatorServiceURLs
    82  	return nil
    83  }
    84  
    85  func (p *PubParams) PostInteractive(ctx ActionCtx) error {
    86  	return nil
    87  }
    88  
    89  func (p *PubParams) Validate(ctx ActionCtx) error {
    90  	if err := p.AccountContextParams.Validate(ctx); err != nil {
    91  		return err
    92  	}
    93  
    94  	if err := p.UserContextParams.Validate(ctx); err != nil {
    95  		return err
    96  	}
    97  
    98  	if p.credsPath == "" {
    99  		return fmt.Errorf("a creds file for account %q/%q was not found", p.AccountContextParams.Name, p.UserContextParams.Name)
   100  	}
   101  
   102  	_, err := os.Stat(p.credsPath)
   103  	if os.IsNotExist(err) {
   104  		return fmt.Errorf("%v: %#q", err, p.credsPath)
   105  	}
   106  	if len(p.natsURLs) == 0 {
   107  		return fmt.Errorf("operator %q doesn't have operator_service_urls set", ctx.StoreCtx().Operator.Name)
   108  	}
   109  	return nil
   110  }
   111  
   112  func (p *PubParams) Run(ctx ActionCtx) (store.Status, error) {
   113  	nc, err := nats.Connect(strings.Join(p.natsURLs, ", "),
   114  		createDefaultToolOptions("nsc_pub", ctx, nats.UserCredentials(p.credsPath))...)
   115  	if err != nil {
   116  		return nil, err
   117  	}
   118  	defer nc.Close()
   119  
   120  	subj := ctx.Args()[0]
   121  	payload := ""
   122  	if len(ctx.Args()) > 1 {
   123  		payload = ctx.Args()[1]
   124  	}
   125  	if err := nc.Publish(subj, []byte(payload)); err != nil {
   126  		return nil, err
   127  	}
   128  	if err := nc.Flush(); err != nil {
   129  		return nil, err
   130  	}
   131  	if err := nc.LastError(); err != nil {
   132  		return nil, err
   133  	}
   134  
   135  	ctx.CurrentCmd().Printf("Published [%s] : %q\n", subj, payload)
   136  
   137  	return nil, nil
   138  }