// NewApplicationCreateCommand returns a new instance of an `argocd app create` command
168437
func NewApplicationCreateCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		appOpts appOptions
		fileURL string
		appName string
		upsert  bool
	)
	var command = &cobra.Command{
		Use:   "create APPNAME",
		Short: "Create an application from a git location",
		Run: func(c *cobra.Command, args []string) {
			var app argoappv1.Application
			argocdClient := argocdclient.NewClientOrDie(clientOpts)
			if fileURL != "" {
				parsedURL, err := url.ParseRequestURI(fileURL)
				if err != nil || !(parsedURL.Scheme == "http" || parsedURL.Scheme == "https") {
					err = config.UnmarshalLocalFile(fileURL, &app)
				} else {
					err = config.UnmarshalRemoteFile(fileURL, &app)
				}
				errors.CheckError(err)
				if len(args) == 1 && args[0] != app.Name {
					log.Fatalf("app name '%s' does not match app spec metadata.name '%s'", args[0], app.Name)
				}
				if appName != "" && appName != app.Name {
					log.Fatalf("--name argument '%s' does not match app spec metadata.name '%s'", appName, app.Name)
				}
			} else {
				if len(args) == 1 {
					if appName != "" && appName != args[0] {
						log.Fatalf("--name argument '%s' does not match app name %s", appName, args[0])
					}
					appName = args[0]
				}
				app = argoappv1.Application{
					ObjectMeta: metav1.ObjectMeta{
						Name: appName,
					},
				}
				setAppOptions(c.Flags(), &app, &appOpts)
				setParameterOverrides(&app, appOpts.parameters)
			}
			if app.Name == "" {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			conn, appIf := argocdClient.NewApplicationClientOrDie()
			defer util.Close(conn)
			appCreateRequest := application.ApplicationCreateRequest{
				Application: app,
				Upsert:      &upsert,
			}
			created, err := appIf.Create(context.Background(), &appCreateRequest)
			errors.CheckError(err)
			fmt.Printf("application '%s' created\n", created.ObjectMeta.Name)
		},
	}
	command.Flags().StringVarP(&fileURL, "file", "f", "", "Filename or URL to Kubernetes manifests for the app")
	command.Flags().StringVar(&appName, "name", "", "A name for the app, ignored if a file is set (DEPRECATED)")
	command.Flags().BoolVar(&upsert, "upsert", false, "Allows to override application with the same name even if supplied application spec is different from existing spec")
	addAppFlags(command, &appOpts)
	return command
}
1218614
func New() *cli.Application {
	return &cli.Application{
		Name:  "snapshot",
		Title: "Machine Provider disk snapshot tool",
		Commands: []*subcommands.Command{
			subcommands.CmdHelp,
			getCreateSnapshotCmd(),
		},
	}
}
752348
func NewApplication() *Application {

	return &Application{
		ReadOnly:               false,
		PerformanceMonitorType: "FIRST_PACKET",
		CertificateCommonName:  "*",
		NetworkSymmetry:        false,
		EnablePPS:              false,
		PostClassificationPath: "ANY",
		PreClassificationPath:  "DEFAULT",
		Protocol:               "NONE",
		Symmetry:               false,
	}
}
51271
func NewApplicationSetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		appOpts appOptions
	)
	var command = &cobra.Command{
		Use:   "set APPNAME",
		Short: "Set application parameters",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 1 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			ctx := context.Background()
			appName := args[0]
			argocdClient := argocdclient.NewClientOrDie(clientOpts)
			conn, appIf := argocdClient.NewApplicationClientOrDie()
			defer util.Close(conn)
			app, err := appIf.Get(ctx, &application.ApplicationQuery{Name: &appName})
			errors.CheckError(err)
			visited := setAppOptions(c.Flags(), app, &appOpts)
			if visited == 0 {
				log.Error("Please set at least one option to update")
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			setParameterOverrides(app, appOpts.parameters)
			_, err = appIf.UpdateSpec(ctx, &application.ApplicationUpdateSpecRequest{
				Name: &app.Name,
				Spec: app.Spec,
			})
			errors.CheckError(err)
		},
	}
	addAppFlags(command, &appOpts)
	return command
}
30708
func (st *State) AddApplication(args AddApplicationArgs) (_ *Application, err error) {
	defer errors.DeferredAnnotatef(&err, "cannot add application %q", args.Name)

	// Sanity checks.
	if !names.IsValidApplication(args.Name) {
		return nil, errors.Errorf("invalid name")
	}
	if args.Charm == nil {
		return nil, errors.Errorf("charm is nil")
	}

	model, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	if err := validateCharmSeries(model.Type(), args.Series, args.Charm); err != nil {
		return nil, errors.Trace(err)
	}

	// CAAS charms don't support volume/block storage yet.
	if model.Type() == ModelTypeCAAS {
		for name, charmStorage := range args.Charm.Meta().Storage {
			if storageKind(charmStorage.Type) != storage.StorageKindBlock {
				continue
			}
			var count uint64
			if arg, ok := args.Storage[name]; ok {
				count = arg.Count
			}
			if charmStorage.CountMin > 0 || count > 0 {
				return nil, errors.NotSupportedf("block storage on a Kubernetes model")
			}
		}
	}

	if len(args.AttachStorage) > 0 && args.NumUnits != 1 {
		return nil, errors.Errorf("AttachStorage is non-empty but NumUnits is %d, must be 1", args.NumUnits)
	}

	if err := validateCharmVersion(args.Charm); err != nil {
		return nil, errors.Trace(err)
	}

	if exists, err := isNotDead(st, applicationsC, args.Name); err != nil {
		return nil, errors.Trace(err)
	} else if exists {
		return nil, errors.Errorf("application already exists")
	}
	if err := checkModelActive(st); err != nil {
		return nil, errors.Trace(err)
	}

	// ensure storage
	if args.Storage == nil {
		args.Storage = make(map[string]StorageConstraints)
	}
	sb, err := NewStorageBackend(st)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if err := addDefaultStorageConstraints(sb, args.Storage, args.Charm.Meta()); err != nil {
		return nil, errors.Trace(err)
	}
	if err := validateStorageConstraints(sb, args.Storage, args.Charm.Meta()); err != nil {
		return nil, errors.Trace(err)
	}
	storagePools := make(set.Strings)
	for _, storageParams := range args.Storage {
		storagePools.Add(storageParams.Pool)
	}

	// ensure Devices
	if args.Devices == nil {
		args.Devices = make(map[string]DeviceConstraints)
	}
	deviceb, err := NewDeviceBackend(st)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if err := validateDeviceConstraints(deviceb, args.Devices, args.Charm.Meta()); err != nil {
		return nil, errors.Trace(err)
	}

	// Perform model specific arg processing.
	scale := 0
	placement := ""
	switch model.Type() {
	case ModelTypeIAAS:
		if err := st.processIAASModelApplicationArgs(&args); err != nil {
			return nil, errors.Trace(err)
		}
	case ModelTypeCAAS:
		if err := st.processCAASModelApplicationArgs(&args); err != nil {
			return nil, errors.Trace(err)
		}
		scale = args.NumUnits
		if len(args.Placement) == 1 {
			placement = args.Placement[0].Directive
		}
	}

	applicationID := st.docID(args.Name)

	// Create the application addition operations.
	peers := args.Charm.Meta().Peers

	// The doc defaults to CharmModifiedVersion = 0, which is correct, since it
	// has, by definition, at its initial state.
	appDoc := &applicationDoc{
		DocID:         applicationID,
		Name:          args.Name,
		ModelUUID:     st.ModelUUID(),
		Series:        args.Series,
		Subordinate:   args.Charm.Meta().Subordinate,
		CharmURL:      args.Charm.URL(),
		Channel:       string(args.Channel),
		RelationCount: len(peers),
		Life:          Alive,

		// CAAS
		DesiredScale: scale,
		Placement:    placement,
	}

	app := newApplication(st, appDoc)

	endpointBindingsOp, err := createEndpointBindingsOp(
		st, app.globalKey(),
		args.EndpointBindings, args.Charm.Meta(),
	)
	if err != nil {
		return nil, errors.Trace(err)
	}

	statusDoc := statusDoc{
		ModelUUID:  st.ModelUUID(),
		Status:     status.Waiting,
		StatusInfo: status.MessageWaitForMachine,
		Updated:    st.clock().Now().UnixNano(),
		// This exists to preserve questionable unit-aggregation behaviour
		// while we work out how to switch to an implementation that makes
		// sense.
		NeverSet: true,
	}
	if model.Type() == ModelTypeCAAS {
		statusDoc.StatusInfo = status.MessageWaitForContainer
	}

	if err := args.ApplicationConfig.Validate(); err != nil {
		return nil, errors.Trace(err)
	}
	appConfigAttrs := args.ApplicationConfig.Attributes()

	// When creating the settings, we ignore nils.  In other circumstances, nil
	// means to delete the value (reset to default), so creating with nil should
	// mean to use the default, i.e. don't set the value.
	removeNils(args.CharmConfig)
	removeNils(appConfigAttrs)

	buildTxn := func(attempt int) ([]txn.Op, error) {
		// If we've tried once already and failed, check that
		// model may have been destroyed.
		if attempt > 0 {
			if err := checkModelActive(st); err != nil {
				return nil, errors.Trace(err)
			}
			// Ensure a local application with the same name doesn't exist.
			if exists, err := isNotDead(st, applicationsC, args.Name); err != nil {
				return nil, errors.Trace(err)
			} else if exists {
				return nil, errLocalApplicationExists
			}
			// Ensure a remote application with the same name doesn't exist.
			if remoteExists, err := isNotDead(st, remoteApplicationsC, args.Name); err != nil {
				return nil, errors.Trace(err)
			} else if remoteExists {
				return nil, errSameNameRemoteApplicationExists
			}
		}
		// The addApplicationOps does not include the model alive assertion,
		// so we add it here.
		ops := []txn.Op{
			assertModelActiveOp(st.ModelUUID()),
			endpointBindingsOp,
		}
		addOps, err := addApplicationOps(st, app, addApplicationOpsArgs{
			applicationDoc:    appDoc,
			statusDoc:         statusDoc,
			constraints:       args.Constraints,
			storage:           args.Storage,
			devices:           args.Devices,
			applicationConfig: appConfigAttrs,
			charmConfig:       map[string]interface{}(args.CharmConfig),
		})
		if err != nil {
			return nil, errors.Trace(err)
		}
		ops = append(ops, addOps...)

		// Collect peer relation addition operations.
		//
		// TODO(dimitern): Ensure each st.Endpoint has a space name associated in a
		// follow-up.
		peerOps, err := st.addPeerRelationsOps(args.Name, peers)
		if err != nil {
			return nil, errors.Trace(err)
		}
		ops = append(ops, peerOps...)

		if len(args.Resources) > 0 {
			// Collect pending resource resolution operations.
			resources, err := st.Resources()
			if err != nil {
				return nil, errors.Trace(err)
			}
			resOps, err := resources.NewResolvePendingResourcesOps(args.Name, args.Resources)
			if err != nil {
				return nil, errors.Trace(err)
			}
			ops = append(ops, resOps...)
		}

		// Collect unit-adding operations.
		for x := 0; x < args.NumUnits; x++ {
			unitName, unitOps, err := app.addApplicationUnitOps(applicationAddUnitOpsArgs{
				cons:          args.Constraints,
				storageCons:   args.Storage,
				attachStorage: args.AttachStorage,
			})
			if err != nil {
				return nil, errors.Trace(err)
			}
			ops = append(ops, unitOps...)
			placement := instance.Placement{}
			if x < len(args.Placement) {
				placement = *args.Placement[x]
			}
			ops = append(ops, assignUnitOps(unitName, placement)...)
		}
		return ops, nil
	}
	// At the last moment before inserting the application, prime status history.
	probablyUpdateStatusHistory(st.db(), app.globalKey(), statusDoc)

	if err = st.db().Run(buildTxn); err == nil {
		// Refresh to pick the txn-revno.
		if err = app.Refresh(); err != nil {
			return nil, errors.Trace(err)
		}
		return app, nil
	}
	return nil, errors.Trace(err)
}
636252
func NewCmdCreateDeployment(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
	options := &DeploymentOpts{
		CreateSubcommandOptions: NewCreateSubcommandOptions(ioStreams),
	}

	cmd := &cobra.Command{
		Use:                   "deployment NAME --image=image [--dry-run]",
		DisableFlagsInUseLine: true,
		Aliases:               []string{"deploy"},
		Short:                 i18n.T("Create a deployment with the specified name."),
		Long:                  deploymentLong,
		Example:               deploymentExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(options.Complete(f, cmd, args))
			cmdutil.CheckErr(options.Run())
		},
	}

	options.CreateSubcommandOptions.PrintFlags.AddFlags(cmd)

	cmdutil.AddApplyAnnotationFlags(cmd)
	cmdutil.AddValidateFlags(cmd)
	cmdutil.AddGeneratorFlags(cmd, "")
	cmd.Flags().StringSlice("image", []string{}, "Image name to run.")
	cmd.MarkFlagRequired("image")
	return cmd
}
1374879
func NewApplicationListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		output string
	)
	var command = &cobra.Command{
		Use:   "list",
		Short: "List applications",
		Run: func(c *cobra.Command, args []string) {
			conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie()
			defer util.Close(conn)
			apps, err := appIf.List(context.Background(), &application.ApplicationQuery{})
			errors.CheckError(err)
			w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
			var fmtStr string
			headers := []interface{}{"NAME", "CLUSTER", "NAMESPACE", "PROJECT", "STATUS", "HEALTH", "SYNCPOLICY", "CONDITIONS"}
			if output == "wide" {
				fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
				headers = append(headers, "REPO", "PATH", "TARGET")
			} else {
				fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
			}
			fmt.Fprintf(w, fmtStr, headers...)
			for _, app := range apps.Items {
				vals := []interface{}{
					app.Name,
					app.Spec.Destination.Server,
					app.Spec.Destination.Namespace,
					app.Spec.GetProject(),
					app.Status.Sync.Status,
					app.Status.Health.Status,
					formatSyncPolicy(app),
					formatConditionsSummary(app),
				}
				if output == "wide" {
					vals = append(vals, app.Spec.Source.RepoURL, app.Spec.Source.Path, app.Spec.Source.TargetRevision)
				}
				fmt.Fprintf(w, fmtStr, vals...)
			}
			_ = w.Flush()
		},
	}
	command.Flags().StringVarP(&output, "output", "o", "", "Output format. One of: wide")
	return command
}
734342
func (client *Client) CreateApplication(app Application) (Application, Warnings, error) {
	body, err := json.Marshal(app)
	if err != nil {
		return Application{}, nil, err
	}

	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PostAppRequest,
		Body:        bytes.NewReader(body),
	})
	if err != nil {
		return Application{}, nil, err
	}

	var updatedApp Application
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &updatedApp,
	}

	err = client.connection.Make(request, &response)
	return updatedApp, response.Warnings, err
}
536399
func NewApplicationTerminateOpCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var command = &cobra.Command{
		Use:   "terminate-op APPNAME",
		Short: "Terminate running operation of an application",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 1 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			appName := args[0]
			conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie()
			defer util.Close(conn)
			ctx := context.Background()
			_, err := appIf.TerminateOperation(ctx, &application.OperationTerminateRequest{Name: &appName})
			errors.CheckError(err)
			fmt.Printf("Application '%s' operation terminating\n", appName)
		},
	}
	return command
}
1370280
func New(params *Parameters) *cli.Application {
	return &cli.Application{
		Name:  "crimson",
		Title: "Machine Database client",
		Commands: []*subcommands.Command{
			subcommands.CmdHelp,
			{}, // Create an empty command to separate groups of similar commands.

			// Authentication.
			authcli.SubcommandInfo(params.AuthOptions, "auth-info", true),
			authcli.SubcommandLogin(params.AuthOptions, "auth-login", false),
			authcli.SubcommandLogout(params.AuthOptions, "auth-logout", false),
			{},

			// Static entities.
			getDatacentersCmd(params),
			getIPsCmd(params),
			getKVMsCmd(params),
			getOSesCmd(params),
			getPlatformsCmd(params),
			getRacksCmd(params),
			getSwitchesCmd(params),
			getVLANsCmd(params),
			{},

			// Machines.
			addMachineCmd(params),
			deleteMachineCmd(params),
			editMachineCmd(params),
			getMachinesCmd(params),
			renameMachineCmd(params),
			{},

			// Network interfaces.
			addNICCmd(params),
			deleteNICCmd(params),
			editNICCmd(params),
			getNICsCmd(params),
			{},

			// DRACs.
			addDRACCmd(params),
			editDRACCmd(params),
			getDRACsCmd(params),
			{},

			// Physical hosts.
			addPhysicalHostCmd(params),
			editPhysicalHostCmd(params),
			getPhysicalHostsCmd(params),
			{},

			// VM slots.
			getVMSlotsCmd(params),
			{},

			// Virtual hosts.
			addVMCmd(params),
			editVMCmd(params),
			getVMsCmd(params),
			{},

			// Hostnames.
			deleteHostCmd(params),
			{},

			// States.
			getStatesCmd(params),
		},
	}
}
781502
func (actor Actor) CreateApplicationInSpace(app Application, spaceGUID string) (Application, Warnings, error) {
	createdApp, warnings, err := actor.CloudControllerClient.CreateApplication(
		ccv3.Application{
			LifecycleType:       app.LifecycleType,
			LifecycleBuildpacks: app.LifecycleBuildpacks,
			StackName:           app.StackName,
			Name:                app.Name,
			Relationships: ccv3.Relationships{
				constant.RelationshipTypeSpace: ccv3.Relationship{GUID: spaceGUID},
			},
		})

	if err != nil {
		if _, ok := err.(ccerror.NameNotUniqueInSpaceError); ok {
			return Application{}, Warnings(warnings), actionerror.ApplicationAlreadyExistsError{Name: app.Name}
		}
		return Application{}, Warnings(warnings), err
	}

	return actor.convertCCToActorApplication(createdApp), Warnings(warnings), nil
}
394635
func NewCommand(name string, runFn func(*cobra.Command, []string)) *cobra.Command {
	return &cobra.Command{Use: name, Run: runFn, PreRun: setupHTTPLogger}
}
1297400
func (api *API) ApplicationsCreate(apps Applications) (err error) {
	response, err := api.CallWithError("application.create", apps)
	if err != nil {
		return
	}

	result := response.Result.(map[string]interface{})
	applicationids := result["applicationids"].([]interface{})
	for i, id := range applicationids {
		apps[i].ApplicationId = id.(string)
	}
	return
}
122165
func (o *Applicationperformancemanagement) CreateApplicationBinding(child *ApplicationBinding) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
1242550
func NewCommandLineApp(v interface{}) (*kingpin.Application, error) {
	s := reflect.ValueOf(v).Elem()
	app := kingpin.New("app", "Auto generated command line application")
	if err := setupApp(app, s); err != nil {
		return nil, trace.Wrap(err)
	}
	return app, nil
}
262769
func NewApplicationUnsetCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
	var (
		parameters  []string
		valuesFiles []string
	)
	var command = &cobra.Command{
		Use:   "unset APPNAME -p COMPONENT=PARAM",
		Short: "Unset application parameters",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 1 || (len(parameters) == 0 && len(valuesFiles) == 0) {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			appName := args[0]
			conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie()
			defer util.Close(conn)
			app, err := appIf.Get(context.Background(), &application.ApplicationQuery{Name: &appName})
			errors.CheckError(err)

			updated := false
			if app.Spec.Source.Ksonnet != nil {
				for _, paramStr := range parameters {
					parts := strings.SplitN(paramStr, "=", 2)
					if len(parts) != 2 {
						log.Fatalf("Expected parameter of the form: component=param. Received: %s", paramStr)
					}
					overrides := app.Spec.Source.Ksonnet.Parameters
					for i, override := range overrides {
						if override.Component == parts[0] && override.Name == parts[1] {
							app.Spec.Source.Ksonnet.Parameters = append(overrides[0:i], overrides[i+1:]...)
							updated = true
							break
						}
					}
				}
			}
			if app.Spec.Source.Helm != nil {
				for _, paramStr := range parameters {
					helmParams := app.Spec.Source.Helm.Parameters
					for i, p := range helmParams {
						if p.Name == paramStr {
							app.Spec.Source.Helm.Parameters = append(helmParams[0:i], helmParams[i+1:]...)
							updated = true
							break
						}
					}
				}
				specValueFiles := app.Spec.Source.Helm.ValueFiles
				for _, valuesFile := range valuesFiles {
					for i, vf := range specValueFiles {
						if vf == valuesFile {
							specValueFiles = append(specValueFiles[0:i], specValueFiles[i+1:]...)
							updated = true
							break
						}
					}
				}
				setHelmOpt(&app.Spec.Source, specValueFiles)
				if !updated {
					return
				}
			}

			_, err = appIf.UpdateSpec(context.Background(), &application.ApplicationUpdateSpecRequest{
				Name: &app.Name,
				Spec: app.Spec,
			})
			errors.CheckError(err)
		},
	}
	command.Flags().StringArrayVarP(&parameters, "parameter", "p", []string{}, "unset a parameter override (e.g. -p guestbook=image)")
	command.Flags().StringArrayVar(&valuesFiles, "values", []string{}, "unset one or more helm values files")
	return command
}
6589
func NewCommand() *cobra.Command {
	var (
		logLevel string
	)

	var command = &cobra.Command{
		Use:   cliName,
		Short: "argocd-util has internal tools used by Argo CD",
		Run: func(c *cobra.Command, args []string) {
			c.HelpFunc()(c, args)
		},
	}

	command.AddCommand(cli.NewVersionCmd(cliName))
	command.AddCommand(NewRunDexCommand())
	command.AddCommand(NewGenDexConfigCommand())
	command.AddCommand(NewImportCommand())
	command.AddCommand(NewExportCommand())
	command.AddCommand(NewClusterConfig())

	command.Flags().StringVar(&logLevel, "loglevel", "info", "Set the logging level. One of: debug|info|warn|error")
	return command
}