Skip to content

Commit

Permalink
重新设计镜像拉取部分代码
Browse files Browse the repository at this point in the history
  • Loading branch information
llody55 committed Jul 8, 2024
1 parent 734a643 commit 3478521
Show file tree
Hide file tree
Showing 11 changed files with 226 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ coverage.xml
cover/

# Translations
*.mo
#*.mo
*.pot

# Django stuff:
Expand Down
51 changes: 51 additions & 0 deletions Dockerfile_bak
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# 第一阶段
FROM --platform=$TARGETPLATFORM python:3.9.10-slim as builder
ARG TARGETPLATFORM
ARG BUILDPLATFORM
ARG TARGETARCH

ENV PIP_CACHE_DIR=/app/.cache \
LANG=en_GB.UTF-8 \
DOCKER_HOST=unix:///var/run/docker.sock
#RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list
#RUN sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
libc6-dev \
libsqlite3-dev \
build-essential \
libssl-dev \
libffi-dev \
python3-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN python -m pip install --upgrade pip
#RUN pip install --no-cache-dir -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/ && python -m pip install Pillow -i https://mirrors.aliyun.com/pypi/simple/
RUN pip install --no-cache-dir -r requirements.txt

# 第二阶段
FROM python:3.9.10-slim

LABEL maintainer="llody55"

COPY --from=builder /usr/local/lib/python3.9 /usr/local/lib/python3.9

WORKDIR /app

COPY . /app

RUN mkdir /app/db

# 初始化数据库
RUN python manage.py migrate
RUN echo "from apps.models import CustomUser; CustomUser.objects.create_superuser('[email protected]','llody', '1qaz2wsx')" | python manage.py shell
RUN echo "from apps.models import Registries; registry = Registries(registries_name='dockerhub', registries_url='docker.io', registries_auth=False, registries_remarks='DockerHub'); registry.save()" | python manage.py shell
RUN echo "from apps.models import Registries; registry = Registries(registries_name='llody_proxy', registries_url='docker.llody.cn', registries_auth=False, registries_remarks='CF agent for Docker'); registry.save()" | python manage.py shell

RUN chmod +x start.sh

EXPOSE 9002
EXPOSE 8000

CMD ["./start.sh"]
1 change: 1 addition & 0 deletions apps/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
re_path("docker_container_batchrestart_api/",views.docker_container_batchrestart_api,name="docker_container_batchrestart_api"),
re_path("docker_logs/",views.docker_logs,name="docker_logs"), # 远程docker容器日志
re_path("docker_terminal/",views.docker_terminal,name="docker_terminal"), # 远程docker容器终端
re_path("docker_pull/",views.docker_pull_view,name="docker_pull"),

re_path("docker_image_info/",views.docker_image_info,name="docker_image_info"), # 远程docker镜像管理
re_path("docker_images_api/",views.docker_images_api,name="docker_images_api"), # 远程docker镜像管理API
Expand Down
6 changes: 5 additions & 1 deletion apps/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -828,6 +828,10 @@ def docker_terminal(request):
connect={"name":name,"container_id":container_id,"containers":containers}
return render(request, 'container/docker_terminal.html',{"connect":connect})

@login_required
def docker_pull_view(request):
return render(request, 'images/images_pull.html')

# 镜像管理
@login_required
def docker_image_info(request):
Expand Down Expand Up @@ -980,7 +984,7 @@ def process_image(image):
raw_password = docker_mod.decrypt_password(encrypted_password, key)
# 同步方法
# 容器管理模块API
print("接受的镜像仓库:",registries_url,raw_password)
print("接收的镜像仓库:",registries_url)
logger.error(image_name)
success, client = docker_mod.connect_to_docker()
if success:
Expand Down
Binary file added locale/en/LC_MESSAGES/django.mo
Binary file not shown.
Binary file added locale/zh_HANS/LC_MESSAGES/django.mo
Binary file not shown.
13 changes: 13 additions & 0 deletions templates/images/docker_images_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
{% if 'admin' in request.session.kube_user_role or request.user.is_superuser %}
<button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add">{% translate "拉取镜像" %}</button>
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="clear">{% translate "清理【none】镜像" %}</button>
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="pull">{% translate "PULL" %}</button>
{% endif %}
</script>
<!-- 行工具 -->
Expand Down Expand Up @@ -251,6 +252,18 @@
layer.close(index);
});
break
case 'pull':
layer.open({
type: 2,
area: ['600px', '70%'],
closeBtn: true,
title: "拉取镜像",
shift: 2,
shade: 0.2,
shadeClose: false,
content: '{% url "docker_pull" %}',
})
break
}
})

