Files
devstar/modules/docker/AssignDevcontainerGettingDockerOperator.go
xinitx e6d1dbb381 !46 [DIP-2][DevContainer] 添加 WebSSH 和 保存镜像功能、更新了DevContainer相关的配置
* 合并devcontainer web相关的源文件,简化目录结构
* devcontainer、ssh_key_pair和devcontainer.cloud
* fixed bug:创建容器时Host为localhost时创建失败的问题
* 删除了死代码,更新了一些命名(主要是去掉devstar字符串)
* 常量名全大写
* devcontainer HOST改为用户设置的域名或IP
* 安装时如没有配置devcontainer则默认设置为docker方式
* 直接使用kubernetes和docker简化代码提高可读性
* 去除services/devstar_devcontainer文件夹名中不必要的devstar字符串
* 去除services/devstar_devcontainer文件夹名中不必要的devstar字符串
* 文件名中去掉不必要的devstar字符串
* 变量名中删除不必要的Devstar字符串
* Merge branch 'dev' into feature-websshAndUpdateImage
* change pages style
* change Structure
* fix bug
* websshAndUpdateImage
2025-01-07 01:25:54 +00:00

83 lines
2.4 KiB
Go

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() {
}