详细的说明如何利用kubernetes api创建一个支持多集群的k8s后台,这里主要实现调用kubernetes api获取查看service服务,pod服务。下一篇再说明如果操作一个service,以及注入容器console
- 相关的组件
- Django (2.0.7)
- kubernetes (6.0.0)
- Django Rest Framework (3.8.2)
- Bootstrap 3.3.7
- Jquery 2.1.1
- pace 页面异步加载插件
- 新建一个基于django的k8s项目,命名为k8s_web_console
- 增加一个cluster应用
python manage.py startapp cluster
- 添加 Django Rest Framework
- 使用rest框架是方便做前后端分离,如果你是个全栈工程师,建议做前后端分离,这样方便维护。但这里为了入门快速方便,如果还要加一个node.js开发,比较麻烦,所以暂时保留这种可能,但还是用django的template方式开发。
pip install djangorestframework
- 在setting.py中加入rest框架
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘rest_framework‘,
‘cluster‘,
]
- 创建数据库以及数据表
python manage.py makemigrations
python manage.py migrate
- 打开cluster应用下的models.py添加一个k8s集群信息的model
class Cluster(models.Model): name = models.TextField() api = models.TextField() token = models.TextField() class Meta : db_table = "cluster" def __str__(self): return self.name
这里是k8s的连接通过api+token的方式进行连接,当然也可以用证书认证的方式
- name : 集群的名称
- api : k8s集群的api 链接
- token : k8s集群拥有admin权限的token
- cluster应用添加一个serializers.py文件
from rest_framework import serializers
from cluster.models import Cluster
class ClusterSerializer( serializers.ModelSerializer ):
class Meta:
model = Cluster
fields = ‘__all__‘
- rest 框架根据这里的配置对Cluster对象自动做序列化
- cluster 的view文件添加cluster的viewset
# /api/cluster/
class ClusterViewSet( viewsets.ModelViewSet ):
queryset = Cluster.objects.all()
serializer_class = ClusterSerializer
# permission_classes = (IsAuthenticated,)
parser_classes = (JSONParser,)
- rest 框架的parser有多种,这里用的是jsonparser,需要再settings.py 中添加如下配置
REST_FRAMEWORK = {
‘DEFAULT_PARSER_CLASSES‘: (
‘rest_framework.parsers.JSONParser‘,
)
}
- 编辑admin.py,将cluster注册到Django Admin后台
from django.contrib import admin
from .models import Cluster
admin.site.register(Cluster)
- urls.py 中设置下路由
from cluster import views as cluster_views
router = DefaultRouter()
router.register(r‘cluster‘, cluster_views.ClusterViewSet)
urlpatterns = [
path( ‘admin/‘, admin.site.urls ),
path( ‘api/‘, include( router.urls ) ),
path(‘api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘)),
]
- 测试下cluster的crud,以及rest api方式
- 运行django后,打开 http://127.0.0.1:8000/admin/cluster/cluster/
- 添加集群的信息
- 如果用rest 框架来看,就打开 http://127.0.0.1:8000/api/cluster/
- 加入kubernetes api,开始调试kubernetes
pip install kubernetes
- cluster应用的view修改如下
from pprint import pprint
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from kubernetes.client import Configuration, ApiClient, CoreV1Api
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.parsers import JSONParser
from cluster.models import Cluster
from .serializers import ClusterSerializer
def get_config(cluster):
‘‘‘
:param cluster: k8s集群的配置对象
:return: 返回一个config对象
‘‘‘
configuration = Configuration()
configuration.verify_ssl = False
configuration.host = cluster.api
configuration.api_key[‘authorization‘] = cluster.token
configuration.api_key_prefix[‘authorization‘] = ‘Bearer‘
return configuration
def get_clients(cluster):
‘‘‘
:param cluster: k8s集群对象
:return: 一个apiclient对象,一个coreV1Api对象
‘‘‘
api_client = ApiClient( get_config( cluster ) )
return api_client, CoreV1Api( api_client )
# /api/cluster/
class ClusterViewSet( viewsets.ModelViewSet ):
queryset = Cluster.objects.all()
serializer_class = ClusterSerializer
# permission_classes = (IsAuthenticated,)
parser_classes = (JSONParser,)
# /api/cluster/[pk]/list_service/
@action( detail=True, methods=[‘get‘] )
def list_service(self, request, pk=None):
cluster = get_object_or_404( Cluster, pk=pk )
api_client, core_v1_api = get_clients( cluster )
v1_service_list = core_v1_api.list_service_for_all_namespaces()
# pprint(v1_service_list)
result = {}
items = []
headers = [‘NAMESPACE‘, ‘NAME‘, ‘TYPE‘, ‘CLUSTER-IP‘, ‘SELF LINK‘]
for item in v1_service_list.items:
items.append( [item.metadata.namespace,
item.metadata.name,
item.spec.cluster_ip, item.spec.type, item.metadata.self_link
] )
result[‘items‘] = items
result[‘headers‘] = headers
result[‘caption‘] = "Services"
return render( request, "table.html", {‘result‘: result} )
# /api/cluster/[pk]/list_pod/
@action( detail=True, methods=[‘get‘] )
def list_pod(self, request, pk=None):
cluster = get_object_or_404( Cluster, pk=pk )
api_client, core_v1_api = get_clients( cluster )
v1_service_list = core_v1_api.list_pod_for_all_namespaces()
# pprint(v1_service_list)
result = {}
items = []
headers = [‘NAMESPACE‘, ‘NAME‘, ‘IP‘, ‘NODE‘]
for item in v1_service_list.items:
items.append( [
item.metadata.namespace,
item.metadata.name,
item.status.host_ip,
item.status.pod_ip,
] )
result[‘items‘] = items
result[‘headers‘] = headers
result[‘caption‘] = "Pods"
return render( request, "table.html", {‘result‘: result} )
因为这里仅作了一个cluster测试,所以这里将对k8s的连接也放在这里,当如果正式的项目,应该放在一个独立的文件,创建成连接池管理,再通过引用提供到这里使用
- 再次声明,如果是这里为了简单,仍然用了django的template模式,当如果前后端分离开发,返回应该是序列化后的json
上面的list用到一个table.html模板,内容如下
<table class="table table-hover " id="service-table">
<caption>{{ result.caption }}</caption>
<thead>
<tr>
{% for item in result.headers %}
<th>{{ item }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for item in result.items %}
<tr>
{% for eny in item %}
<td>{{ eny }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
{% for item in result.headers %}
<th>{{ item }}</th>
{% endfor %}
</tr>
</tfoot>
</table>
- 项目中添加一个dashboard目录,目录下添加init.py,views.py文件
- 为了做当前页面刷新,方便管理,所以多了一个dashboard来管理,views.py的内容如下
from django.shortcuts import render
from cluster.models import Cluster
def cluster_main(request):
result = {}
result[‘clusters‘] = Cluster.objects.all()
return render(request,‘main.html‘,{‘result‘:result})
- 在urls.py 中添加一条路由,最终内容如下
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from rest_framework.routers import DefaultRouter
from cluster import views as cluster_views
from dashboard import views as dashboard_views
router = DefaultRouter()
router.register(r‘cluster‘, cluster_views.ClusterViewSet)
urlpatterns = [
path( ‘admin/‘, admin.site.urls ),
path(‘dash/cluster‘,dashboard_views.cluster_main),
path( ‘api/‘, include( router.urls ) ),
path(‘api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘)),
]
dashboard 中用了一个main.html模板,使用的是bootstrap+jquery+pace,实现当前页面刷新:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>K8s 多集群管理测试</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/src/messagebox.css">
<link rel="stylesheet" href="{% static ‘plugins/pace/pace.min.css‘ %}">
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://mindmup.github.io/editable-table/mindmup-editabletable.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/messagebox.min.js"></script>
<script src="{% static ‘plugins/pace/pace.min.js‘ %}"></script>
</head>
<body>
<div class="container">
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">K8S Dashboard</a>
</div>
<form class="navbar-form navbar-left pull-right" role="search">
<div class="form-group">
<label for="k8s-api"></label>
<select class=" form-control" id="k8s-api">
<option value="#">选择集群</option>
{% for cluster in result.clusters %}
<option value="{{ cluster.id }}">{{ cluster.name }}</option>
{% endfor %}
</select>
</div>
</form>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
选择类型 <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="javascript:void(0);" onclick="load_table(‘/list_pod/‘)">Pod</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0);" onclick="load_table(‘/list_service/‘)">Service</a></li>
</ul>
</li>
</ul>
</div>
</nav>
<div id="table-div"></div>
</div>
<script type="application/javascript">
$(document).ajaxStart(function () {
Pace.restart()
});
function load_table(url_method) {
console.log(url_method);
k8s_select = $("#k8s-api");
k8s_id = k8s_select.val();
if (k8s_id === "#") {
$.MessageBox({
buttonDone: "OK",
message: "<center>先选择一个集群</center>",
queue: true,
speed: 200 ,
top: "25%" ,
});
return null;
}
url = ‘/api/cluster/‘ + k8s_id + url_method;
$.ajax({
url: url,
success: function (ex) {
console.log("success");
$(‘#table-div‘).html(ex);
},
error: function (ex) {
console.log(ex);
}
})
}
</script>
</body>
</html>
- 好了,完成这些后,终于做完了,现在可以测试下,完成的页面就是上面的显示图片,下面来讲讲kubernetes api的使用
- k8s api 的主页 https://github.com/kubernetes-client/python
- 主要的操作接口 : https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md
如果想要连接k8s接口并操作,需要的步骤
- 创建一个Configuration,这是k8s的连接配置信息,这里提供api接口跟token进行连接
configuration = Configuration() configuration.verify_ssl = False configuration.host = cluster.api configuration.api_key[‘authorization‘] = cluster.token configuration.api_key_prefix[‘authorization‘] = ‘Bearer‘
- 根据config创建一个CoreV1Api,这个类下包含多个操作k8s的接口方法
api_client = ApiClient( configuration ) - 如果想要查看所有的service,利用接口list_service_for_all_namespaces
本文的源码下载目录:http://down.51cto.com/data/2450296
原文地址:http://blog.51cto.com/brucewang/2156305
时间: 2024-10-07 18:14:52