fix: daemon.json 路径逻辑调整

This commit is contained in:
ssongliu 2023-01-05 17:29:27 +08:00
parent 5a20546fc6
commit 8674cf0b53
14 changed files with 194 additions and 198 deletions

View file

@ -28,22 +28,6 @@ func (b *BaseApi) GetSettingInfo(c *gin.Context) {
helper.SuccessWithData(c, setting)
}
// Load daemon.json path
// @Tags System Setting
// @Summary Load daemon.json path
// @Description 加载 docker 配置路径
// @Success 200 {string} path
// @Security ApiKeyAuth
// @Router /settings/daemonjson [get]
func (b *BaseApi) GetDaemonjson(c *gin.Context) {
value, err := settingService.GetDaemonjson()
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}
helper.SuccessWithData(c, value)
}
// @Tags System Setting
// @Summary Update system setting
// @Description 更新系统配置

View file

@ -7,6 +7,7 @@ type DaemonJsonUpdateByFile struct {
type DaemonJsonConf struct {
Status string `json:"status"`
Version string `json:"version"`
Mirrors []string `json:"registryMirrors"`
Registries []string `json:"insecureRegistries"`
LiveRestore bool `json:"liveRestore"`

View file

@ -2,14 +2,17 @@ package service
import (
"bufio"
"context"
"encoding/json"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"github.com/1Panel-dev/1Panel/backend/app/dto"
"github.com/1Panel-dev/1Panel/backend/constant"
"github.com/1Panel-dev/1Panel/backend/utils/docker"
"github.com/pkg/errors"
)
@ -53,31 +56,33 @@ func (u *DockerService) LoadDockerConf() *dto.DaemonJsonConf {
if string(stdout) != "active\n" || err != nil {
status = constant.Stopped
}
fileSetting, err := settingRepo.Get(settingRepo.WithByKey("DaemonJsonPath"))
version := "-"
client, err := docker.NewDockerClient()
if err == nil {
ctx := context.Background()
itemVersion, err := client.ServerVersion(ctx)
if err == nil {
version = itemVersion.Version
}
}
if _, err := os.Stat(constant.DaemonJsonPath); err != nil {
return &dto.DaemonJsonConf{Status: status, Version: version}
}
file, err := ioutil.ReadFile(constant.DaemonJsonPath)
if err != nil {
return &dto.DaemonJsonConf{Status: status}
}
if len(fileSetting.Value) == 0 {
return &dto.DaemonJsonConf{Status: status}
}
if _, err := os.Stat(fileSetting.Value); err != nil {
return &dto.DaemonJsonConf{Status: status}
}
file, err := ioutil.ReadFile(fileSetting.Value)
if err != nil {
return &dto.DaemonJsonConf{Status: status}
return &dto.DaemonJsonConf{Status: status, Version: version}
}
var conf daemonJsonItem
deamonMap := make(map[string]interface{})
if err := json.Unmarshal(file, &deamonMap); err != nil {
return &dto.DaemonJsonConf{Status: status}
return &dto.DaemonJsonConf{Status: status, Version: version}
}
arr, err := json.Marshal(deamonMap)
if err != nil {
return &dto.DaemonJsonConf{Status: status}
return &dto.DaemonJsonConf{Status: status, Version: version}
}
if err := json.Unmarshal(arr, &conf); err != nil {
return &dto.DaemonJsonConf{Status: status}
return &dto.DaemonJsonConf{Status: status, Version: version}
}
driver := "cgroupfs"
for _, opt := range conf.ExecOpts {
@ -88,6 +93,7 @@ func (u *DockerService) LoadDockerConf() *dto.DaemonJsonConf {
}
data := dto.DaemonJsonConf{
Status: status,
Version: version,
Mirrors: conf.Mirrors,
Registries: conf.Registries,
LiveRestore: conf.LiveRestore,
@ -98,22 +104,16 @@ func (u *DockerService) LoadDockerConf() *dto.DaemonJsonConf {
}
func (u *DockerService) UpdateConf(req dto.DaemonJsonConf) error {
fileSetting, err := settingRepo.Get(settingRepo.WithByKey("DaemonJsonPath"))
if err != nil {
return err
}
if len(fileSetting.Value) == 0 {
return errors.New("error daemon.json path in request")
}
if _, err := os.Stat(fileSetting.Value); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(fileSetting.Value, os.ModePerm); err != nil {
if _, err := os.Stat(constant.DaemonJsonPath); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(path.Dir(constant.DaemonJsonPath), os.ModePerm); err != nil {
if err != nil {
return err
}
}
_, _ = os.Create(constant.DaemonJsonPath)
}
file, err := ioutil.ReadFile(fileSetting.Value)
file, err := ioutil.ReadFile(constant.DaemonJsonPath)
if err != nil {
return err
}
@ -155,7 +155,7 @@ func (u *DockerService) UpdateConf(req dto.DaemonJsonConf) error {
if err != nil {
return err
}
if err := ioutil.WriteFile(fileSetting.Value, newJson, 0640); err != nil {
if err := ioutil.WriteFile(constant.DaemonJsonPath, newJson, 0640); err != nil {
return err
}

View file

@ -176,24 +176,17 @@ func (u *ImageRepoService) checkConn(host, user, password string) error {
}
func (u *ImageRepoService) handleRegistries(newHost, delHost, handle string) error {
fileSetting, err := settingRepo.Get(settingRepo.WithByKey("DaemonJsonPath"))
if err != nil {
return err
}
if len(fileSetting.Value) == 0 {
return errors.New("error daemon.json in settings")
}
if _, err := os.Stat(path.Dir(fileSetting.Value)); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(fileSetting.Value, os.ModePerm); err != nil {
if _, err := os.Stat(constant.DaemonJsonPath); err != nil && os.IsNotExist(err) {
if err = os.MkdirAll(path.Dir(constant.DaemonJsonPath), os.ModePerm); err != nil {
if err != nil {
return err
}
}
_, _ = os.Create(fileSetting.Value)
_, _ = os.Create(constant.DaemonJsonPath)
}
deamonMap := make(map[string]interface{})
file, err := ioutil.ReadFile(fileSetting.Value)
file, err := ioutil.ReadFile(constant.DaemonJsonPath)
if err != nil {
return err
}
@ -229,7 +222,7 @@ func (u *ImageRepoService) handleRegistries(newHost, delHost, handle string) err
if err != nil {
return err
}
if err := ioutil.WriteFile(fileSetting.Value, newJson, 0640); err != nil {
if err := ioutil.WriteFile(constant.DaemonJsonPath, newJson, 0640); err != nil {
return err
}
return nil

View file

@ -16,7 +16,6 @@ type SettingService struct{}
type ISettingService interface {
GetSettingInfo() (*dto.SettingInfo, error)
GetDaemonjson() (string, error)
Update(c *gin.Context, key, value string) error
UpdatePassword(c *gin.Context, old, new string) error
HandlePasswordExpired(c *gin.Context, old, new string) error
@ -47,14 +46,6 @@ func (u *SettingService) GetSettingInfo() (*dto.SettingInfo, error) {
return &info, err
}
func (u *SettingService) GetDaemonjson() (string, error) {
setting, err := settingRepo.Get(settingRepo.WithByKey("DaemonJsonPath"))
if err != nil {
return "", err
}
return setting.Value, nil
}
func (u *SettingService) Update(c *gin.Context, key, value string) error {
if key == "ExpirationDays" {
timeout, _ := strconv.Atoi(value)

View file

@ -16,4 +16,5 @@ const (
TmpDockerBuildDir = "/opt/1Panel/data/docker/build"
TmpComposeBuildDir = "/opt/1Panel/data/docker/compose"
DaemonJsonPath = "/tmp/docker/daemon.json"
)

View file

@ -114,10 +114,6 @@ var AddTableSetting = &gormigrate.Migration{
return err
}
if err := tx.Create(&model.Setting{Key: "DaemonJsonPath", Value: "/opt/1Panel/docker/conf/daemon.json"}).Error; err != nil {
return err
}
if err := tx.Create(&model.Setting{Key: "MessageType", Value: "none"}).Error; err != nil {
return err
}

View file

@ -23,7 +23,6 @@ func (s *SettingRouter) InitSettingRouter(Router *gin.RouterGroup) {
settingRouter.POST("/time/sync", baseApi.SyncTime)
settingRouter.POST("/monitor/clean", baseApi.CleanMonitor)
settingRouter.GET("/mfa", baseApi.GetMFA)
settingRouter.GET("/daemonjson", baseApi.GetDaemonjson)
settingRouter.POST("/mfa/bind", baseApi.MFABind)
}
}

View file

@ -236,7 +236,6 @@ export namespace Container {
}
export interface DaemonJsonUpdateByFile {
path: string;
file: string;
}
export interface DockerOperate {
@ -244,6 +243,7 @@ export namespace Container {
}
export interface DaemonJsonConf {
status: string;
version: string;
registryMirrors: Array<string>;
insecureRegistries: Array<string>;
liveRestore: boolean;

View file

@ -359,6 +359,7 @@ export default {
rdbInfo: 'Rule list has 0 value, please confirm and try again!',
},
container: {
containerList: 'Container list',
operatorHelper: '{0} will be performed on the selected container. Do you want to continue?',
start: 'Start',
stop: 'Stop',

View file

@ -372,6 +372,7 @@ export default {
rdbInfo: '规则列表存在 0 请确认后重试',
},
container: {
containerList: '容器列表',
operatorHelper: '将对选中容器进行 {0} 操作是否继续',
start: '启动',
stop: '停止',

View file

@ -1,31 +1,42 @@
<template>
<div v-loading="loading">
<LayoutContent :header="composeName" back-name="Compose" :reload="true">
<div v-if="createdBy === '1Panel'">
<el-card>
<template #header>
<div class="card-header">
<span>{{ $t('container.compose') }}</span>
<div class="app-content" style="margin-top: 20px">
<el-card class="app-card">
<el-row :gutter="20">
<el-col :lg="3" :xl="2">
<div>
<el-tag effect="dark" type="success">{{ composeName }}</el-tag>
</div>
</template>
<el-button-group>
<el-button @click="onComposeOperate('start')">{{ $t('container.start') }}</el-button>
<el-button @click="onComposeOperate('stop')">{{ $t('container.stop') }}</el-button>
<el-button @click="onComposeOperate('down')">
{{ $t('container.remove') }}
</el-button>
</el-button-group>
</el-card>
</div>
<div v-else>
<el-alert :closable="false" show-icon :title="$t('container.composeDetailHelper')" type="info" />
</div>
<el-card style="margin-top: 20px">
<template #header>
<div class="card-header">
<span>{{ $t('container.container') }}</span>
</div>
</template>
</el-col>
<el-col :lg="8" :xl="12">
<div v-if="createdBy === '1Panel'">
<el-button link type="primary" @click="onComposeOperate('start')">
{{ $t('container.start') }}
</el-button>
<el-divider direction="vertical" />
<el-button link type="primary" @click="onComposeOperate('stop')">
{{ $t('container.stop') }}
</el-button>
<el-divider direction="vertical" />
<el-button link type="primary" @click="onComposeOperate('down')">
{{ $t('container.remove') }}
</el-button>
</div>
<div v-else>
<el-alert
style="margin-top: -5px"
:closable="false"
show-icon
:title="$t('container.composeDetailHelper')"
type="info"
/>
</div>
</el-col>
</el-row>
</el-card>
</div>
<el-card style="margin-top: 20px">
<LayoutContent :header="$t('container.containerList')" back-name="Compose" :reload="true">
<ComplexTable
:pagination-config="paginationConfig"
v-model:selects="selects"
@ -103,8 +114,8 @@
<CreateDialog @search="search" ref="dialogCreateRef" />
<MonitorDialog ref="dialogMonitorRef" />
<TerminalDialog ref="dialogTerminalRef" />
</el-card>
</LayoutContent>
</LayoutContent>
</el-card>
</div>
</template>
@ -314,3 +325,18 @@ defineExpose({
acceptParams,
});
</script>
<style lang="scss">
.app-card {
font-size: 14px;
height: 60px;
}
.app-content {
height: 50px;
}
body {
margin: 0;
}
</style>

View file

@ -1,6 +1,10 @@
<template>
<div v-loading="loading">
<Submenu activeName="compose" />
<div v-show="isOnDetail">
<ComposeDetial @back="backList" ref="composeDetailRef" />
</div>
<el-card width="30%" v-if="dockerStatus != 'Running'" class="mask-prompt">
<span style="font-size: 14px">{{ $t('container.serviceUnavailable') }}</span>
<el-button type="primary" link style="font-size: 14px; margin-bottom: 5px" @click="goSetting">
@ -8,8 +12,8 @@
</el-button>
<span style="font-size: 14px">{{ $t('container.startIn') }}</span>
</el-card>
<el-card style="margin-top: 20px" :class="{ mask: dockerStatus != 'Running' }">
<div v-if="!isOnDetail">
<el-card v-if="!isOnDetail" style="margin-top: 20px" :class="{ mask: dockerStatus != 'Running' }">
<div>
<ComplexTable
:pagination-config="paginationConfig"
v-model:selects="selects"
@ -54,9 +58,6 @@
/>
</ComplexTable>
</div>
<div v-show="isOnDetail">
<ComposeDetial @back="backList" ref="composeDetailRef" />
</div>
</el-card>
<EditDialog ref="dialogEditRef" />

View file

@ -1,53 +1,63 @@
<template>
<div v-loading="loading">
<Submenu activeName="setting" />
<el-form :model="form" ref="formRef" label-width="120px">
<el-card style="margin-top: 20px">
<el-row style="margin-top: 20px">
<el-col :span="1"><br /></el-col>
<el-col :span="10">
<el-form-item :label="$t('container.dockerStatus')">
<div v-if="form.status === 'Running'">
<el-tag type="success">{{ $t('commons.status.running') }}</el-tag>
<el-button type="primary" @click="onOperator('stop')" link style="margin-left: 20px">
{{ $t('container.stop') }}
</el-button>
<el-divider direction="vertical" />
<el-button type="primary" @click="onOperator('restart')" link>
{{ $t('container.restart') }}
</el-button>
</div>
<div v-if="form.status === 'Stopped'">
<el-tag type="info">{{ $t('commons.status.stopped') }}</el-tag>
<el-button type="primary" @click="onOperator('start')" link style="margin-left: 20px">
{{ $t('container.start') }}
</el-button>
<el-divider direction="vertical" />
<el-button type="primary" @click="onOperator('restart')" link>
{{ $t('container.restart') }}
</el-button>
</div>
</el-form-item>
<el-form-item :label="$t('container.daemonJsonPath')">
<el-input disabled v-model="daemonJsonPath">
<template #append>
<FileList @choose="loadLoadDir" :dir="false"></FileList>
</template>
</el-input>
<span class="input-help">{{ $t('container.daemonJsonPathHelper') }}</span>
<el-button type="primary" @click="savePath">{{ $t('commons.button.save') }}</el-button>
</el-form-item>
<div class="app-content" style="margin-top: 20px">
<el-card class="app-card">
<el-row :gutter="20">
<el-col :lg="3" :xl="2">
<div>
<el-tag effect="dark" type="success">Docker</el-tag>
</div>
</el-col>
<el-col :lg="3" :xl="2">
<div>
{{ $t('app.version') }}:
<el-tag type="info">{{ form.version }}</el-tag>
</div>
</el-col>
<el-col :lg="3" :xl="2">
<div>
{{ $t('commons.table.status') }}:
<el-tag v-if="form.status === 'Running'" type="success">
{{ $t('commons.status.running') }}
</el-tag>
<el-tag v-if="form.status === 'Stopped'" type="info">
{{ $t('commons.status.stopped') }}
</el-tag>
</div>
</el-col>
<el-col :lg="4" :xl="6">
<div v-if="form.status === 'Running'">
<el-button type="primary" @click="onOperator('stop')" link style="margin-left: 20px">
{{ $t('container.stop') }}
</el-button>
<el-divider direction="vertical" />
<el-button type="primary" @click="onOperator('restart')" link>
{{ $t('container.restart') }}
</el-button>
</div>
<div v-if="form.status === 'Stopped'">
<el-button type="primary" @click="onOperator('start')" link style="margin-left: 20px">
{{ $t('container.start') }}
</el-button>
<el-divider direction="vertical" />
<el-button type="primary" @click="onOperator('restart')" link>
{{ $t('container.restart') }}
</el-button>
</div>
</el-col>
</el-row>
</el-card>
<el-card style="margin-top: 10px">
<el-radio-group v-model="confShowType" @change="changeMode">
<el-radio-button label="base">{{ $t('database.baseConf') }}</el-radio-button>
<el-radio-button label="all">{{ $t('database.allConf') }}</el-radio-button>
</el-radio-group>
<el-row style="margin-top: 20px" v-if="confShowType === 'base'">
<el-col :span="1"><br /></el-col>
<el-col :span="10">
</div>
<el-card style="margin-top: 20px">
<el-radio-group v-model="confShowType" @change="changeMode">
<el-radio-button label="base">{{ $t('database.baseConf') }}</el-radio-button>
<el-radio-button label="all">{{ $t('database.allConf') }}</el-radio-button>
</el-radio-group>
<el-row style="margin-top: 20px" v-if="confShowType === 'base'">
<el-col :span="1"><br /></el-col>
<el-col :span="10">
<el-form :model="form" ref="formRef" label-width="120px">
<el-form-item :label="$t('container.mirrors')" prop="mirrors">
<el-input
type="textarea"
@ -80,30 +90,30 @@
{{ $t('commons.button.save') }}
</el-button>
</el-form-item>
</el-col>
</el-row>
</el-form>
</el-col>
</el-row>
<div v-if="confShowType === 'all'">
<codemirror
:autofocus="true"
placeholder="None data"
:indent-with-tab="true"
:tabSize="4"
style="margin-top: 10px; height: calc(100vh - 380px)"
:lineWrapping="true"
:matchBrackets="true"
theme="cobalt"
:styleActiveLine="true"
:extensions="extensions"
v-model="dockerConf"
:readOnly="true"
/>
<el-button :disabled="loading" type="primary" @click="onSaveFile" style="margin-top: 5px">
{{ $t('commons.button.save') }}
</el-button>
</div>
</el-card>
</el-form>
<div v-if="confShowType === 'all'">
<codemirror
:autofocus="true"
placeholder="None data"
:indent-with-tab="true"
:tabSize="4"
style="margin-top: 10px; height: calc(100vh - 380px)"
:lineWrapping="true"
:matchBrackets="true"
theme="cobalt"
:styleActiveLine="true"
:extensions="extensions"
v-model="dockerConf"
:readOnly="true"
/>
<el-button :disabled="loading" type="primary" @click="onSaveFile" style="margin-top: 5px">
{{ $t('commons.button.save') }}
</el-button>
</div>
</el-card>
<ConfirmDialog ref="confirmDialogRef" @confirm="onSubmitSave"></ConfirmDialog>
</div>
@ -111,7 +121,6 @@
<script lang="ts" setup>
import { ElMessage, FormInstance } from 'element-plus';
import FileList from '@/components/file-list/index.vue';
import { onMounted, reactive, ref } from 'vue';
import Submenu from '@/views/container/index.vue';
import { Codemirror } from 'vue-codemirror';
@ -121,20 +130,15 @@ import { LoadFile } from '@/api/modules/files';
import ConfirmDialog from '@/components/confirm-dialog/index.vue';
import i18n from '@/lang';
import { dockerOperate, loadDaemonJson, updateDaemonJson, updateDaemonJsonByfile } from '@/api/modules/container';
import { loadDaemonJsonPath, updateSetting } from '@/api/modules/setting';
const loading = ref(false);
const extensions = [javascript(), oneDark];
const confShowType = ref('base');
const daemonJsonPath = ref();
const loadLoadDir = async (path: string) => {
daemonJsonPath.value = path;
};
const form = reactive({
status: '',
version: '',
mirrors: '',
registries: '',
liveRestore: false,
@ -177,22 +181,9 @@ const onOperator = async (operation: string) => {
ElMessage.success(i18n.global.t('commons.msg.operationSuccess'));
};
const savePath = async () => {
let param = {
key: 'DaemonJsonPath',
value: daemonJsonPath.value,
};
await updateSetting(param);
changeMode();
ElMessage.success(i18n.global.t('commons.msg.operationSuccess'));
};
const onSubmitSave = async () => {
if (confShowType.value === 'all') {
let param = {
file: dockerConf.value,
path: daemonJsonPath.value,
};
let param = { file: dockerConf.value };
loading.value = true;
await updateDaemonJsonByfile(param)
.then(() => {
@ -208,6 +199,7 @@ const onSubmitSave = async () => {
let itemRegistries = form.registries.split('\n');
let param = {
status: form.status,
version: '',
registryMirrors: itemMirrors.filter(function (el) {
return el !== null && el !== '' && el !== undefined;
}),
@ -229,19 +221,14 @@ const onSubmitSave = async () => {
});
};
const loadMysqlConf = async () => {
const res = await LoadFile({ path: daemonJsonPath.value });
const loadDockerConf = async () => {
const res = await LoadFile({ path: '/etc/docker/daemon.json' });
dockerConf.value = res.data;
};
const loadPath = async () => {
const res = await loadDaemonJsonPath();
daemonJsonPath.value = res.data;
};
const changeMode = async () => {
if (confShowType.value === 'all') {
loadMysqlConf();
loadDockerConf();
} else {
search();
}
@ -250,6 +237,7 @@ const changeMode = async () => {
const search = async () => {
const res = await loadDaemonJson();
form.status = res.data.status;
form.version = res.data.version;
form.cgroupDriver = res.data.cgroupDriver;
form.liveRestore = res.data.liveRestore;
form.mirrors = res.data.registryMirrors ? res.data.registryMirrors.join('\n') : '';
@ -257,7 +245,21 @@ const search = async () => {
};
onMounted(() => {
loadPath();
search();
});
</script>
<style lang="scss">
.app-card {
font-size: 14px;
height: 60px;
}
.app-content {
height: 50px;
}
body {
margin: 0;
}
</style>