Skip to content

Commit ed4f582

Browse files
add deboucne and more trigger debug
1 parent 28e8eaf commit ed4f582

1 file changed

Lines changed: 75 additions & 16 deletions

File tree

service_monitor.py

Lines changed: 75 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import os
44
import logging
5+
import time
6+
from typing import Dict
57
from kubernetes import client, config, watch
68
from github import Github
79

@@ -19,39 +21,96 @@
1921
TENANT = os.environ.get('TENANT')
2022
PROJECT = os.environ.get('PROJECT')
2123

22-
def trigger_github_workflow(gh_token, event_type):
24+
# Store the last trigger time for each service
25+
_last_trigger_times: Dict[str, float] = {}
26+
DEBOUNCE_INTERVAL = 180 # 3 minutes in seconds
27+
28+
def trigger_github_workflow(gh_token: str, event_type: str, service_key: str) -> bool:
2329
"""
24-
Trigger GitHub Actions workflow with the specified parameters
30+
Trigger GitHub Actions workflow with debouncing and detailed error logging
31+
32+
Args:
33+
gh_token: GitHub authentication token
34+
event_type: Type of the Kubernetes event
35+
service_key: Unique identifier for the service (namespace/name)
36+
37+
Returns:
38+
bool: True if workflow was triggered, False otherwise
2539
"""
40+
if not GITHUB_REPO:
41+
logger.error("GITHUB_REPO environment variable not set")
42+
return False
43+
44+
if not WORKFLOW_FILE:
45+
logger.error("WORKFLOW_FILE environment variable not set")
46+
return False
47+
48+
current_time = time.time()
49+
last_trigger_time = _last_trigger_times.get(service_key, 0)
50+
51+
# Check if enough time has passed since the last trigger
52+
if current_time - last_trigger_time < DEBOUNCE_INTERVAL:
53+
logger.info(f"Skipping workflow trigger for {service_key} due to debouncing (last trigger was {int(current_time - last_trigger_time)} seconds ago)")
54+
return False
55+
2656
try:
57+
logger.info(f"Connecting to GitHub repo: {GITHUB_REPO}")
2758
g = Github(gh_token)
2859
repo = g.get_repo(GITHUB_REPO)
2960

61+
# Get all workflows and log them for debugging
62+
workflows = list(repo.get_workflows())
63+
logger.info(f"Found {len(workflows)} workflows in repository")
64+
for wf in workflows:
65+
logger.info(f"Available workflow: {wf.path} (ID: {wf.id})")
66+
3067
# Get the workflow by filename
3168
workflow = None
32-
for wf in repo.get_workflows():
69+
for wf in workflows:
3370
if wf.path.endswith(WORKFLOW_FILE):
3471
workflow = wf
72+
logger.info(f"Found matching workflow: {wf.path} (ID: {wf.id})")
3573
break
3674

3775
if workflow is None:
38-
logger.error(f"Workflow {WORKFLOW_FILE} not found")
76+
logger.error(f"Workflow {WORKFLOW_FILE} not found in repository {GITHUB_REPO}")
3977
return False
4078

41-
# Create workflow dispatch event with inputs
42-
workflow.create_dispatch(
43-
ref="main", # You might want to make this configurable
44-
inputs={
45-
"tenant": TENANT,
46-
"project": PROJECT
47-
}
48-
)
79+
# Prepare inputs
80+
inputs = {
81+
"tenant": TENANT or "",
82+
"project": PROJECT or ""
83+
}
84+
85+
logger.info(f"Triggering workflow dispatch for {workflow.path} with inputs: {inputs}")
4986

50-
logger.info(f"Successfully triggered workflow for event: {event_type}")
51-
return True
87+
# Create workflow dispatch event with inputs
88+
try:
89+
workflow.create_dispatch(
90+
ref="main", # You might want to make this configurable
91+
inputs=inputs
92+
)
93+
# Update the last trigger time only on successful dispatch
94+
_last_trigger_times[service_key] = current_time
95+
logger.info(f"Successfully triggered workflow {workflow.path} for event: {event_type} (service: {service_key})")
96+
return True
97+
98+
except Exception as dispatch_error:
99+
logger.error(f"Failed to dispatch workflow: {str(dispatch_error)}")
100+
# Try to get more details about the error
101+
if hasattr(dispatch_error, 'response'):
102+
response = getattr(dispatch_error, 'response')
103+
if response:
104+
logger.error(f"GitHub API Response: {response.status_code} - {response.text}")
105+
return False
52106

53107
except Exception as e:
54108
logger.error(f"Failed to trigger workflow: {str(e)}")
109+
# Try to get more details about the error
110+
if hasattr(e, 'response'):
111+
response = getattr(e, 'response')
112+
if response:
113+
logger.error(f"GitHub API Response: {response.status_code} - {response.text}")
55114
return False
56115

57116
def watch_services():
@@ -81,7 +140,8 @@ def watch_services():
81140
# Trigger workflow for relevant events
82141
if event_type in ['ADDED', 'MODIFIED', 'DELETED']:
83142
if GITHUB_TOKEN:
84-
trigger_github_workflow(GITHUB_TOKEN, event_type)
143+
service_key = f"{service.metadata.namespace}/{service.metadata.name}"
144+
trigger_github_workflow(GITHUB_TOKEN, event_type, service_key)
85145
else:
86146
logger.error("GITHUB_TOKEN environment variable not set")
87147

@@ -103,7 +163,6 @@ def main():
103163
except Exception as e:
104164
logger.error(f"Error in main loop: {str(e)}")
105165
# Wait a bit before retrying
106-
import time
107166
time.sleep(5)
108167

109168
if __name__ == "__main__":

0 commit comments

Comments
 (0)