云计算入门到精通

举报
yd_276641118 发表于 2023/09/19 23:26:26 2023/09/19
【摘要】 当谈到云计算时,通常指的是通过互联网提供计算资源和服务的一种模型。云计算使用户能够通过云服务提供商(如亚马逊AWS、微软Azure、谷歌云等)按需获取计算资源,而无需拥有和管理这些资源的物理基础设施。云计算的主要特点包括:弹性伸缩: 云计算允许用户根据实际需求快速扩展或缩减计算资源。用户可以根据业务负载的变化,自动或手动地增加或减少计算能力,以确保资源的高效利用。按需自助服务: 用户可以根据...

当谈到云计算时,通常指的是通过互联网提供计算资源和服务的一种模型。云计算使用户能够通过云服务提供商(如亚马逊AWS、微软Azure、谷歌云等)按需获取计算资源,而无需拥有和管理这些资源的物理基础设施。

云计算的主要特点包括:

弹性伸缩: 云计算允许用户根据实际需求快速扩展或缩减计算资源。用户可以根据业务负载的变化,自动或手动地增加或减少计算能力,以确保资源的高效利用。

按需自助服务: 用户可以根据自己的需求,在云服务提供商的管理界面或API上自助选择和配置所需的计算资源。这种自助服务的模式使用户能够快速获取和使用所需的资源,无需等待繁琐的审批和设置过程。

共享资源池: 云计算提供商通过将计算资源池化,使多个用户能够共享相同的物理资源。这种共享模式可以提高资源的利用率,减少资源浪费,并为用户提供灵活和经济高效的计算服务。

网络访问: 云计算通过互联网提供计算资源和服务。用户可以通过网络连接访问云服务提供商的数据中心,无论是从办公室、家庭还是其他任何地方,只要有网络连接即可使用云计算服务。

云计算提供了多种服务模型,包括:

基础设施即服务(IaaS): 提供虚拟化的计算资源,如虚拟机、存储和网络。用户可以在虚拟化的基础设施上构建自己的应用程序和软件环境,并对底层基础设施进行更细粒度的控制。

平台即服务(PaaS): 提供了一个完整的应用程序开发和部署平台,包括运行时环境、开发工具和自动化管理服务。用户可以使用PaaS来开发、测试和部署应用程序,而不需要关注底层的基础设施。

软件即服务(SaaS): 提供完整的应用程序作为云服务。用户可以直接通过互联网访问和使用软件应用程序,而无需自己安装、配置和管理软件。
[root@ecs-37c4 bundle]# yum install -y npm nodejs gcc make epel-release GraphicsMagick
[root@ecs-37c4 server]# yum groupinstall ‘Development Tools’ gcc-c++
[root@ecs-37c4 bundle]# node -v
v16.17.0

使用nodejs的包管理工具 全局安装n命令

[root@ecs-37c4 bundle]# npm install -g n

使用n命令切换nodejs版本

[root@ecs-37c4 bundle]# n v12.16.1
installing : node-v12.16.1
[root@ecs-37c4 ~]# node -v
v12.16.1
[root@ecs-37c4 ~]# cd bundle/programs/server/

使用node的包管理工具npm来自动解决依赖

会基于当前路径下的package.json来安装一系列的依赖包

[root@ecs-37c4 server]# npm i
[root@ecs-37c4 bundle]# cat README
This is a Meteor application bundle. It has only one external dependency:
Node.js v12.16.1. To run the application:

$ (cd programs/server && npm install)
$ export MONGO_URL=‘mongodb://user:password@host:port/databasename’
$ export ROOT_URL=‘http://example.com
$ export MAIL_URL=‘smtp://user:password@mailhost:port/’
$ node main.js

Use the PORT environment variable to set the port where the
application will listen. The default is 80, but that will require
root on most systems.

Find out more about Meteor at meteor.com.
export MONGO_URL=‘mongodb://127.0.0.1:27017/rocketchat’
export ROOT_URL=‘http://60.204.203.211:3000
export PORT=3000
export MONGO_OPLOG_URL=mongodb://127.0.0.1:27017/local?replicaSet=rs
[root@ecs-37c4 bundle]# node main.js
LocalStore: store created at
LocalStore: store created at
LocalStore: store created at
Setting default file store to GridFS
{“line”:“120”,“file”:“migrations.js”,“message”:“Migrations: Not migrating, already at version 205”,“time”:{"$date":1669534706046},“level”:“info”}
Loaded the Apps Framework and loaded a total of 0 Apps!
Using GridFS for custom sounds storage
Using GridFS for custom emoji storage
Browserslist: caniuse-lite is outdated. Please run next command npm update
➔ System ➔ startup
➔ ±------------------------------------------------+
➔ | SERVER RUNNING |
➔ ±------------------------------------------------+
➔ | |
➔ | Rocket.Chat Version: 3.6.0 |
➔ | NodeJS Version: 12.16.1 - x64 |
➔ | MongoDB Version: 4.4.18 |
➔ | MongoDB Engine: wiredTiger |
➔ | Platform: linux |
➔ | Process Port: 3000 |
➔ | Site URL: http://123.60.89.76:3000 |
➔ | ReplicaSet OpLog: Enabled |
➔ | Commit Hash: 071d72ebdc |
➔ | Commit Branch: HEAD |
➔ | |
➔ ±------------------------------------------------+
Updating process.env.MAIL_URL

