package docker import ( "context" "fmt" "io/ioutil" "strconv" "code.gitea.io/gitea/modules/log" devcontainer_service_errors "code.gitea.io/gitea/services/devcontainer/errors" devcontainer_service_options "code.gitea.io/gitea/services/devcontainer/options" "github.com/docker/docker/api/types" ) func AssignDevcontainerGettingDockerOperator(ctx *context.Context, opts *devcontainer_service_options.OpenDevcontainerAppDispatcherOptions) (uint16, error) { // 1. 创建docker client cli, err := CreateDockerClient(ctx) if err != nil { return 0, err } if cli != nil { defer cli.Close() } // 获取容器详细信息 containerJSON, err := cli.ContainerInspect(context.Background(), opts.Name) if err != nil { return 0, err } // 获取端口映射信息 portBindings := containerJSON.NetworkSettings.Ports for containerPort, bindings := range portBindings { for _, binding := range bindings { log.Info("Container Port %s is mapped to Host Port %s on IP %s\n", containerPort, binding.HostPort, binding.HostIP) if containerPort.Port() == "22" { v, err := strconv.ParseUint(binding.HostPort, 10, 16) if err != nil { return 0, err } // 执行命令在容器内添加公钥 execConfig := types.ExecConfig{ Cmd: []string{"sh", "-c", fmt.Sprintf("echo '%s' >> ~/.ssh/authorized_keys", opts.UserPublicKey)}, AttachStdout: true, AttachStderr: true, } // 创建执行实例 execID, err := cli.ContainerExecCreate(context.Background(), containerJSON.ID, execConfig) if err != nil { log.Info("Failed to create exec instance:", err) return 0, err } // 附加到执行实例 attachConfig := types.ExecStartCheck{} resp, err := cli.ContainerExecAttach(context.Background(), execID.ID, attachConfig) if err != nil { log.Info("Failed to attach to exec instance:", err) return 0, err } defer resp.Close() // 启动执行实例 err = cli.ContainerExecStart(context.Background(), execID.ID, attachConfig) if err != nil { log.Info("Failed to start exec instance:", err) return 0, err } output, err := ioutil.ReadAll(resp.Reader) log.Info("Command output:\n%s\n", output) return uint16(v), nil } } } return 0, devcontainer_service_errors.ErrOperateDevcontainer{ Action: "Open DevContainer in docker", Message: "cannot find SSH containerPort 22 for DevContainer " + opts.Name, } } func addTemporaryPublicKey() { }