pytogo / portforward

Kubernetes Port-Forward Go-Edition For Python

Home Page:https://portforward.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

partially initiatlized most likely due to a circular import error

MChrys opened this issue · comments

  • portforward version: "0.5.0"
  • Python version: 3.10.8
  • Operating System: macos

Description

I simply try to make a script that run portforwards with parameter set in yaml file

What I Did

in the vscode python debugger I got this error

Exception has occurred: AttributeError
partially initialized module 'portforward' has no attribute 'forward' (most likely due to a circular import)
  File "/Users//kube_cmd/portforward.py", line 47, in port_forward
    pf= portforward.forward(
  File "/Users/kube_cmd/portforward.py", line 82, in <module>
    run = port_forward(service_name,namespace, local_port, pod_port, types)
  File "/Users/kube_cmd/portforward.py", line 14, in <module>
    import portforward
AttributeError: partially initialized module 'portforward' has no attribute 'forward' (most likely due to a circular import)

my script

import sys
sys.path.insert(0,"/Users/")
path = sys.path
# from kubernetes import config, client, utils

# from kubernetes.client import Configuration
# from kubernetes.client.api import core_v1_api
# from kubernetes.client.rest import ApiException
# from kubernetes.stream import stream, ws_client
import threading
from functions import ConfigYML
import time
from pathlib import Path
import portforward
import requests
# Chargez la configuration de kubeconfig (par défaut à '~/.kube/config')
# config.load_kube_config(context="minikube")



print(Path.cwd())
print("______________________________________________________________________")
def port_forward(service_name: str, namespace: str, local_port: int, pod_port: int, types:bool):
    # Chargez la configuration de kubeconfig (par défaut à '~/.kube/config')

    if types == 'pod':
        config.load_kube_config(context="minikube")
        c = Configuration().get_default_copy()

        core_v1 = core_v1_api.CoreV1Api()
        service = core_v1.read_namespaced_service(name=service_name, namespace=namespace)
        label_selector = ','.join([f'{k}={v}' for k, v in service.spec.selector.items()])

        pods = core_v1.list_namespaced_pod(namespace, label_selector=label_selector)
        pod_name = pods.items[0].metadata.name

        port = f'{local_port}:{pod_port}'
        port = [local_port,pod_port]
        port = f'{local_port},{pod_port}' 
        service_name=pod_name
        # Port forward
    # run:ws_client.PortForward = portforward(core_v1.connect_get_namespaced_pod_portforward,
    #             name=pod_name,
    #             namespace=namespace,
    #             ports=port,
    #             )
    pf= portforward.forward(
        namespace=namespace,
        pod_or_service=service_name,
        from_port=local_port,
        to_port=pod_port
        )
    url = f"http://localhost:{local_port}"

    # Boucle infinie
    print(f"{pod_name} => {url}  -> {pod_port}")
    print("")
    with pf as forward:
        while True:
            response = requests.get(url)
            print(f"{service_name} at {url} -> {response}")
            # Attendez 1 seconde à chaque itération
            time.sleep(5)


pf_params = {}
# Example usage
for portname in (conf:=ConfigYML(full_path=sys.path[0])).read('kubernetes','portforward'):
    with conf.walk('service',portname,"kubernetes") as pf :
        # Nom du service pour lequel vous voulez faire le port-forward
        service_name = pf.read( 'service_name')

        # Namespace où le service est déployé
        namespace = pf.read( 'namespace')

        # Port sur lequel vous voulez faire le port-forward
        local_port = pf.read('local_port')    
        pod_port = pf.read('pod_port')

        types = pf.read('type')
    # pf_params[service_name] = (service_name,namespace, local_port, pod_port) 
    run = port_forward(service_name,namespace, local_port, pod_port, types)
    print("Port forward is running. Press Ctrl+C to stop.")
threads = []
# for k,v in pf_params.items():
#     thread = threading.Thread(target=port_forward, args=v
#     )
#     thread.start()
#     threads.append(thread)

# Le port-forward est maintenant en cours. Il se terminera lorsque le script Python se terminera.

ok i didn't put the "if main" stuff but know i simple got this error

Exception has occurred: AttributeError
module 'portforward' has no attribute 'forward'

now my script :

import sys
sys.path.insert(0,"/Users/chrysostomebeltran/DemiurgeSDK/")
path = sys.path
# from kubernetes import config, client, utils

# from kubernetes.client import Configuration
# from kubernetes.client.api import core_v1_api
# from kubernetes.client.rest import ApiException
# from kubernetes.stream import stream, ws_client
import threading
from functions import ConfigYML
import time
from pathlib import Path
import portforward
import requests
# Chargez la configuration de kubeconfig (par défaut à '~/.kube/config')
# config.load_kube_config(context="minikube")



print(Path.cwd())
print("______________________________________________________________________")
def port_forward(service_name: str, namespace: str, local_port: int, pod_port: int, types:bool):
    # Chargez la configuration de kubeconfig (par défaut à '~/.kube/config')

    if types == 'pod':
        config.load_kube_config(context="minikube")
        c = Configuration().get_default_copy()

        core_v1 = core_v1_api.CoreV1Api()
        service = core_v1.read_namespaced_service(name=service_name, namespace=namespace)
        label_selector = ','.join([f'{k}={v}' for k, v in service.spec.selector.items()])

        pods = core_v1.list_namespaced_pod(namespace, label_selector=label_selector)
        pod_name = pods.items[0].metadata.name

        port = f'{local_port}:{pod_port}'
        port = [local_port,pod_port]
        port = f'{local_port},{pod_port}' 
        service_name=pod_name
        # Port forward
    # run:ws_client.PortForward = portforward(core_v1.connect_get_namespaced_pod_portforward,
    #             name=pod_name,
    #             namespace=namespace,
    #             ports=port,
    #             )
    pf= portforward.forward(
        namespace=namespace,
        pod_or_service=service_name,
        from_port=local_port,
        to_port=pod_port
        )
    url = f"http://localhost:{local_port}"

    # Boucle infinie
    print(f"{pod_name} => {url}  -> {pod_port}")
    print("")
    with pf as forward:
        while True:
            response = requests.get(url)
            print(f"{service_name} at {url} -> {response}")
            # Attendez 1 seconde à chaque itération
            time.sleep(5)

def main():
    pf_params = {}
    # Example usage
    for portname in (conf:=ConfigYML(full_path=sys.path[0])).read('kubernetes','portforward'):
        with conf.walk('service',portname,"kubernetes") as pf :
            # Nom du service pour lequel vous voulez faire le port-forward
            service_name = pf.read( 'service_name')

            # Namespace où le service est déployé
            namespace = pf.read( 'namespace')

            # Port sur lequel vous voulez faire le port-forward
            local_port = pf.read('local_port')    
            pod_port = pf.read('pod_port')

            types = pf.read('type')
        # pf_params[service_name] = (service_name,namespace, local_port, pod_port) 
        run = port_forward(service_name,namespace, local_port, pod_port, types)
        print("Port forward is running. Press Ctrl+C to stop.")
    threads = []
    # for k,v in pf_params.items():
    #     thread = threading.Thread(target=port_forward, args=v
    #     )
    #     thread.start()
    #     threads.append(thread)

    # Le port-forward est maintenant en cours. Il se terminera lorsque le script Python se terminera.
if __name__ == "__main__":
    main()