--- /dev/null
+
+Step 1: Installed softwares:
+===========================
+Python: 3.12 (latest should work)
+Pip3
+Helm: v3.14.3 (latest should work)
+Kubernetes Client: v1.28.2 (latest should work)
+Kubernetes Server: v1.28.4 (latest should work)
+
+Step 2: Create virtul environment:
+=================================
+#pip installed using get-pip.py
+pip3 install virtualenv
+virtualenv venv_nfo
+
+source env/bin/activate # On Windows use `env\Scripts\activate`
+
+Step 3: Install Pip packages:
+============================
+pip3 install requests
+pip3 install django
+pip3 install djangorestframework
+pip3 install pyhelm
+pip3 install kubernetes
+
+
+python3 manage.py startapp apis //creates new app named apis
+
+Step 4: Change environment configurations in conig.ini
+======================================================
+Change Kubernetes config path
+Change Helm executable path
+
+Step 5: Run application:
+=======================
+python3 manage.py migrations
+python3 manage.py migrate
+python3 manage.py runserver
+
+Step 6: Run REST apis:
+=====================
+
+GET http://127.0.0.1:8000/nfo/api/v1/
+POST http://127.0.0.1:8000/nfo/api/v1/
+ {
+ "charts": [
+ {
+ "name": "cert-manager",
+ "version": "v1.8.x",
+ "repo": "https://charts.jetstack.io"
+
+ }
+ ]
+ }
+DELETE http://127.0.0.1:8000/nfo/api/v1/
+ {
+ "name": "cert-manager",
+ "namespace": "default"
+ }
+
+
+#Helm Client Library
+#https://github.com/stackhpc/pyhelm3
\ No newline at end of file
--- /dev/null
+from django.contrib import admin
+
+# Register your models here.
--- /dev/null
+from django.apps import AppConfig
+
+
+class ApisConfig(AppConfig):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'apis'
--- /dev/null
+# Generated by Django 5.0.3 on 2024-03-11 13:41
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='NFOModel',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('title', models.CharField(max_length=200)),
+ ('description', models.TextField()),
+ ],
+ ),
+ ]
--- /dev/null
+# Generated by Django 5.0.3 on 2024-03-13 10:03
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('apis', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.DeleteModel(
+ name='NFOModel',
+ ),
+ ]
--- /dev/null
+from django.db import models
+
+
+class NFOModel(models.Model):
+ title = models.CharField(max_length=200)
+ description = models.TextField()
+
+ def __str__(self):
+ return self.title
--- /dev/null
+# import serializer from rest_framework
+from rest_framework import serializers
+
+# import model from models.py
+from .models import NFOModel
+
+# Create a model serializer
+class NFOSerializer(serializers.HyperlinkedModelSerializer):
+ # specify model and fields
+ class Meta:
+ model = NFOModel
+ fields = ('title', 'description')
--- /dev/null
+from django.test import TestCase
+
+# Create your tests here.
--- /dev/null
+# basic URL Configurations
+from django.urls import include, path
+# import routers
+from rest_framework import routers
+
+# import everything from views
+from .views import *
+#from .views import api_home
+from . import views
+
+# define the router
+router = routers.DefaultRouter()
+
+# define the router path and viewset to be used
+#router.register(r'nfoapi', NFOViewSet)
+
+# specify URL Path for rest_framework
+urlpatterns = [
+ path('', views.api_home),
+ #path('', include(router.urls)),
+ path('api-auth/', include('rest_framework.urls'))
+]
--- /dev/null
+from django.shortcuts import render
+import pyhelm
+import asyncio
+from kubernetes import client
+from pyhelm3 import Client
+
+
+# Create your views here.
+# import viewsets
+from rest_framework import viewsets
+import json
+
+# import local data
+#from .serializers import NFOSerializer
+#from .models import NFOModel
+
+from django.http import JsonResponse
+
+
+async def api_home(request, *args, **kwargs):
+ body = request.body
+ data = {}
+ try:
+ data = json.loads(body)
+ except:
+ pass
+ #return JsonResponse({"message: Hi there"}, safe=False)
+ await asyncio.gather(process_helm_charts())
+ #process_helm_charts()
+ return JsonResponse(data)
+
+async def process_helm_charts():
+ print("Processing Helm charts")
+
+ # This will use the Kubernetes configuration from the environment
+ client = Client()
+ # Specify the kubeconfig file to use
+ client = Client(kubeconfig = "/home/fnclab/.kube/config")
+ # Specify a custom Helm executable (by default, we expect 'helm' to be on the PATH)
+ client = Client(executable = "/usr/local/bin/helm")
+
+ # List the deployed releases
+ releases = await client.list_releases(all = True, all_namespaces = True)
+ for release in releases:
+ revision = await release.current_revision()
+ print(release.name, release.namespace, revision.revision, str(revision.status))
+
+
+
+# create a viewset
+#class NFOViewSet(viewsets.ModelViewSet):
+ # define queryset
+ #queryset = NFOModel.objects.all()
+
+ # specify serializer to be used
+ #serializer_class = NFOSerializer
\ No newline at end of file
--- /dev/null
+[localpath]
+kubeconfig_file_path = /home/fnclab/.kube/config
+helm_executable_path = /usr/local/bin/helm
+
--- /dev/null
+from django.contrib import admin
+from helm.models import Application,OAI
+# Register your models here..
+
+class ApplicationAdmin(admin.ModelAdmin):
+ list_display=('app_name','about')
+ search_fields=('app_name',)
+
+class OAIAdmin(admin.ModelAdmin):
+ list_display=('oai_helm_chart_name','repo','version')
+ list_filter=('oai_helm_chart_name',)
+
+admin.site.register(Application,ApplicationAdmin)
+admin.site.register(OAI,OAIAdmin)
--- /dev/null
+from django.apps import AppConfig
+
+
+class HelmConfig(AppConfig):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'helm'
--- /dev/null
+# Generated by Django 5.0.3 on 2024-03-20 13:15
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='Application',
+ fields=[
+ ('app_id', models.AutoField(primary_key=True, serialize=False)),
+ ('app_name', models.CharField(max_length=50)),
+ ('location', models.CharField(max_length=50)),
+ ('about', models.TextField()),
+ ('type', models.CharField(choices=[('RAN', 'RAN'), ('CORE', 'CORE'), ('IT', 'IT')], max_length=100)),
+ ('added_date', models.DateTimeField(auto_now=True)),
+ ('active', models.BooleanField(default=True)),
+ ],
+ ),
+ migrations.CreateModel(
+ name='OAI',
+ fields=[
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+ ('oai_helm_chart_name', models.CharField(max_length=100)),
+ ('repo', models.CharField(max_length=50)),
+ ('version', models.TextField()),
+ ('description', models.TextField()),
+ ('company', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='helm.application')),
+ ],
+ ),
+ ]
--- /dev/null
+from django.db import models
+
+# Create your models here.
+
+#Creating Application Model
+
+class Application(models.Model):
+ app_id=models.AutoField(primary_key=True)
+ app_name= models.CharField(max_length=50)
+ location=models.CharField(max_length=50)
+ about=models.TextField()
+ type=models.CharField(max_length=100,choices=
+ (('RAN','RAN'),
+ ('CORE','CORE'),
+ ("IT",'IT')
+ ))
+ added_date=models.DateTimeField(auto_now=True)
+ active=models.BooleanField(default=True)
+
+ def __str__(self):
+ return self.name +'--'+ self.location
+
+
+
+#Employee Model
+class OAI(models.Model):
+ oai_helm_chart_name=models.CharField(max_length=100)
+ repo=models.CharField(max_length=50)
+ version=models.TextField()
+ description=models.TextField()
+
+
+ company=models.ForeignKey(Application, on_delete=models.CASCADE)
+
+
\ No newline at end of file
--- /dev/null
+from rest_framework import serializers
+from helm.models import Application,OAI
+
+
+#create serializers here
+class ApplicationSerializer(serializers.HyperlinkedModelSerializer):
+ appl_id=serializers.ReadOnlyField()
+ class Meta:
+ model=Application
+ fields="__all__"
+
+
+
+class OAISerializer(serializers.HyperlinkedModelSerializer):
+ id=serializers.ReadOnlyField()
+ class Meta:
+ model=OAI
+ fields="__all__"
\ No newline at end of file
--- /dev/null
+from django.test import TestCase
+
+# Create your tests here.
--- /dev/null
+from django.contrib import admin
+from django.urls import path,include
+from helm.views import ApplicationViewSet,OAIViewSet
+from rest_framework import routers
+
+
+router= routers.DefaultRouter()
+router.register(r'applications', ApplicationViewSet)
+router.register(r'oai', OAIViewSet)
+
+urlpatterns = [
+ path('',include(router.urls))
+
+]
+
+
+#companies/{companyId}/employees
\ No newline at end of file
--- /dev/null
+from django.shortcuts import render
+from rest_framework import viewsets
+from helm.models import Application,OAI
+from helm.serializers import ApplicationSerializer,OAISerializer
+from rest_framework.decorators import action
+from rest_framework.response import Response
+# Create your views here.
+class ApplicationViewSet(viewsets.ModelViewSet):
+ queryset= Application.objects.all()
+ serializer_class=ApplicationSerializer
+
+ #applications/{ApplicationId}/oai
+ @action(detail=True,methods=['get'])
+ def employees(self,request,pk=None):
+ try:
+ application=Application.objects.get(pk=pk)
+ emps=OAI.objects.filter(application=application)
+ emps_serializer=OAISerializer(emps,many=True,context={'request':request})
+ return Response(emps_serializer.data)
+ except Exception as e:
+ print(e)
+ return Response({
+ 'message':'application might not exists !! Error'
+ })
+
+
+class OAIViewSet(viewsets.ModelViewSet):
+ queryset=OAI.objects.all()
+ serializer_class=OAISerializer
\ No newline at end of file
--- /dev/null
+from django.contrib import admin
+from helmprocessor.models import Company,Employee
+# Register your models here..
+
+class CompanyAdmin(admin.ModelAdmin):
+ list_display=('name','location','type')
+ search_fields=('name',)
+
+class EmployeeAdmin(admin.ModelAdmin):
+ list_display=('name','email','company')
+ list_filter=('company',)
+
+admin.site.register(Company,CompanyAdmin)
+admin.site.register(Employee,EmployeeAdmin)
--- /dev/null
+from django.apps import AppConfig
+
+
+class ApitestConfig(AppConfig):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'helmprocessor'
--- /dev/null
+from django.db import models
+
+# Create your models here.
+
+#Creating Company Model
+
+class Company(models.Model):
+ company_id=models.AutoField(primary_key=True)
+ name= models.CharField(max_length=50)
+ location=models.CharField(max_length=50)
+ about=models.TextField()
+ type=models.CharField(max_length=100,choices=
+ (('IT','IT'),
+ ('Non IT','Non IT'),
+ ("Mobiles Phones",'Mobile Phones')
+ ))
+ added_date=models.DateTimeField(auto_now=True)
+ active=models.BooleanField(default=True)
+
+ def __str__(self):
+ return self.name +'--'+ self.location
+
+
+
+#Employee Model
+class Employee(models.Model):
+ name=models.CharField(max_length=100)
+ email=models.CharField(max_length=50)
+ address=models.CharField(max_length=200)
+ phone=models.CharField(max_length=10)
+ about=models.TextField()
+ position=models.CharField(max_length=50,choices=(
+ ('Manager','manager'),
+ ('Software Developer','sd'),
+ ('Project Leader','pl')
+ ))
+
+ company=models.ForeignKey(Company, on_delete=models.CASCADE)
+
+
\ No newline at end of file
--- /dev/null
+from rest_framework import serializers
+from helmprocessor.models import Company,Employee
+
+
+#create serializers here
+class CompanySerializer(serializers.HyperlinkedModelSerializer):
+ company_id=serializers.ReadOnlyField()
+ class Meta:
+ model=Company
+ fields="__all__"
+
+
+
+class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
+ id=serializers.ReadOnlyField()
+ class Meta:
+ model=Employee
+ fields="__all__"
\ No newline at end of file
--- /dev/null
+from django.test import TestCase
+
+# Create your tests here.
--- /dev/null
+from django.contrib import admin
+from django.urls import path,include
+from helmprocessor.views import CompanyViewSet,EmployeeViewSet
+from rest_framework import routers
+
+
+router= routers.DefaultRouter()
+router.register(r'companies', CompanyViewSet)
+router.register(r'employees', EmployeeViewSet)
+
+urlpatterns = [
+ path('',include(router.urls))
+
+]
+
+
+#companies/{companyId}/employees
\ No newline at end of file
--- /dev/null
+from django.shortcuts import render
+from rest_framework import viewsets
+from helmprocessor.models import Company,Employee
+from helmprocessor.serializers import CompanySerializer,EmployeeSerializer
+from rest_framework.decorators import action
+from rest_framework.response import Response
+# Create your views here.
+class CompanyViewSet(viewsets.ModelViewSet):
+ queryset= Company.objects.all()
+ serializer_class=CompanySerializer
+
+ #companies/{companyId}/emplyees
+ @action(detail=True,methods=['get'])
+ def employees(self,request,pk=None):
+ try:
+ company=Company.objects.get(pk=pk)
+ emps=Employee.objects.filter(company=company)
+ emps_serializer=EmployeeSerializer(emps,many=True,context={'request':request})
+ return Response(emps_serializer.data)
+ except Exception as e:
+ print(e)
+ return Response({
+ 'message':'Company might not exists !! Error'
+ })
+
+
+class EmployeeViewSet(viewsets.ModelViewSet):
+ queryset=Employee.objects.all()
+ serializer_class=EmployeeSerializer
\ No newline at end of file
--- /dev/null
+#!/usr/bin/env python
+"""Django's command-line utility for administrative tasks."""
+import os
+import sys
+
+
+def main():
+ """Run administrative tasks."""
+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nfo_microservice.settings')
+ try:
+ from django.core.management import execute_from_command_line
+ except ImportError as exc:
+ raise ImportError(
+ "Couldn't import Django. Are you sure it's installed and "
+ "available on your PYTHONPATH environment variable? Did you "
+ "forget to activate a virtual environment?"
+ ) from exc
+ execute_from_command_line(sys.argv)
+
+
+if __name__ == '__main__':
+ main()
--- /dev/null
+"""
+ASGI config for nfo_microservice project.
+
+It exposes the ASGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
+"""
+
+import os
+
+from django.core.asgi import get_asgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nfo_microservice.settings')
+
+application = get_asgi_application()
--- /dev/null
+"""
+Django settings for nfo_microservice project.
+
+Generated by 'django-admin startproject' using Django 5.0.3.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/5.0/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/5.0/ref/settings/
+"""
+
+from pathlib import Path
+
+# Build paths inside the project like this: BASE_DIR / 'subdir'.
+BASE_DIR = Path(__file__).resolve().parent.parent
+
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'django-insecure-@2#ob=f_mn7-8#)(v+*yc9yx3(l(h&av5rjna5$)gv4qevq61v'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+ALLOWED_HOSTS = []
+
+
+# Application definition
+
+INSTALLED_APPS = [
+ 'django.contrib.admin',
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.messages',
+ 'django.contrib.staticfiles',
+ 'rest_framework',
+ 'apis',
+ 'helmprocessor',
+ 'helm',
+]
+
+MIDDLEWARE = [
+ 'django.middleware.security.SecurityMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.middleware.common.CommonMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.contrib.messages.middleware.MessageMiddleware',
+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
+]
+
+ROOT_URLCONF = 'nfo_microservice.urls'
+
+TEMPLATES = [
+ {
+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
+ 'DIRS': [],
+ 'APP_DIRS': True,
+ 'OPTIONS': {
+ 'context_processors': [
+ 'django.template.context_processors.debug',
+ 'django.template.context_processors.request',
+ 'django.contrib.auth.context_processors.auth',
+ 'django.contrib.messages.context_processors.messages',
+ ],
+ },
+ },
+]
+
+WSGI_APPLICATION = 'nfo_microservice.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': BASE_DIR / 'db.sqlite3',
+ }
+}
+
+
+# Password validation
+# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
+
+AUTH_PASSWORD_VALIDATORS = [
+ {
+ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
+ },
+ {
+ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
+ },
+ {
+ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
+ },
+ {
+ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
+ },
+]
+
+
+# Internationalization
+# https://docs.djangoproject.com/en/5.0/topics/i18n/
+
+LANGUAGE_CODE = 'en-us'
+
+TIME_ZONE = 'UTC'
+
+USE_I18N = True
+
+USE_TZ = True
+
+
+# Static files (CSS, JavaScript, Images)
+# https://docs.djangoproject.com/en/5.0/howto/static-files/
+
+STATIC_URL = 'static/'
+
+# Default primary key field type
+# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
+
+DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
--- /dev/null
+"""
+URL configuration for nfo_microservice project.
+
+The `urlpatterns` list routes URLs to views. For more information please see:
+ https://docs.djangoproject.com/en/5.0/topics/http/urls/
+Examples:
+Function views
+ 1. Add an import: from my_app import views
+ 2. Add a URL to urlpatterns: path('', views.home, name='home')
+Class-based views
+ 1. Add an import: from other_app.views import Home
+ 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
+Including another URLconf
+ 1. Import the include() function: from django.urls import include, path
+ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
+"""
+from django.contrib import admin
+# include necessary libraries
+from django.urls import path, include
+from .views import home_page
+
+urlpatterns = [
+ path('admin/', admin.site.urls),
+ path('nfo/api/v1/', home_page),
+ #path('apis/', include("apis.urls")),
+ #path('nfohelm/api/v1/', include("helmprocessor.urls")),
+ #path('nfo/api/v1/', include("helm.urls")),
+
+]
--- /dev/null
+from django.http import HttpResponse, JsonResponse
+import asyncio
+from pyhelm3 import Client
+from django.views.decorators.csrf import csrf_exempt
+from rest_framework.decorators import api_view
+import json
+from rest_framework import status
+from rest_framework.response import Response
+from configparser import ConfigParser
+
+@csrf_exempt
+@api_view(['GET', 'POST', 'DELETE'])
+def home_page(request):
+ books = ['selfhelp','fantacy','novels']
+ #return HttpResponse("<h1>This is home page !!</h1>")
+
+ if request.method == "GET":
+ result = executeGet()
+ if request.method == "DELETE":
+ result = "Uninstalled !!"
+ executeDelete(request)
+ elif request.method == "POST":
+ executPost(request)
+ result = "Installed !!"
+
+ return JsonResponse(result, safe=False)
+
+def executeDelete(request):
+ print ("Delete request !!")
+ data = request.data
+ payload = json.loads(json.dumps(data))
+ name = payload['name']
+ namespace = payload['namespace']
+ print ("chart name: "+ name + " chart namespace: "+ namespace )
+ return asyncio.run(uninstall_helm(name, namespace))
+
+async def uninstall_helm(name, namespace):
+ client = getHelmClient()
+
+ revision = await client.get_current_revision(name, namespace = namespace)
+ await revision.release.uninstall(wait = True)
+ # Or directly by name
+ await client.uninstall_release(name, namespace = "default", wait = True)
+ return Response("Uninstalled", status=status.HTTP_201_CREATED)
+
+def executeGet():
+ print ("Get request !!")
+ return asyncio.run(list_releases())
+
+async def list_releases():
+ client = getHelmClient()
+
+ # List the deployed releases
+ releases = await client.list_releases(all = True, all_namespaces = True)
+ charts = []
+ chart = {}
+ for release in releases:
+ revision = await release.current_revision()
+ print(release.name, release.namespace, revision.revision, str(revision.status))
+ chart['name'] = release.name
+ chart['revision'] = revision.revision
+ chart['namespace'] = release.namespace
+ chart['status'] = str(revision.status)
+ charts.append(chart)
+
+ result = json.dumps(charts)
+ return result
+
+def executPost(request):
+ print ("POST request !!")
+ data = request.data
+ payload = json.loads(json.dumps(data))
+ charts = payload['charts']
+ for chart in charts:
+ name = chart['name']
+ version = chart['version']
+ repo = chart['repo']
+ print ("chart name: "+ name + " chart version: "+ version + " chart repo: " + repo)
+ asyncio.run(porcessCharts(name, version, repo))
+
+async def porcessCharts(name, version, repo):
+ print ("Post request !!")
+
+ client = getHelmClient()
+
+ # Fetch a chart
+ chart = await client.get_chart(
+ name,
+ repo = repo,
+ version = version
+ )
+ print(chart.metadata.name, chart.metadata.version)
+ #print(await chart.readme())
+
+ # Install or upgrade a release
+ revision = await client.install_or_upgrade_release(
+ name,
+ chart,
+ { "installCRDs": True },
+ atomic = True,
+ wait = True
+ )
+ print(
+ revision.release.name,
+ revision.release.namespace,
+ revision.revision,
+ str(revision.status)
+ )
+
+ content = { revision.release.name, revision.release.namespace, revision.revision, str(revision.status)}
+ return Response(content, status=status.HTTP_201_CREATED)
+
+def getHelmClient():
+
+ config = ConfigParser()
+ with open("config.ini", "r") as file_object:
+ config.read_file(file_object)
+ kube_config = config.get("localpath", "kubeconfig_file_path")
+ helm_executable = config.get("localpath", "helm_executable_path")
+
+ # This will use the Kubernetes configuration from the environment
+ client = Client()
+ # Specify the kubeconfig file to use
+ client = Client(kubeconfig = kube_config)
+ # Specify a custom Helm executable (by default, we expect 'helm' to be on the PATH)
+ client = Client(executable = helm_executable)
+
+ return client
+
+
+
--- /dev/null
+"""
+WSGI config for nfo_microservice project.
+
+It exposes the WSGI callable as a module-level variable named ``application``.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
+"""
+
+import os
+
+from django.core.wsgi import get_wsgi_application
+
+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nfo_microservice.settings')
+
+application = get_wsgi_application()
--- /dev/null
+#https://github.com/stackhpc/pyhelm3
+
+import requests
+from pyhelm3 import Client
+import asyncio
+
+async def test_client():
+ #endpoint = "https://httpbin.org/get"
+ endpoint = "http://127.0.0.1:8000/api/"
+ getresponse = requests.get(endpoint, json={"query":"Hello, World!"})
+
+ #print(getresponse.text)
+ print(getresponse.status_code)
+ #print(getresponse.json()['message'])
+ print(getresponse.json())
+
+async def get_current_version():
+ client = Client()
+ client = Client(kubeconfig = "/home/fnclab/.kube/config")
+ client = Client(executable = "/usr/local/bin/helm")
+ # Get the current revision for an existing release
+ revision = await client.get_current_revision("hello-world-1711020846", namespace = "default")
+ chart_metadata = await revision.chart_metadata()
+ print(
+ revision.release.name,
+ revision.release.namespace,
+ revision.revision,
+ str(revision.status),
+ chart_metadata.name,
+ chart_metadata.version
+ )
+
+async def list_releases():
+ client = Client()
+ client = Client(kubeconfig = "/home/fnclab/.kube/config")
+ client = Client(executable = "/usr/local/bin/helm")
+
+ # List the deployed releases
+ releases = await client.list_releases(all = True, all_namespaces = True)
+ for release in releases:
+ print("executing for loop ->")
+ revision = await release.current_revision()
+ print(release.name, release.namespace, revision.revision, str(revision.status))
+
+async def uninstall_helm():
+ client = Client()
+ client = Client(kubeconfig = "/home/fnclab/.kube/config")
+ client = Client(executable = "/usr/local/bin/helm")
+ revision = await client.get_current_revision("cert-manager", namespace = "default")
+ await revision.release.uninstall(wait = True)
+ # Or directly by name
+ await client.uninstall_release("cert-manager", namespace = "default", wait = True)
+
+async def install_helm():
+ print("executing test_helmClient() ->")
+
+ # This will use the Kubernetes configuration from the environment
+ client = Client()
+ # Specify the kubeconfig file to use
+ client = Client(kubeconfig = "/home/fnclab/.kube/config")
+ # Specify a custom Helm executable (by default, we expect 'helm' to be on the PATH)
+ client = Client(executable = "/usr/local/bin/helm")
+
+ # Fetch a chart
+ chart = await client.get_chart(
+ "cert-manager",
+ repo = "https://charts.jetstack.io",
+ version = "v1.8.x"
+ )
+ print(chart.metadata.name, chart.metadata.version)
+ #print(await chart.readme())
+
+ # Install or upgrade a release
+ revision = await client.install_or_upgrade_release(
+ "cert-manager",
+ chart,
+ { "installCRDs": True },
+ atomic = True,
+ wait = True
+ )
+ print(
+ revision.release.name,
+ revision.release.namespace,
+ revision.revision,
+ str(revision.status)
+ )
+
+if __name__ == "__main__":
+ #asyncio.run(get_current_version())
+ #asyncio.run(list_releases())
+ #asyncio.run(install_helm())
+ asyncio.run(uninstall_helm())