// Debug creates and runs a debugging pod.
511786
func (o *DebugOptions) RunDebug() error {
	b := o.Builder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		NamespaceParam(o.Namespace).DefaultNamespace().
		SingleResourceType().
		ResourceNames("pods", o.Resources...).
		Flatten()
	if len(o.FilenameOptions.Filenames) > 0 {
		b.FilenameParam(o.ExplicitNamespace, &o.FilenameOptions)
	}
	one := false
	infos, err := b.Do().IntoSingleItemImplied(&one).Infos()
	if err != nil {
		return err
	}
	if !one {
		return fmt.Errorf("you must identify a resource with a pod template to debug")
	}

	templateV1, err := o.approximatePodTemplateForObject(infos[0].Object)
	if err != nil && templateV1 == nil {
		return fmt.Errorf("cannot debug %s: %v", infos[0].Name, err)
	}
	if err != nil {
		klog.V(4).Infof("Unable to get exact template, but continuing with fallback: %v", err)
	}
	template := &corev1.PodTemplateSpec{}
	if err := legacyscheme.Scheme.Convert(templateV1, template, nil); err != nil {
		return err
	}
	pod := &corev1.Pod{
		ObjectMeta: template.ObjectMeta,
		Spec:       template.Spec,
	}
	ns := infos[0].Namespace
	if len(ns) == 0 {
		ns = o.Namespace
	}
	pod.Name, pod.Namespace = fmt.Sprintf("%s-debug", generateapp.MakeSimpleName(infos[0].Name)), ns
	o.Attach.Pod = pod

	if len(o.Attach.ContainerName) == 0 && len(pod.Spec.Containers) > 0 {
		if len(pod.Spec.Containers) > 1 && len(o.FullCmdName) > 0 {
			fmt.Fprintf(o.ErrOut, "Defaulting container name to %s.\n", pod.Spec.Containers[0].Name)
			fmt.Fprintf(o.ErrOut, "Use '%s describe pod/%s -n %s' to see all of the containers in this pod.\n", o.FullCmdName, pod.Name, pod.Namespace)
			fmt.Fprintf(o.ErrOut, "\n")
		}

		klog.V(4).Infof("Defaulting container name to %s", pod.Spec.Containers[0].Name)
		o.Attach.ContainerName = pod.Spec.Containers[0].Name
	}

	names := containerNames(o.Attach.Pod)
	if len(names) == 0 {
		return fmt.Errorf("the provided pod must have at least one container")
	}
	if len(o.Attach.ContainerName) == 0 {
		return fmt.Errorf("you must provide a container name to debug")
	}
	if containerForName(o.Attach.Pod, o.Attach.ContainerName) == nil {
		return fmt.Errorf("the container %q is not a valid container name; must be one of %v", o.Attach.ContainerName, names)
	}

	o.Annotations[debugPodAnnotationSourceResource] = fmt.Sprintf("%s/%s", infos[0].Mapping.Resource, infos[0].Name)
	o.Annotations[debugPodAnnotationSourceContainer] = o.Attach.ContainerName

	pod, originalCommand := o.transformPodForDebug(o.Annotations)
	var commandString string
	switch {
	case len(originalCommand) > 0:
		commandString = strings.Join(originalCommand, " ")
	default:
		commandString = ""
	}

	if o.Printer != nil {
		return o.Printer.PrintObj(pod, o.Out)
	}

	klog.V(5).Infof("Creating pod: %#v", pod)
	pod, err = o.createPod(pod)
	if err != nil {
		return err
	}

	// ensure the pod is cleaned up on shutdown
	o.Attach.InterruptParent = interrupt.New(
		func(os.Signal) { os.Exit(1) },
		func() {
			stderr := o.ErrOut
			if stderr == nil {
				stderr = os.Stderr
			}
			fmt.Fprintf(stderr, "\nRemoving debug pod ...\n")
			if err := o.CoreClient.Pods(pod.Namespace).Delete(pod.Name, metav1.NewDeleteOptions(0)); err != nil {
				if !kapierrors.IsNotFound(err) {
					fmt.Fprintf(stderr, "error: unable to delete the debug pod %q: %v\n", pod.Name, err)
				}
			}
		},
	)

	klog.V(5).Infof("Created attach arguments: %#v", o.Attach)
	return o.Attach.InterruptParent.Run(func() error {
		w, err := o.CoreClient.Pods(pod.Namespace).Watch(metav1.SingleObject(pod.ObjectMeta))
		if err != nil {
			return err
		}
		if len(commandString) > 0 {
			fmt.Fprintf(o.ErrOut, "Starting pod/%s, command was: %s\n", pod.Name, commandString)
		} else {
			fmt.Fprintf(o.ErrOut, "Starting pod/%s ...\n", pod.Name)
		}
		if o.IsNode {
			fmt.Fprintf(o.ErrOut, "To use host binaries, run `chroot /host`\n")
		}

		ctx, cancel := context.WithTimeout(context.Background(), o.Timeout)
		defer cancel()
		switch containerRunningEvent, err := watchtools.UntilWithoutRetry(ctx, w, conditions.PodContainerRunning(o.Attach.ContainerName)); {
		// api didn't error right away but the pod wasn't even created
		case kapierrors.IsNotFound(err):
			msg := fmt.Sprintf("unable to create the debug pod %q", pod.Name)
			if len(o.NodeName) > 0 {
				msg += fmt.Sprintf(" on node %q", o.NodeName)
			}
			return fmt.Errorf(msg)
			// switch to logging output
		case err == kubectl.ErrPodCompleted, err == conditions.ErrContainerTerminated, !o.Attach.Stdin:
			return logs.LogsOptions{
				Object: pod,
				Options: &corev1.PodLogOptions{
					Container: o.Attach.ContainerName,
					Follow:    true,
				},
				RESTClientGetter: o.RESTClientGetter,
				ConsumeRequestFn: logs.DefaultConsumeRequest,
				IOStreams:        o.IOStreams,
				LogsForObject:    o.LogsForObject,
			}.RunLogs()
		case err != nil:
			return err
		default:
			// TODO this doesn't do us much good for remote debugging sessions, but until we get a local port
			// set up to proxy, this is what we've got.
			if podWithStatus, ok := containerRunningEvent.Object.(*kapi.Pod); ok {
				fmt.Fprintf(o.Attach.ErrOut, "Pod IP: %s\n", podWithStatus.Status.PodIP)
			}

			// TODO: attach can race with pod completion, allow attach to switch to logs
			return o.Attach.Run()
		}
	})
}
802877
func (b *simple) Debug(msg ...interface{}) {
	stdlog.Printf("[DEBUG] %s %s", fmt.Sprint(msg...), pretty(b.fields))
}
806744
func (l *Logger) Debug(v ...interface{}) {
	if l.Level >= DebugLevel {
		l.Logger.Print(DebugLevel.String() + fmt.Sprint(v...))
	}
}
1318142
func (l logger) Debug(message string, data ...interface{}) {
	for _, sink := range l.sinks {
		sink.Log(DEBUG, l.toByteArray(message, data...))
	}
}
829487
func (f *Fetcher) Debug() <-chan *DebugInfo {
	f.dbgmu.Lock()
	defer f.dbgmu.Unlock()
	f.debugging = true
	return f.dbg
}
963367
func (l *logger) Debug(format string, args ...interface{}) {
	if l.Level >= DEBUG {
		l.log(DEBUG, format, args...)
	}
}
527400
func (l *LagerAdapter) Debug(action string, data ...lager.Data) {
	l.originalLogger.Debug(action, dataToFields(data)...)
}
140272
func (c *Conn) debug(fn func(d *debugger)) {
	if c.d == nil {
		return
	}

	fn(c.d)
}
530119
func (log *impl) Debug(msg string) {
	log.w.logAtLevel(syslog.LOG_DEBUG, msg)
}
1372611
func (l *Logger) Debug(v interface{}) {
	if l.checkLogLevel(DebugLevel) {
		l.Output(time.Now(), DebugLevel, format(v))
	}
}
969442
func Debug(logger log.Logger) log.Logger {
	return log.WithPrefix(logger, Key(), DebugValue())
}
1341527
func (c *Config) LogDebug(format string, v ...interface{}) {
	c.doLog(LogDebug, format, v...)
}
179086
func (w *Writer) Debug(m string) (err error) {
	_, err = w.writeAndRetry(LOG_DEBUG, m)
	return err
}
1322444
func logDebug(source, format string, v ...interface{}) {
	if EnableDebugLogging {
		stdLogger.Printf(fmt.Sprintf("[DEBUG] %s %s", source, format), v...)
	}
}
260828
func (l *Logger) Debug(format string, v ...interface{}) {
	l.output(LDebug, format, v...)
}
252986
func (logger *Logger) Debug(args ...interface{}) {
	if logger.std.Level >= lg.DebugLevel {
		logger.header(1).Debug(args...)
	}
}
432869
func (l *intLogger) Debug(msg string, args ...interface{}) {
	l.Log(Debug, msg, args...)
}