github.com/mdaxf/iac@v0.0.0-20240519030858-58a061660378/controllers/health/healthcheck.go (about)

     1  package health
     2  
     3  import (
     4  	//"log"
     5  	"fmt"
     6  	"net/http"
     7  	"time"
     8  
     9  	"github.com/gin-gonic/gin"
    10  	"github.com/mdaxf/iac/com"
    11  	"github.com/mdaxf/iac/controllers/common"
    12  	"github.com/mdaxf/iac/health"
    13  	"github.com/mdaxf/iac/logger"
    14  )
    15  
    16  type HealthController struct {
    17  }
    18  
    19  // CheckHealth is a function that handles the health check request.
    20  // It retrieves user information from the request context, logs the health check activity,
    21  // and calls the CheckSystemHealth function to get the system health data.
    22  // If there is an error retrieving user information or checking the system health,
    23  // it returns an error response with the corresponding status code.
    24  // Otherwise, it returns a success response with the system health data.
    25  
    26  func (f *HealthController) CheckHealth(c *gin.Context) {
    27  	iLog := logger.Log{ModuleName: logger.API, User: "System", ControllerName: "health"}
    28  	startTime := time.Now()
    29  	defer func() {
    30  		elapsed := time.Since(startTime)
    31  		iLog.PerformanceWithDuration("controllers.health.CheckHealth", elapsed)
    32  	}()
    33  	/*
    34  		defer func() {
    35  			if err := recover(); err != nil {
    36  				iLog.Error(fmt.Sprintf("Health Check error: %s", err))
    37  				c.JSON(http.StatusBadRequest, gin.H{"error": err})
    38  			}
    39  		}()
    40  	*/
    41  	_, user, clientid, err := common.GetRequestUser(c)
    42  	if err != nil {
    43  		iLog.Error(fmt.Sprintf("Get user information Error: %v", err))
    44  		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    45  		return
    46  	}
    47  	iLog.ClientID = clientid
    48  	iLog.User = user
    49  
    50  	iLog.Debug("Health Check")
    51  	data, err := health.CheckSystemHealth(c)
    52  	iLog.Debug(fmt.Sprintf("Health Check Result: %v", data))
    53  
    54  	iLog.Debug(fmt.Sprintf("all node health data: %v", com.NodeHeartBeats))
    55  
    56  	nodehealth := make(map[string]interface{})
    57  	nodehealth["Result"] = data
    58  	nodehealth["Node"] = com.IACNode
    59  	nodehealth["ServiceStatus"] = make(map[string]interface{})
    60  	nodehealth["timestamp"] = time.Now().UTC()
    61  	//nodehealth["ServiceStatus"] = (com.NodeHeartBeats[com.IACNode["AppID"].(string)].(map[string]interface{}))["ServiceStatus"]
    62  	com.NodeHeartBeats[com.IACNode["AppID"].(string)] = nodehealth
    63  
    64  	if err != nil {
    65  		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
    66  		return
    67  	}
    68  
    69  	c.JSON(http.StatusOK, gin.H{"data": com.NodeHeartBeats})
    70  
    71  }