예제 #1
0
func RunExpose(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
	var name, resource string
	switch l := len(args); {
	case l == 2:
		resource, name = args[0], args[1]
	default:
		return cmdutil.UsageError(cmd, "the type and name of a resource to expose are required arguments")
	}

	namespace, err := f.DefaultNamespace()
	if err != nil {
		return err
	}
	client, err := f.Client()
	if err != nil {
		return err
	}

	generatorName := cmdutil.GetFlagString(cmd, "generator")

	generator, found := kubectl.Generators[generatorName]
	if !found {
		return cmdutil.UsageError(cmd, fmt.Sprintf("generator %q not found.", generator))
	}
	names := generator.ParamNames()
	params := kubectl.MakeParams(cmd, names)
	if len(cmdutil.GetFlagString(cmd, "service-name")) == 0 {
		params["name"] = name
	} else {
		params["name"] = cmdutil.GetFlagString(cmd, "service-name")
	}
	if s, found := params["selector"]; !found || len(s) == 0 || cmdutil.GetFlagInt(cmd, "port") < 1 {
		mapper, _ := f.Object()
		v, k, err := mapper.VersionAndKindForResource(resource)
		if err != nil {
			return err
		}
		mapping, err := mapper.RESTMapping(k, v)
		if err != nil {
			return err
		}
		if len(s) == 0 {
			s, err := f.PodSelectorForResource(mapping, namespace, name)
			if err != nil {
				return err
			}
			params["selector"] = s
		}
		if cmdutil.GetFlagInt(cmd, "port") < 0 {
			ports, err := f.PortsForResource(mapping, namespace, name)
			if err != nil {
				return err
			}
			if len(ports) == 0 {
				return cmdutil.UsageError(cmd, "couldn't find a suitable port via --port flag or introspection")
			}
			if len(ports) > 1 {
				return cmdutil.UsageError(cmd, "more than one port to choose from, please explicitly specify a port using the --port flag.")
			}
			params["port"] = ports[0]
		}
	}
	if cmdutil.GetFlagBool(cmd, "create-external-load-balancer") {
		params["create-external-load-balancer"] = "true"
	}

	err = kubectl.ValidateParams(names, params)
	if err != nil {
		return err
	}

	service, err := generator.Generate(params)
	if err != nil {
		return err
	}

	inline := cmdutil.GetFlagString(cmd, "overrides")
	if len(inline) > 0 {
		service, err = cmdutil.Merge(service, inline, "Service")
		if err != nil {
			return err
		}
	}

	// TODO: extract this flag to a central location, when such a location exists.
	if !cmdutil.GetFlagBool(cmd, "dry-run") {
		service, err = client.Services(namespace).Create(service.(*api.Service))
		if err != nil {
			return err
		}
	}

	return f.PrintObject(cmd, service, out)
}