本文共 7983 字,大约阅读时间需要 26 分钟。
详细的说明如何利用kubernetes api创建一个支持多集群的k8s后台,这里主要实现调用kubernetes api获取查看service服务,pod服务。下一篇再说明如果操作一个service,以及注入容器console
python manage.py startapp cluster
pip install djangorestframework
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 makemigrationspython 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的方式进行连接,当然也可以用证书认证的方式
from rest_framework import serializersfrom cluster.models import Clusterclass ClusterSerializer( serializers.ModelSerializer ): class Meta: model = Cluster fields = '__all__'
# /api/cluster/class ClusterViewSet( viewsets.ModelViewSet ): queryset = Cluster.objects.all() serializer_class = ClusterSerializer # permission_classes = (IsAuthenticated,) parser_classes = (JSONParser,)
REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', )}
from django.contrib import adminfrom .models import Clusteradmin.site.register(Cluster)
from cluster import views as cluster_viewsrouter = 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方式
加入kubernetes api,开始调试kubernetes
pip install kubernetes
from pprint import pprintfrom django.shortcuts import get_object_or_404from django.shortcuts import renderfrom kubernetes.client import Configuration, ApiClient, CoreV1Apifrom rest_framework import viewsetsfrom rest_framework.decorators import actionfrom rest_framework.parsers import JSONParserfrom cluster.models import Clusterfrom .serializers import ClusterSerializerdef 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 configurationdef 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的连接也放在这里,当如果正式的项目,应该放在一个独立的文件,创建成连接池管理,再通过引用提供到这里使用
上面的list用到一个table.html模板,内容如下
{ { item }} | {% endfor %}
---|
{ { eny }} | {% endfor %}
{ { item }} | {% endfor %}
项目中添加一个dashboard目录,目录下添加init.py,views.py文件
from django.shortcuts import renderfrom cluster.models import Clusterdef cluster_main(request): result = {} result['clusters'] = Cluster.objects.all() return render(request,'main.html',{'result':result})
from django.contrib import adminfrom django.urls import pathfrom django.conf.urls import includefrom rest_framework.routers import DefaultRouterfrom cluster import views as cluster_viewsfrom dashboard import views as dashboard_viewsrouter = 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 %}K8s 多集群管理测试
好了,完成这些后,终于做完了,现在可以测试下,完成的页面就是上面的显示图片,下面来讲讲kubernetes api的使用
如果想要连接k8s接口并操作,需要的步骤
configuration = Configuration()configuration.verify_ssl = Falseconfiguration.host = cluster.apiconfiguration.api_key['authorization'] = cluster.tokenconfiguration.api_key_prefix['authorization'] = 'Bearer'
根据config创建一个CoreV1Api,这个类下包含多个操作k8s的接口方法
api_client = ApiClient( configuration )本文的×××目录:
转载于:https://blog.51cto.com/brucewang/2156305