[root@test ~]# tar xf wordpress-13.0.23.tgz
[root@test ~]# cd wordpress/
[root@test wordpress]# vi values.yaml
514 type: NodePort
665 enabled: false
1061 persistence:
1062 enabled: false
[root@test wordpress]# helm install wp-admin .

[root@test wordpress]# kubectl create ns chartmuseum
[root@test wordpress]# vim chartmuseum.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: chartmuseum
name: chartmuseum
namespace: chartmuseum
spec:
replicas: 1
selector:
matchLabels:
app: chartmuseum
template:
metadata:
labels:
app: chartmuseum
spec:
containers:
- image: bitnami/chartmuseum:latest
imagePullPolicy: IfNotPresent
name: chartmuseum
ports:
- containerPort: 8080
protocol: TCP
env:
- name: DEBUG
value: “1”
- name: STORAGE
value: local
- name: STORAGE_LOCAL_ROOTDIR
value: /charts
[root@test wordpress]# kubectl apply -f chartmuseum.yaml
[root@test wordpress]# kubectl expose deployment chartmuseum -n chartmuseum --name chartmuseum --port 8080 --target-port 8080
[root@test wordpress]# curl -L $(kubectl -n chartmuseum get service chartmuseum -o jsonpath=’{.spec.clusterIP}:{.spec.ports[].targetPort}’)

<!DOCTYPE html> <html> <head> <title>Welcome to ChartMuseum!</title> <style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; } </style> </head> <body>

Welcome to ChartMuseum!

If you see this page, the ChartMuseum web server is successfully installed and working.

For online documentation and support please refer to the GitHub project.

Thank you for using ChartMuseum.

