🔍 Code Extractor

function main_v55

Maturity: 38

Performs a comprehensive status check of an email forwarder service, verifying process status, port availability, SMTP communication, and configuration settings.

File:
/tf/active/vicechatdev/email-forwarder/service_status.py
Lines:
44 - 101
Complexity:
moderate

Purpose

This function serves as a diagnostic and verification tool for an email forwarder service that accepts SMTP connections and forwards emails via Microsoft 365 Graph API. It systematically checks four critical aspects: (1) whether the service process is running, (2) if port 2525 is listening for connections, (3) SMTP protocol communication functionality, and (4) configuration validity. The function provides detailed console output with visual indicators and usage instructions, making it suitable for deployment verification, troubleshooting, and health monitoring.

Source Code

def main():
    print("=" * 60)
    print("EMAIL FORWARDER SERVICE - FINAL STATUS CHECK")
    print("=" * 60)
    
    # Check 1: Process running
    print("\n1. Checking if service process is running...")
    is_running, process_info = check_service_process()
    if is_running:
        print(f"   ✓ Service is running: {process_info}")
    else:
        print("   ✗ Service process not found")
        return False
    
    # Check 2: Port listening
    print("\n2. Checking if SMTP port 2525 is listening...")
    if check_port_listening():
        print("   ✓ Port 2525 is accepting connections")
    else:
        print("   ✗ Port 2525 is not accessible")
        return False
    
    # Check 3: SMTP communication
    print("\n3. Testing SMTP protocol communication...")
    smtp_result = test_smtp_basic()
    if smtp_result is True:
        print("   ✓ SMTP protocol communication successful")
    else:
        print(f"   ✗ SMTP communication failed: {smtp_result}")
        return False
    
    # Check 4: Configuration
    print("\n4. Checking configuration...")
    try:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
        import config.settings as settings
        print(f"   ✓ SMTP Listen: {settings.SMTP_LISTEN_HOST}:{settings.SMTP_LISTEN_PORT}")
        print(f"   ✓ MS365 Sender: {settings.MS365_SENDER_EMAIL}")
        print(f"   ✓ Validation: {settings.VALIDATE_RECIPIENTS}")
    except Exception as e:
        print(f"   ✗ Configuration error: {e}")
        return False
    
    print("\n" + "=" * 60)
    print("SERVICE STATUS: ✓ FULLY OPERATIONAL")
    print("=" * 60)
    print("\nThe email forwarder service is successfully running and ready to:")
    print("• Accept SMTP connections on 127.0.0.1:2525")
    print("• Parse incoming email messages")
    print("• Forward emails via Microsoft 365 Graph API")
    print("• Handle rate limiting and retries")
    print("• Log all activities")
    print("\nTo send test emails, use:")
    print("  python send_test_email.py --to recipient@domain.com --from sender@domain.com")
    print("\nTo stop the service:")
    print("  pkill -f 'python src/main.py'")
    
    return True

Return Value

Returns a boolean value: True if all four checks (service process, port listening, SMTP communication, and configuration) pass successfully, indicating the service is fully operational; False if any check fails, indicating the service has issues that need attention.

Dependencies

  • subprocess
  • sys
  • os
  • socket
  • time
  • smtplib

Required Imports

import subprocess
import sys
import os
import socket
import time
import smtplib

Conditional/Optional Imports

These imports are only needed under specific conditions:

import config.settings as settings

Condition: imported dynamically during configuration check (Check 4), requires src directory in path

Required (conditional)

Usage Example

# Assuming this is in a file called check_status.py with required helper functions
# and the email forwarder service is running

if __name__ == '__main__':
    # Run the comprehensive status check
    success = main()
    
    if success:
        print("\nAll systems operational!")
        exit(0)
    else:
        print("\nService has issues that need attention.")
        exit(1)

# Expected output when successful:
# ============================================================
# EMAIL FORWARDER SERVICE - FINAL STATUS CHECK
# ============================================================
# 
# 1. Checking if service process is running...
#    ✓ Service is running: PID 12345
# 
# 2. Checking if SMTP port 2525 is listening...
#    ✓ Port 2525 is accepting connections
# 
# 3. Testing SMTP protocol communication...
#    ✓ SMTP protocol communication successful
# 
# 4. Checking configuration...
#    ✓ SMTP Listen: 127.0.0.1:2525
#    ✓ MS365 Sender: sender@domain.com
#    ✓ Validation: True
# 
# ============================================================
# SERVICE STATUS: ✓ FULLY OPERATIONAL
# ============================================================

Best Practices

  • This function requires three helper functions to be defined in the same module: check_service_process(), check_port_listening(), and test_smtp_basic()
  • The function performs checks sequentially and returns False immediately upon first failure, implementing fail-fast behavior
  • Ensure the email forwarder service (src/main.py) is running before calling this function
  • The function modifies sys.path to import configuration, which may affect module resolution in the calling context
  • Use this function as part of deployment verification or continuous health monitoring
  • The function provides user-friendly console output with visual indicators (✓/✗) for easy interpretation
  • Exit codes should be used when calling from command line: exit(0) for success, exit(1) for failure
  • Consider wrapping this in a try-except block if using in automated monitoring to handle unexpected exceptions
  • The function assumes port 2525 is the SMTP listening port; modify if using a different port

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function send_test_email_v1 72.1% similar

    Sends a test email to a local SMTP server (127.0.0.1:2525) to verify email forwarding functionality and service connectivity.

    From: /tf/active/vicechatdev/email-forwarder/test_e2e.py
  • function test_smtp_connection 71.3% similar

    Tests the SMTP connection to a local email forwarder service running on port 2525 by establishing a connection and performing an EHLO handshake.

    From: /tf/active/vicechatdev/email-forwarder/test_e2e.py
  • function main_v40 69.3% similar

    Orchestrates and executes a test suite for an email forwarder service, running multiple test functions sequentially and reporting results.

    From: /tf/active/vicechatdev/email-forwarder/test_service.py
  • function test_configuration_v3 67.3% similar

    A test function that validates the presence and loading of required Microsoft 365 and SMTP configuration settings from a settings module.

    From: /tf/active/vicechatdev/email-forwarder/test_imports.py
  • function send_test_email 65.6% similar

    Sends a test email via SMTP to verify email forwarding service functionality, creating a MIME multipart message with customizable sender, recipient, subject, and body content.

    From: /tf/active/vicechatdev/email-forwarder/send_test_email.py
← Back to Browse