Expand Down
128 changes: 128 additions & 0 deletions templates/images/images_pull.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Docker Image Pull</title>
<link rel="stylesheet" href="/static/layui/css/layui.css"/>
<script src="/static/layui/layui.js"></script>
<style>
.log-entry {
margin-bottom: 10px;
}
.log-entry p {
margin: 0;
}
.progress-container {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="layui-container">
<div class="layui-row">
<div class="layui-col-md12">
<input type="text" id="image_name" class="layui-input" placeholder="Enter Docker Image Name">
<button class="layui-btn" id="pull_button">Pull Image</button>
</div>
<div class="layui-col-md12">
<div id="output"></div>
</div>
</div>
</div>

<script>
var protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
var socket = new WebSocket(protocol + window.location.host + '/apps/dockerpull/');
var output = document.getElementById('output');
var logEntries = {};

document.getElementById('pull_button').onclick = function() {
var imageName = document.getElementById('image_name').value;
output.innerHTML = ''; // 清空之前的日志
logEntries = {}; // 清空之前的日志条目
socket.send(JSON.stringify({
'image_name': imageName
}));
};

socket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data.message;

if (message.id) {
if (!logEntries[message.id]) {
// 创建新的日志条目
var logEntry = document.createElement('div');
logEntry.classList.add('log-entry');
logEntry.setAttribute('id', 'log-' + message.id);

var status = document.createElement('p');
status.innerHTML = '<strong>ID:</strong> ' + message.id + ' <strong>Status:</strong> ' + message.status;
logEntry.appendChild(status);

if (message.progressDetail && message.progressDetail.total > 0) {
var progress = (message.progressDetail.current / message.progressDetail.total * 100).toFixed(2);
var progressBarContainer = document.createElement('div');
progressBarContainer.classList.add('layui-progress', 'progress-container');
progressBarContainer.setAttribute('lay-showPercent', 'true');

var progressBar = document.createElement('div');
progressBar.classList.add('layui-progress-bar');
progressBar.setAttribute('lay-percent', progress + '%');
progressBar.style.width = progress + '%';

progressBarContainer.appendChild(progressBar);
logEntry.appendChild(progressBarContainer);
}

output.appendChild(logEntry);
logEntries[message.id] = logEntry;
layui.element.init(); // 重新初始化进度条
} else {
// 更新现有的日志条目
var existingEntry = logEntries[message.id];
existingEntry.querySelector('p').innerHTML = '<strong>ID:</strong> ' + message.id + ' <strong>Status:</strong> ' + message.status;
if (message.progressDetail && message.progressDetail.total > 0) {
var progress = (message.progressDetail.current / message.progressDetail.total * 100).toFixed(2);
var progressBar = existingEntry.querySelector('.layui-progress-bar');
if (!progressBar) {
// 如果进度条不存在,创建新的进度条
var progressBarContainer = document.createElement('div');
progressBarContainer.classList.add('layui-progress', 'progress-container');
progressBarContainer.setAttribute('lay-showPercent', 'true');

progressBar = document.createElement('div');
progressBar.classList.add('layui-progress-bar');
progressBar.setAttribute('lay-percent', progress + '%');
progressBar.style.width = progress + '%';

progressBarContainer.appendChild(progressBar);
existingEntry.appendChild(progressBarContainer);
} else {
progressBar.setAttribute('lay-percent', progress + '%');
progressBar.style.width = progress + '%';
}
layui.element.init(); // 重新初始化进度条
}
}
} else {
// 处理最终结果的情况
var finalStatus = document.createElement('div');
finalStatus.classList.add('log-entry');
finalStatus.innerHTML = '<p><strong>Final Status:</strong> ' + message.status + '</p>';
if (message.error) {
finalStatus.innerHTML += '<p><strong>Error:</strong> ' + message.error + '</p>';
finalStatus.classList.add('layui-bg-red'); // 添加红色背景表示错误
} else {
finalStatus.classList.add('layui-bg-green'); // 添加绿色背景表示成功
}
output.appendChild(finalStatus);
}
};

socket.onclose = function(e) {
console.error('WebSocket closed unexpectedly');
};
</script>
</body>
</html>
2 changes: 1 addition & 1 deletion udockers/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
#CSRF_TRUSTED_ORIGINS = ['https://add.llody.top']

# Application definition
VERSION = (1, 1, 3)
VERSION = (1, 1, 4)

VERSION_STR = '.'.join(map(str, VERSION))

Expand Down
24 changes: 24 additions & 0 deletions udockers/websocket/docker_image_pull_consumers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# consumers.py
import json
import docker
from channels.generic.websocket import WebsocketConsumer
# 引用验证是否开启TLS认证的公共模块
from apps.docker_mod import connect_to_docker

class DockerPullConsumer(WebsocketConsumer):
def connect(self):
self.accept()

def disconnect(self, close_code):
pass

def receive(self, text_data):
text_data_json = json.loads(text_data)
image_name = text_data_json['image_name']

success, client = connect_to_docker()
if success:
for line in client.api.pull(image_name, stream=True, decode=True):
self.send(text_data=json.dumps({
'message': line
}))
2 changes: 2 additions & 0 deletions udockers/websocket/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
from udockers.websocket.docker_logs_consumers import DockerLogConsumer
from udockers.websocket.docker_terminal_consumers import ProxyConsumer
from udockers.websocket.webssh_consumers import SSHConsumer
from udockers.websocket.docker_image_pull_consumers import DockerPullConsumer

websocket_urlpatterns =[
re_path(r'^apps/docker_logs/$', DockerLogConsumer.as_asgi(),name='docker_logs'),
re_path(r'^apps/docker_terminal/$', ProxyConsumer.as_asgi(),name='docker_terminal'),
re_path(r'^apps/webssh_terminal/$', SSHConsumer.as_asgi(),name='webssh_terminal'),
re_path(r'apps/dockerpull/$', DockerPullConsumer.as_asgi()),
]
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
Expand Down

0 comments on commit 3478521

Please sign in to comment.