</body> </html> ```python import os

from dotenv import load_dotenv
from fastapi import APIRouter
from fastapi import FastAPI
from fastapi import File
from fastapi import Form
from fastapi import UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi_gateway import route
from starlette import status
from starlette.requests import Request
from starlette.responses import Response

from models import User
from models import DeviceModel
from models import Name
from models import Device
from models import Label

#后续可以在Dockerfile里传.env文件,并将环境变量写进文件中,从中读取读取变量
load_dotenv()
#创建 1个服务网关
app = FastAPI(title=“API Gateway”)
#微服务 地址 gatway_endpint

http://localedge:30850/cloudedge/

router = APIRouter(prefix="/cloudedge")

ENV SERVICE_CLOUD_EDGE_URL=“http://192.168.100.70:8045

ENV SERVICE_USER_URL=“http://192.168.100.70:8046

ENV SERVICE_CLOUD_URL=“http://192.168.100.70:8047

ENV SERVICE_AI_URL=“http://192.168.100.70:8048

SERVICE_CLOUD_EDGE_URL = os.environ.get(‘SERVICE_CLOUD_EDGE_URL’) if os.environ.get(‘SERVICE_CLOUD_EDGE_URL’) else “http://127.0.0.1:8045
SERVICE_USER_URL = os.environ.get(‘SERVICE_USER_URL’) if os.environ.get(‘SERVICE_USER_URL’) else “http://127.0.0.1:8046
SERVICE_CLOUD_URL = os.environ.get(‘SERVICE_CLOUD_URL’) if os.environ.get(‘SERVICE_CLOUD_URL’) else “http://127.0.0.1:8070
SERVICE_AI_URL = os.environ.get(‘SERVICE_AI_URL’) if os.environ.get(‘SERVICE_AI_URL’) else “http://127.0.0.1:8048

app.add_middleware(
CORSMiddleware,
allow_origins=[""],
allow_credentials=True,
allow_methods=["
"],
allow_headers=["*"],
)

@route(
request_method=router.post,
service_url=SERVICE_USER_URL,
gateway_path="/register",
service_path="/register",
status_code=status.HTTP_200_OK,
override_headers=False,
body_params=[“RegisterUser”],
tags=[“Edge_User”],
)
async def check_params(RegisterUser: User, request: Request, response: Response):
pass

@route(
request_method=router.post,
service_url=SERVICE_USER_URL,
gateway_path="/login",
service_path="/login",
status_code=status.HTTP_200_OK,
override_headers=False,
body_params=[“LoginUser”],
tags=[“Edge_User”],
)
async def check_params(LoginUser: User, request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_URL,
gateway_path="/node/cloudnode",
service_path="/node/cloudnode",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_URL,
gateway_path="/node/edgenode",
service_path="/node/edgenode",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_URL,
gateway_path="/nodes/{nodename}",
service_path="/nodes/{nodename}",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_URL,
gateway_path="/metrics/node/{nodename}",
service_path="/metrics/node/{nodename}",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_URL,
gateway_path="/node/label/{nodename}",
service_path="/node/label/{nodename}",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.put,
service_url=SERVICE_CLOUD_URL,
gateway_path="/node/label",
service_path="/node/label",
status_code=status.HTTP_200_OK,
override_headers=False,
body_params=[“Label”],
)
async def check_params(Label: Label,request: Request, response: Response):
pass

@route(
request_method=router.delete,
service_url=SERVICE_CLOUD_URL,
gateway_path="/node/label",
service_path="/node/label",
status_code=status.HTTP_200_OK,
override_headers=False,
body_params=[“Label”],

)
async def check_params(Label: Label,request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_URL,
gateway_path="/node/join",
service_path="/join",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/pod/{namespace}",
service_path="/pod/{namespace}",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/device/{name}",
service_path="/device/{name}",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/devicemodel/devicemodel",
service_path="/devicemodel/devicemodel",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/devicemodel/{name}",
service_path="/devicemodel/{name}",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

@route(
request_method=router.post,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/device/device",
service_path="/device/device",
status_code=status.HTTP_200_OK,
override_headers=False,
body_params=[“Device”],
)
async def check_params(Device: Device,request: Request, response: Response):
pass

@route(
request_method=router.delete,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/device/device",
service_path="/device/device",
status_code=status.HTTP_200_OK,
override_headers=False,
body_params=[“Name”],
)
async def check_params(Name: Name,request: Request, response: Response):
pass

@route(
request_method=router.post,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/devicemodel/devicemodel",
service_path="/devicemodel/devicemodel",
status_code=status.HTTP_200_OK,
body_params=[“DeviceModel”],
override_headers=False,
)
async def check_params(DeviceModel: DeviceModel,request: Request, response: Response):
pass

@route(
request_method=router.put,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/devicemodel/devicemodel",
service_path="/devicemodel/devicemodel",
status_code=status.HTTP_200_OK,
body_params=[“DeviceModel”],
override_headers=False,
)
async def check_params(DeviceModel: DeviceModel,request: Request, response: Response):
pass

@route(
request_method=router.delete,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/device/devicemodel",
service_path="/device/devicemodel",
status_code=status.HTTP_200_OK,
body_params=[“Name”],
override_headers=False,
)
async def check_params(Name: Name,request: Request, response: Response):
pass

@route(
request_method=router.get,
service_url=SERVICE_CLOUD_EDGE_URL,
gateway_path="/svc_data/svc_data/",
service_path="/svc_data/svc_data/",
status_code=status.HTTP_200_OK,
override_headers=False,
)
async def check_params(request: Request, response: Response):
pass

app.mount("/static", StaticFiles(directory=“static”), name=“static”)
app.include_router(router)

if name == ‘main’:
import uvicorn
uvicorn.run(app=‘main:app’, host=‘0.0.0.0’, port=8050, reload=True)

from pydantic import BaseModel

class User(BaseModel):
username: str
password: str

class Name(BaseModel):
name: str

class DeviceModel(BaseModel):
name: str
properties: list

class Device(BaseModel):
dmName: str
name: str
nodeName: str

class Label(BaseModel):
label_key: str
label_value: str
node_name: str

from fastapi import APIRouter,status
from fastapi import FastAPI
from kubernetes import client,config
import os,json,base64
from pathlib import Path
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

router = APIRouter()

base_dir = Path(file).resolve().parent.parent
config.load_kube_config(config_file=os.path.join(base_dir,‘k8s_config’, ‘config’))
v1 = client.CoreV1Api()
cust_obj = client.CustomObjectsApi()
group = “metrics.k8s.io
version = “v1beta1”
plural = “nodes”

class Label(BaseModel):
label_key: str
label_value: str
node_name: str

@router.get("/node/cloudnode")
def list_cloudnode():
nodes = []
resp = v1.list_node(label_selector=“node-role.kubernetes.io/control-plane”)
for node in resp.items:
nodes.append(node.to_dict())
return nodes

@router.get("/node/edgenode")
def list_edgenode():
nodes = []
resp = v1.list_node(label_selector=“node-role.kubernetes.io/edge”)
for node in resp.items:
nodes.append(node.to_dict())
return nodes

@router.get("/nodes/{nodename}")
def get_node_detail(nodename: str):
node = v1.read_node(name=nodename)
return node.to_dict()

@router.get("/join")
def join_node():
return {“detail”: “f70d360dbf0bf764f9d341868c2c6003e2e5f6c1a4dcfa441dabcaa9fc3ae986.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTUxODM0ODN9.hTP8mgqSMNyM4S5V2oPKx-oF3P6W7yb3Y15jaYzL6bs”}

@router.get("/node/label/{nodename}")
def list_labels(nodename: str):
resp = v1.read_node_status(name=nodename)
return resp.metadata.to_dict()

@router.put("/node/label")
def create_label(label: Label):
body = {
“metadata”:{
“labels”:
{
label.label_key: label.label_value
}
}
}
v1.patch_node(name=label.node_name, body=body)
return {“detail”:“创建成功”}

@router.delete("/node/label")
def delete_label(label: Label):
body = {
“metadata”:{
“labels”:
{
label.label_key: None
}
}
}
v1.patch_node(name=label.node_name,body=body)
return {“detail”:“删除成功”}

@router.get("/metrics/node/{nodename}")
def metrics_node(nodename: str):
resp = v1.read_node_status(name=nodename)
return {
“usage”: {
“cpu”: resp.status.allocatable[“cpu”],
“memory”: resp.status.allocatable[“memory”],
}
}

@router.get("/svc_data/svc_data")
def list_svc_data():
return [1,2]

class Device(BaseModel):
dmName: str
name: str
nodeName: str

class Name(BaseModel):
name: str

@router.get("/device/{name}")
def list_devices(name: str):
devices = cust_obj.list_cluster_custom_object(group=group, version=version, plural=plural)
return devices

@router.post("/device/device")
def create_device(device: Device):
body = {
“apiVersion”: “devices.kubeedge.io/v1alpha2”,
“kind”: “Device”,
“metadata”: {
“name”: device.name
},
“spec”: {
“deviceModelRef”: {
“name”: device.dmName
},
“nodeSelector”: {
“nodeSelectorTerms”: [
{
“matchFields”: [
{
“key”: “kubernetes.io/hostname”,
“operator”: “Exist”,
“values”: [
device.nodeName
]
}
]
}
]
}
}
}
cust_obj.create_namespaced_custom_object(group=group, version=version, plural=plural, namespace=“default”,body=body)
return {“detail”: “创建成功”}

@router.delete("/device/device")
def delete_device(name: Name):
cust_obj.delete_namespaced_custom_object(group=group, version=version, plural=plural, namespace=“default”,name=name.name)
return {“detail”: “删除成功”}

import os
from pathlib import Path
from fastapi import APIRouter
from kubernetes import client, config
from pydantic import BaseModel
router = APIRouter()
base_dir = Path(file).resolve().parent.parent
config.load_kube_config(config_file=os.path.join(base_dir,‘k8s_config’, ‘config’))
api_client = client.ApiClient()
cust_obj = client.CustomObjectsApi()
group = “devices.kubeedge.io
version = “v1alpha2”
plural = “devicemodels”

class DeviceModel(BaseModel):
name: str
properties: list

class Name (BaseModel):
name: str

@router.get("/devicemodel/devicemodel")
def list_devices_model():
models = cust_obj.list_cluster_custom_object(group=group, version=version, plural=plural)
return models

@router.get("/devicemodel/{name}")
def list_devices_model(name: str):
model = cust_obj.get_namespaced_custom_object(group=group, version=version, plural=plural,namespace=“default”,name=name)
return model

@router.post("/devicemodel/devicemodel")
def list_devices_model(deviceModel: DeviceModel):
properties = []
for i in deviceModel.properties:
properties.append({‘name’: i})
body = {
“apiVersion”: “devices.kubeedge.io/v1alpha2”,
“kind”: “DeviceModel”,
“namespace”: “default”,
“metadata”: {
“name”: deviceModel.name,
},
“spec”: {
‘properties’: properties
}
}
cust_obj.create_namespaced_custom_object(group=group,version=version,plural=plural,namespace=“default”,body=body)
return {“detail”: “创建成功”}

@router.put("/devicemodel/devicemodel")
def update_device_model(deviceModel: DeviceModel):
properties = []
for i in deviceModel.properties:
properties.append({‘name’: i})
body = {
“apiVersion”: “devices.kubeedge.io/v1alpha2”,
“kind”: “DeviceModel”,
“namespace”: “default”,
“metadata”: {
“name”: deviceModel.name,
},
“spec”: {
‘properties’: properties
}
}
cust_obj.patch_namespaced_custom_object(group=group,version=version,plural=plural, namespace=“default”,name=deviceModel.name, body=body)
return {“detail”: “更新成功”}

@router.delete("/device/devicemodel")
def delete_device_model(name: Name):
cust_obj.delete_namespaced_custom_object(group=group,version=version,plural=plural,namespace=“default”,name=name.name)
return {“detail”: “删除成功”}

@router.get("/pod/{namespace}")
def list_pods(namespace: str):
pods = []
resp = v1.list_namespaced_pod(namespace=namespace,label_selector=“edge=service”)
for pod in resp.items:
pods.append(pod.to_dict())
return pods

service_url:“http://10.18.0.172:80/cloudedge/

     location  /cloudedge/ {
      proxy_pass http://10.18.0.172:30850/cloudedge/;
    }   

[root@k8s-master-node1 ~]# vi lifecycle.yaml
apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: nginx
    image: nginx:latest
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
      preStop:
        exec:
          command: ["/bin/sh", "-c", "nginx -s quit; while killall -0 nginx; do sleep 1; done"]
[root@k8s-master-node1 ~]# kubectl apply -f lifecycle.yaml 


[root@k8s-master-node1 ~]# kubectl create cronjob  date  --schedule='*/1 * * * *'   --image=busybox --dry-run -oyaml > date.yaml
[root@k8s-master-node1 ~]# vi date.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: date
spec:
  jobTemplate:
    metadata:
      name: date
    spec:
      template:
        metadata:
        spec:
          containers:
          - image: busybox
            name: hello
          restartPolicy: OnFailure
  schedule: '*/1 * * * *'  
[root@k8s-master-node1 ~]# kubectl apply -f date.yaml 


[root@k8s-master-node1 ~]# kubectl autoscale --max=1000 --min=1 deployment web --name=web --dry-run  -oyaml > hpa.yaml
#查看v2版本的话需要先查看支持的版本  kubectl api-versions |grep v2
#然后在执行     kubectl explain hpa --api-version=autoscaling/v2beta2   
[root@k8s-master-node1 ~]# vi hpa.yaml 
apiVersion: autoscaling/v2beta2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  maxReplicas: 1000
  minReplicas: 1
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: average
        averageValue: 80
      target:
        type: Utilization
        averageUtilization: 80
  scaleTargetRef:
    apiVersion: v1
    kind: Deployment
    name: nginx
  behavior:
    scaleUp:
      policies:
      - type: Percent
        value: 900
        periodSeconds: 5
[root@k8s-master-node1 ~]# kubectl apply -f hpa.yaml 

[root@iZbp1gcyso0vxpb7hz6p59Z ~]# mv kubezcloud /usr/local/bin/
[root@iZbp1gcyso0vxpb7hz6p59Z ~]# kubezcloud install dependencies     --host 172.16.1.15     --user root     --password Abc@1234     --offline-file /root/dependencies/base-rpms.tar.gz
[root@iZbp1gcyso0vxpb7hz6p59Z ~]#  kubezcloud install kubernetes     --master 172.16.1.15    --user root     --password Abc@1234     --version 1.22.1     --pod-cidr 10.244.0.0/16     --offline-file /root/kubernetes.tar.gz  
[root@k8s-master-node1 ~]# yum-config-manager --add-repo https://mirrors.aliyun.com/repo/Centos-7.repo
[root@k8s-master-node1 ~]# yum install -y unzip
[root@k8s-master-node1 ~]# unzip KubeEdge1.11.zip 
[root@k8s-master-node1 KubeEdge1.11]# ls
checksum_kubeedge-v1.11.1-linux-amd64.tar.gz.txt  kubeedge_pause.tar
cloudcore.tar                                     kubeedge-v1.11.1-linux-amd64.tar.gz
installation.tar                                  mosquitto.tar
keadm-v1.11.1-linux-amd64.tar.gz                  pause.tar
kubeedge-1.11.1.tar.gz
[root@k8s-master-node1 KubeEdge1.11]# docker load -i installation.tar
[root@k8s-master-node1 KubeEdge1.11]# docker load -i cloudcore.tar
[root@k8s-master-node1 KubeEdge1.11]# docker load -i kubeedge_pause.tar
[root@k8s-master-node1 KubeEdge1.11]# docker load -i pause.tar
[root@k8s-master-node1 KubeEdge1.11]# docker load -i mosquitto.tar 
[root@k8s-master-node1 KubeEdge1.11]# tar xf keadm-v1.11.1-linux-amd64.tar.gz 
[root@k8s-master-node1 KubeEdge1.11]# cp keadm-v1.11.1-linux-amd64/keadm/keadm /usr/local/bin/
[root@k8s-master-node1 KubeEdge1.11]# mkdir /etc/kubeedge
[root@k8s-master-node1 KubeEdge1.11]# cp checksum_kubeedge-v1.11.1-linux-amd64.tar.gz.txt kubeedge-v1.11.1-linux-amd64.tar.gz kubeedge-1.11.1.tar.gz /etc/kubeedge
[root@k8s-master-node1 KubeEdge1.11]# tar xf kubeedge-1.11.1.tar.gz  
[root@k8s-master-node1 KubeEdge1.11]# cp -r kubeedge-1.11.1/build/crds/ /etc/kubeedge/
[root@k8s-master-node1 KubeEdge1.11]# keadm deprecated init --advertise-address 121.40.179.62 --kubeedge-version 1.11.1 --tarballpath /etc/kubeedge/
[root@k8s-master-node1 KubeEdge1.11]# netstat -ntpl
tcp6       0      0 :::10000                :::*                    LISTEN      62360/cloudcore   
[root@k8s-master-node1 KubeEdge1.11]#  vi /etc/kubeedge/config/cloudcore.yaml 
43   cloudStream:
44     enable: true
105   router:
107     enable: true
[root@k8s-master-node1 KubeEdge1.11]# cp /etc/kubeedge/cloudcore.service /usr/lib/systemd/system/
[root@k8s-master-node1 KubeEdge1.11]# CLOUDCOREIPS=172.128.10.114 ./kubeedge-1.11.1/build/tools/certgen.sh stream 
[root@k8s-master-node1 KubeEdge1.11]# pkill cloudcore
[root@k8s-master-node1 KubeEdge1.11]# systemctl enable --now cloudcore


ubuntu@node-1:~$ sudo vi /etc/resolv.conf 
nameserver 223.5.5.5
ubuntu@node-1:~$ curl -O http://172.128.10.10/KubeEdge/KubeEdge1.11.zip
ubuntu@node-1:~$ sudo apt-get install unzip
ubuntu@node-1:~$ unzip KubeEdge1.11.zip
# step 1: 安装必要的一些系统工具
sudo apt-get update
sudo apt-get -y install apt-transport-https ca-certificates curl software-properties-common
# step 2: 安装GPG证书
curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add -
# Step 3: 写入软件源信息
sudo add-apt-repository "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
# Step 4: 更新并安装Docker-CE
sudo apt-get -y update
sudo apt-get -y install docker-ce

xxxxxxxxxx ubuntu@node-1:~/KubeEdge1.11$ sudo vi /etc/docker/daemon.json{"exec-opts": ["native.cgroupdriver=cgroupfs"]}ubuntu@node-1:~/KubeEdge1.11$ sudo systemctl daemon-reloadubuntu@node-1:~/KubeEdge1.11$ sudo systemctl restart docker

ubuntu@node-1:~$ sudo docker load -i KubeEdge1.11/mosquitto.tar 

ubuntu@node-1:~$ cd KubeEdge1.11/
ubuntu@node-1:~/KubeEdge1.11$ tar xf keadm-v1.11.1-linux-amd64.tar.gz 
ubuntu@node-1:~/KubeEdge1.11$ sudo cp keadm-v1.11.1-linux-amd64/keadm/keadm /usr/local/bin/

[root@k8s-master-node1 KubeEdge1.11]# keadm gettoken
64697d5769ff5f74882aae4d42a4792d0afee1f4190031e2ec8ea4d360b93c69.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTAyNjc1OTF9.Aqf_1KOgUHwJUB7wKZI9mIyxUjLXOrVSdCBP3ej61hs

ubuntu@node-1:~/KubeEdge1.11$ sudo vi /etc/resolv.conf 
ubuntu@node-1:~/KubeEdge1.11$ sudo keadm deprecated join --cloudcore-ipport 121.40.179.62:10000 --kubeedge-version 1.11.1 --token 64697d5769ff5f74882aae4d42a4792d0afee1f4190031e2ec8ea4d360b93c69.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTAyNjc1OTF9.Aqf_1KOgUHwJUB7wKZI9mIyxUjLXOrVSdCBP3ej61hs --image-repository docker.io

ubuntu@node-1:~/KubeEdge1.11$ sudo systemctl disable ufw

ubuntu@node-1:~/KubeEdge1.11$ sudo rm -rf /etc/kubeedge/
ubuntu@node-1:~/KubeEdge1.11$ sudo mkdir /etc/kubeedge/
ubuntu@node-1:~/KubeEdge1.11$ sudo cp checksum_kubeedge-v1.11.1-linux-amd64.tar.gz.txt kubeedge-v1.11.1-linux-amd64.tar.gz kubeedge-1.11.1.tar.gz /etc/kubeedge/
ubuntu@node-1:~/KubeEdge1.11$ sudo keadm deprecated join --cloudcore-ipport 121.40.179.62:10000 --kubeedge-version 1.11.1 --token 64697d5769ff5f74882aae4d42a4792d0afee1f4190031e2ec8ea4d360b93c69.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTAyNjc1OTF9.Aqf_1KOgUHwJUB7wKZI9mIyxUjLXOrVSdCBP3ej61hs --image-repository docker.io

# 用户提权
ubuntu@ubuntu-1:~$ sudo -i
root@ubuntu-1:~# vim /etc/kubeedge/config/edgecore.yaml 
36   edgeStream:
37     enable: true

root@ubuntu-1:~# systemctl restart edgecore



import os

from dotenv import load_dotenv
from fastapi import APIRouter
from fastapi import FastAPI
from fastapi import File
from fastapi import Form
from fastapi import UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi_gateway import route
from starlette import status
from starlette.requests import Request
from starlette.responses import Response


from models import User
from models import DeviceModel
from models import Name
from models import Device
from models import Label


#后续可以在Dockerfile里传.env文件,并将环境变量写进文件中,从中读取读取变量
load_dotenv()
#创建 1个服务网关
app = FastAPI(title="API Gateway")
#微服务 地址 gatway_endpint
# http://localedge:30850/cloudedge/
router = APIRouter(prefix="/cloudedge")


# ENV SERVICE_CLOUD_EDGE_URL="http://192.168.100.70:8045"
# ENV SERVICE_USER_URL="http://192.168.100.70:8046"
# ENV SERVICE_CLOUD_URL="http://192.168.100.70:8047"
# ENV SERVICE_AI_URL="http://192.168.100.70:8048"

SERVICE_CLOUD_EDGE_URL = os.environ.get('SERVICE_CLOUD_EDGE_URL') if os.environ.get('SERVICE_CLOUD_EDGE_URL') else "http://127.0.0.1:8045"
SERVICE_USER_URL = os.environ.get('SERVICE_USER_URL') if os.environ.get('SERVICE_USER_URL') else "http://127.0.0.1:8046"
SERVICE_CLOUD_URL = os.environ.get('SERVICE_CLOUD_URL') if os.environ.get('SERVICE_CLOUD_URL') else "http://127.0.0.1:8070"
SERVICE_AI_URL = os.environ.get('SERVICE_AI_URL') if os.environ.get('SERVICE_AI_URL') else "http://127.0.0.1:8048"


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@route(
    request_method=router.post,
    service_url=SERVICE_USER_URL,
    gateway_path="/register",
    service_path="/register",
    status_code=status.HTTP_200_OK,
    override_headers=False,
    body_params=["RegisterUser"],
    tags=["Edge_User"],
)
async def check_params(RegisterUser: User, request: Request, response: Response):
    pass



@route(
    request_method=router.post,
    service_url=SERVICE_USER_URL,
    gateway_path="/login",
    service_path="/login",
    status_code=status.HTTP_200_OK,
    override_headers=False,
    body_params=["LoginUser"],
    tags=["Edge_User"],
)
async def check_params(LoginUser: User, request: Request, response: Response):
    pass


@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/node/cloudnode",
    service_path="/node/cloudnode",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass


@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/node/edgenode",
    service_path="/node/edgenode",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass



@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/nodes/{nodename}",
    service_path="/nodes/{nodename}",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass


@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/metrics/node/{nodename}",
    service_path="/metrics/node/{nodename}",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass

@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/node/label/{nodename}",
    service_path="/node/label/{nodename}",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass


@route(
    request_method=router.put,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/node/label",
    service_path="/node/label",
    status_code=status.HTTP_200_OK,
    override_headers=False,
    body_params=["Label"],
)
async def check_params(Label: Label,request: Request, response: Response):
    pass


@route(
    request_method=router.delete,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/node/label",
    service_path="/node/label",
    status_code=status.HTTP_200_OK,
    override_headers=False,
    body_params=["Label"],

)
async def check_params(Label: Label,request: Request, response: Response):
    pass


@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_URL,
    gateway_path="/node/join",
    service_path="/join",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass



@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/pod/{namespace}",
    service_path="/pod/{namespace}",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass


@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/device/{name}",
    service_path="/device/{name}",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass



@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/devicemodel/devicemodel",
    service_path="/devicemodel/devicemodel",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass



@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/devicemodel/{name}",
    service_path="/devicemodel/{name}",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass


@route(
    request_method=router.post,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/device/device",
    service_path="/device/device",
    status_code=status.HTTP_200_OK,
    override_headers=False,
    body_params=["Device"],
)
async def check_params(Device: Device,request: Request, response: Response):
    pass


@route(
    request_method=router.delete,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/device/device",
    service_path="/device/device",
    status_code=status.HTTP_200_OK,
    override_headers=False,
    body_params=["Name"],
)
async def check_params(Name: Name,request: Request, response: Response):
    pass



@route(
    request_method=router.post,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/devicemodel/devicemodel",
    service_path="/devicemodel/devicemodel",
    status_code=status.HTTP_200_OK,
    body_params=["DeviceModel"],
    override_headers=False,
)
async def check_params(DeviceModel: DeviceModel,request: Request, response: Response):
    pass



@route(
    request_method=router.put,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/devicemodel/devicemodel",
    service_path="/devicemodel/devicemodel",
    status_code=status.HTTP_200_OK,
    body_params=["DeviceModel"],
    override_headers=False,
)
async def check_params(DeviceModel: DeviceModel,request: Request, response: Response):
    pass


@route(
    request_method=router.delete,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/device/devicemodel",
    service_path="/device/devicemodel",
    status_code=status.HTTP_200_OK,
    body_params=["Name"],
    override_headers=False,
)
async def check_params(Name: Name,request: Request, response: Response):
    pass



@route(
    request_method=router.get,
    service_url=SERVICE_CLOUD_EDGE_URL,
    gateway_path="/svc_data/svc_data/",
    service_path="/svc_data/svc_data/",
    status_code=status.HTTP_200_OK,
    override_headers=False,
)
async def check_params(request: Request, response: Response):
    pass

app.mount("/static", StaticFiles(directory="static"), name="static")
app.include_router(router)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app='main:app', host='0.0.0.0', port=8050, reload=True)


from pydantic import BaseModel

class User(BaseModel):
    username: str
    password: str

class Name(BaseModel):
    name: str

class DeviceModel(BaseModel):
    name: str
    properties: list
    
    
class Device(BaseModel):
    dmName: str    
    name: str      
    nodeName: str  
    

class Label(BaseModel):
    label_key: str
    label_value: str
    node_name: str



from fastapi import APIRouter,status
from fastapi import FastAPI
from kubernetes import client,config
import os,json,base64
from pathlib import Path
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

router = APIRouter()

base_dir = Path(__file__).resolve().parent.parent
config.load_kube_config(config_file=os.path.join(base_dir,'k8s_config', 'config'))
v1 = client.CoreV1Api()
cust_obj = client.CustomObjectsApi()
group = "metrics.k8s.io"
version = "v1beta1"
plural = "nodes"


class Label(BaseModel):
    label_key: str
    label_value: str
    node_name: str



@router.get("/node/cloudnode")
def list_cloudnode():
    nodes = []
    resp = v1.list_node(label_selector="node-role.kubernetes.io/control-plane")
    for node in resp.items:
        nodes.append(node.to_dict())
    return nodes



@router.get("/node/edgenode")
def list_edgenode():
    nodes = []
    resp = v1.list_node(label_selector="node-role.kubernetes.io/edge")
    for node in resp.items:
        nodes.append(node.to_dict())
    return nodes



@router.get("/nodes/{nodename}")
def get_node_detail(nodename: str):
    node = v1.read_node(name=nodename)
    return node.to_dict()



@router.get("/join")
def join_node():
    return {"detail": "f70d360dbf0bf764f9d341868c2c6003e2e5f6c1a4dcfa441dabcaa9fc3ae986.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2OTUxODM0ODN9.hTP8mgqSMNyM4S5V2oPKx-oF3P6W7yb3Y15jaYzL6bs"} 


@router.get("/node/label/{nodename}")
def list_labels(nodename: str):
    resp = v1.read_node_status(name=nodename)
    return resp.metadata.to_dict()


@router.put("/node/label")
def create_label(label: Label):
    body = {
        "metadata":{
            "labels":
                {
                    label.label_key: label.label_value
                }
            }
        }
    v1.patch_node(name=label.node_name, body=body)
    return  {"detail":"创建成功"}


@router.delete("/node/label")
def delete_label(label: Label):
    body = {
        "metadata":{
            "labels":
                {
                    label.label_key: None
                }
            }
        }
    v1.patch_node(name=label.node_name,body=body)
    return  {"detail":"删除成功"}



@router.get("/metrics/node/{nodename}")
def metrics_node(nodename: str):
    resp = v1.read_node_status(name=nodename)
    return {
        "usage": {
            "cpu": resp.status.allocatable["cpu"],
            "memory": resp.status.allocatable["memory"],
        }
    }
    

@router.get("/svc_data/svc_data")
def list_svc_data():
    return [1,2]









class Device(BaseModel):
    dmName: str    
    name: str      
    nodeName: str  


class Name(BaseModel):
    name: str


@router.get("/device/{name}")
def list_devices(name: str):
    devices = cust_obj.list_cluster_custom_object(group=group, version=version, plural=plural)
    return devices

@router.post("/device/device")
def create_device(device: Device):
    body = {
        "apiVersion": "devices.kubeedge.io/v1alpha2",
        "kind": "Device",
        "metadata": {
            "name": device.name
        },
        "spec": {
            "deviceModelRef": {
                "name": device.dmName
            },
            "nodeSelector": {
                "nodeSelectorTerms": [
                    {
                        "matchFields": [
                            {
                                "key": "kubernetes.io/hostname",
                                "operator": "Exist",
                                "values": [
                                    device.nodeName
                                ]
                            }
                        ]
                    }
                ]
            }
        }
    }
    cust_obj.create_namespaced_custom_object(group=group, version=version, plural=plural, namespace="default",body=body)
    return {"detail": "创建成功"}


@router.delete("/device/device")
def delete_device(name: Name):
    cust_obj.delete_namespaced_custom_object(group=group, version=version, plural=plural, namespace="default",name=name.name)
    return {"detail": "删除成功"}


import os
from pathlib import Path
from fastapi import APIRouter
from kubernetes import client, config
from pydantic import BaseModel
router = APIRouter()
base_dir = Path(__file__).resolve().parent.parent
config.load_kube_config(config_file=os.path.join(base_dir,'k8s_config', 'config'))
api_client = client.ApiClient()
cust_obj = client.CustomObjectsApi()
group = "devices.kubeedge.io"
version = "v1alpha2"
plural = "devicemodels"

class DeviceModel(BaseModel):
    name: str
    properties: list
    

class Name (BaseModel):
    name: str


@router.get("/devicemodel/devicemodel")
def list_devices_model():
    models = cust_obj.list_cluster_custom_object(group=group, version=version, plural=plural)
    return models



@router.get("/devicemodel/{name}")
def list_devices_model(name: str):
    model = cust_obj.get_namespaced_custom_object(group=group, version=version, plural=plural,namespace="default",name=name)
    return model



@router.post("/devicemodel/devicemodel")
def list_devices_model(deviceModel: DeviceModel):
    properties = []
    for i in deviceModel.properties:
        properties.append({'name': i})
    body = {
        "apiVersion": "devices.kubeedge.io/v1alpha2",
        "kind": "DeviceModel",
        "namespace": "default",
        "metadata": {
            "name": deviceModel.name,
        },
        "spec": {
            'properties': properties
        }
    }
    cust_obj.create_namespaced_custom_object(group=group,version=version,plural=plural,namespace="default",body=body)
    return {"detail": "创建成功"}



@router.put("/devicemodel/devicemodel")
def update_device_model(deviceModel: DeviceModel):
    properties = []
    for i in deviceModel.properties:
        properties.append({'name': i})
    body = {
        "apiVersion": "devices.kubeedge.io/v1alpha2",
        "kind": "DeviceModel",
        "namespace": "default",
        "metadata": {
            "name": deviceModel.name,
        },
        "spec": {
            'properties': properties
        }
    }
    cust_obj.patch_namespaced_custom_object(group=group,version=version,plural=plural, namespace="default",name=deviceModel.name, body=body)
    return {"detail": "更新成功"}



@router.delete("/device/devicemodel")
def delete_device_model(name: Name):
    cust_obj.delete_namespaced_custom_object(group=group,version=version,plural=plural,namespace="default",name=name.name)
    return {"detail": "删除成功"}


@router.get("/pod/{namespace}")
def list_pods(namespace: str):
    pods = []
    resp = v1.list_namespaced_pod(namespace=namespace,label_selector="edge=service")
    for pod in resp.items:
        pods.append(pod.to_dict())
    return pods


service_url:"http://10.18.0.172:80/cloudedge/"

         location  /cloudedge/ {
          proxy_pass http://10.18.0.172:30850/cloudedge/;
        }   
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。