<commit_before>{
   "templateGroup": {
      "uuid": "wso2-apim-analytics",
      "name": "WSO2 APIM Analytics",
      "description": "Real Time Analytics of APIM",
      "ruleTemplates": [
         {
            "uuid": "apim_frequent_tier_limit_hitting_alert",
            "name": "APIM Frequent Tier Limit Hitting Alert",
            "description": "Alerts when a user or an application goes beyond the subscribed quota frequently",
            "type": "template",
            "instanceCount": "one",
            "script": "",
            "templates": [
               {
                  "type": "siddhiApp",
                  "content": "@App:name(\"apim_frequent_tier_limit_hitting_alert_0\")\n@App:description(\"Alerts when a user or application goes beyond the subscribed quota frequently\")\n\n@source(type = 'wso2event', wso2.stream.id = 'org.wso2.apimgt.statistics.throttle:3.0.0', \n\t@map(type = 'wso2event'))\ndefine stream ThrottledOutStream(\n    meta_clientType string,\n    username string,\n    userTenantDomain string,\n    apiName string,\n    apiVersion string,\n    apiContext string,\n    apiCreator string,\n    apiCreatorTenantDomain string,\n    applicationId string,\n    applicationName string,\n    subscriber string,\t\n    throttledOutReason string,\n    gatewayType string,\n    throttledOutTimestamp long,\n hostname string \n);\n\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAllAlert (type string, tenantDomain string, message string, severity int, alertTimestamp long);\n\n@PrimaryKey('userId', 'isSubscriber', 'isPublisher', 'isAdmin')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAlertStakeholderInfo(userId string, alertTypes\tstring, emails\tstring, isSubscriber bool, isPublisher\tbool, isAdmin\tbool);\n\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimTierLimitHittingAlert (subscriber string, apiCreator string, apiName string, applicationId string, applicationName string, apiCreatorTenantDomain string, userTenantDomain string, message string, severity int, alertTimestamp long);\n\n@sink(type=\"inMemory\", topic=\"APIM_EMAIL_NOTIFICATION\", @map(type='passThrough'))\ndefine stream EmailAlertStream (type string, message string, alertTimestamp\tstring, emails\tstring);\n\ndefine stream TemporaryUserStream(username string, apiCreator string,apiName string, apiVersion string, applicationId string,applicationName string, apiCreatorTenantDomain string , userTenantDomain string, subscriber string, numHits long);\n\n--checks whether total throttled out count with the throttled out reson SUBSCRIPTION_LIMIT_EXCEEDED is higer than the specified value\n@info(name = 'TemporarySubscriberStream generating Query')\nfrom ThrottledOutStream[throttledOutReason == 'SUBSCRIPTION_LIMIT_EXCEEDED']#window.time(${countingTime})\nselect apiCreator, apiName, apiVersion, applicationId, applicationName,apiCreatorTenantDomain,userTenantDomain, subscriber, count() as numHits\ngroup by apiCreator,apiName,apiVersion, applicationId\nhaving numHits > ${numOfTierCrossing}\ninsert into TemporarySubscriberStream;\n\n--checks whether total throttled out count with the throttled out reson APPLICATION_LIMIT_EXCEEDED is higer than the specified value\n@info(name = 'TemporaryUserStream generating Query')\nfrom ThrottledOutStream[throttledOutReason == 'APPLICATION_LIMIT_EXCEEDED']#window.time(${countingTime})\nselect username, apiCreator, apiName, apiVersion, applicationId, applicationName, \napiCreatorTenantDomain,userTenantDomain, subscriber, count() as numHits\ngroup by username, apiName,apiVersion, applicationId\nhaving numHits > ${numOfTierCrossing}\ninsert into TemporaryUserStream;\n\n--this query ensures that the same type of alert is not generated for same apiCreator again for a time defined in #window.time(),\n@info(name = 'Query contains Suppression logic')\nfrom TemporarySubscriberStream#window.length(1) as a left outer join TemporarySubscriberStream#window.time(${alertSupression}) as b\non (a.apiCreator== b.apiCreator and a.apiVersion== b.apiVersion and a.applicationId==b.applicationId)\nselect ifThenElse(a.apiCreatorTenantDomain == 'carbon.super', str:concat(a.apiCreator, \"@carbon.super\"), a.apiCreator) as apiCreator, a.apiName, a.apiVersion, a.applicationId, a.applicationName, a.apiCreatorTenantDomain,a.userTenantDomain,\nifThenElse(a.userTenantDomain == 'carbon.super', str:concat(a.subscriber, \"@carbon.super\"), a.subscriber) as subscriber, a.numHits\nhaving b.apiCreator is null\ninsert into SuppressedTemporarySubscriberStream ;\n\n--this query ensures that the same type of alert is not generated for same user again for a time defined in #window.time()\n@info(name = 'query4')\nfrom TemporaryUserStream#window.length(1) as a left outer join TemporaryUserStream#window.time(${alertSupression}) as b\non (a.username== b.username and a.apiVersion== b.apiVersion and a.applicationId==b.applicationId)\nselect a.username, ifThenElse(a.apiCreatorTenantDomain == 'carbon.super', str:concat(a.apiCreator, \"@carbon.super\"), a.apiCreator) as apiCreator, a.apiName, a.apiVersion, a.applicationId, a.applicationName, a.apiCreatorTenantDomain, a.userTenantDomain,\nifThenElse(a.userTenantDomain == 'carbon.super', str:concat(a.subscriber, \"@carbon.super\"), a.subscriber) as subscriber, a.numHits\nhaving b.username is null\ninsert into SuppressedTemporaryUserStream;\n\n--send to the alert stream specific to this scenario\n@info(name = 'Query generates TierLimitHittingAlertStream')\nfrom SuppressedTemporarySubscriberStream\nselect subscriber, apiCreator, apiName, applicationId, applicationName, apiCreatorTenantDomain,userTenantDomain, str:concat(applicationName, \" Application frequently goes beyond the allocated quota when accessing \",apiName,' ',apiVersion) as message, ${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into TierLimitHittingAlertStream;\n\n@info(name = 'Query generates TierLimitHittingAlertStream from supressedUserStream')\nfrom SuppressedTemporaryUserStream\nselect subscriber, apiCreator, apiName, applicationId, applicationName, apiCreatorTenantDomain, userTenantDomain, str:concat(\"User \", username, \" frequently crosses the limit set.\") as message, ${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into TierLimitHittingAlertStream;\n\n@info(name='Query inserts data to ApimAllAlert Table') \nfrom TierLimitHittingAlertStream\nselect \"FrequentTierLimitHitting\" as type, userTenantDomain as tenantDomain,message,severity,alertTimestamp\ninsert into ApimAllAlert;\n\n@info(name='Query inserts data to ApimTierLimitHittingAlert table')\nfrom TierLimitHittingAlertStream\nselect *\ninsert into ApimTierLimitHittingAlert;\n\n@info(name='Email generation query') \nfrom TierLimitHittingAlertStream#window.length(1) as TL join ApimAlertStakeholderInfo as ASI\non ((TL.subscriber == ASI.userId and true == ASI.isSubscriber ) or true == ASI.isAdmin )\nselect 'FrequentTierLimitHitting' as type ,\nifThenElse(str:contains(TL.message, 'Application frequently goes beyond the allocated quota'),str:concat(\"The application \", TL.applicationName, \" owned by \", TL.subscriber, \" frequently goes beyond the allocated quota when accessing the \", TL.apiName,\" API.\"),\nstr:concat(TL.message , \" Using the \", TL.applicationName, \" application owned by \",TL.subscriber, \".\")) as message, time:dateFormat(TL.alertTimestamp,'yyyy-MM-dd HH:mm:ss') as alertTimestamp,ASI.emails\nhaving  str:contains(ASI.alertTypes, 'FrequentTierLimitHitting')\ninsert into EmailAlertStream;\n"
               }
            ],
            "properties": {
               "numOfTierCrossing": {
                  "fieldName": "No of Tier Crossing",
                  "description": "Max Number of tier crossings for the given time window",
                  "defaultValue": "10"
               },
               "severityLevel": {
                  "fieldName": "Severity Level",
                  "description": " Severity level of the alert:(1:severe,2:moderate,3:mild)",
                  "defaultValue": "3",
                  "options": [
                     "1",
                     "2",
                     "3"
                  ]
               },
               "countingTime": {
                  "fieldName": "Counting Time Interval",
                  "description": "Time period (day/hours/min/sec) of which the request count would be taken. ",
                  "defaultValue": "1 hours"
               },
               "alertSupression": {
                  "fieldName": "Alert Supression Period",
                  "description": "Time period to wait before resending the same alert ",
                  "defaultValue": "10 minute"
               }
            }
         },
         {
            "uuid": "apim_health_availability_alert",
            "name": "APIM Health Availability Alert",
            "description": "Monitors the Health of an API",
            "type": "template",
            "instanceCount": "one",
            "script": "",
            "templates": [
               {
                  "type": "siddhiApp",
                  "content": "@App:name(\"apim_health_availability_alert_0\")\n@App:description(\"Determines the availablity and health of an api\")\n\n@source(type ='inMemory', topic = 'APIM_REQUEST_ALERT_INFO')\ndefine stream RequestAlertInfoStream (apiContext string,apiName string, apiVersion string, apiResourceTemplate string, apiMethod string, apiCreator string, apiCreatorTenantDomain string, requestTimestamp long, responseTime long, backendTime long, thresholdBackendTime long, thresholdResponseTime long,responseCode int );\n\n--Table Definitions\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAllAlert (type string, tenantDomain string, message string, severity int, alertTimestamp long);\n\n@primaryKey('tenantApiVersion')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAlertTableResponseInfo (tenantApiVersion string, count int);\n\n@primaryKey('apiName','apiVersion','tenantDomain')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimApiAvailabilityInfo (apiName string,apiVersion string, apiCreator string , tenantDomain string, status string);\n\n@PrimaryKey('userId', 'isSubscriber', 'isPublisher', 'isAdmin')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAlertStakeholderInfo(userId string, alertTypes\tstring, emails string, isSubscriber bool, isPublisher\tbool, isAdmin\tbool);\n\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimApiHealthMonitorAlert(apiName string,apiVersion string,apiCreator string, apiCreatorTenantDomain string,\n message string, severity int, alertTimestamp long);\n\n@sink(type=\"inMemory\", topic=\"APIM_EMAIL_NOTIFICATION\", @map(type='passThrough'))\ndefine stream EmailAlertStream (type string, message string, alertTimestamp\tstring, emails string);\n\ndefine stream ApimAllAlertSummary (type string, tenantDomain string, message string, severity int, alertTimestamp long);\n\npartition with (apiContext of RequestAlertInfoStream)\nbegin\n    -- checks whether the response time is higher than the threshold response time continously for 5 times\n    from every e1=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0],e2=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0],e3=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0], e4=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0],e5=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0]\n    select e1.apiName,e1.apiVersion,e1.apiContext,e1.apiCreator,e1.apiCreatorTenantDomain,e1.thresholdResponseTime\n    insert into TempResponseTimeAlertStream;\n\n    --checks whether the response code is between 500 - 600 to identify a server error\n     from every e1=RequestAlertInfoStream[responseCode>=500 and responseCode<600],e2=RequestAlertInfoStream[responseCode>=500 and responseCode<600],e3=RequestAlertInfoStream[responseCode>=500 and responseCode<600], e4=RequestAlertInfoStream[responseCode>=500 and responseCode<600],e5=RequestAlertInfoStream[responseCode>=500 and responseCode<600]\n    select e1.apiName,e1.apiVersion,e1.apiContext,e1.apiCreator,e1.apiCreatorTenantDomain\n    insert into TempResponseCodeAlertStream;\nend;\n\n@info(name='Query generates ApiHealthMonitorAlertStreamTemp with message for high response time alert')\nfrom TempResponseTimeAlertStream\nselect apiName,apiVersion, apiCreator, apiCreatorTenantDomain, str:concat('Response time is higher than ' ,thresholdResponseTime, ' ms continuously for 5 or more responses.') as message, ${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into ApiHealthMonitorAlertStreamTemp;\n\n@info(name='Query generates ApiHealthMonitorAlertStreamTemp with message for server error alert')\nfrom TempResponseCodeAlertStream\nselect apiName, apiVersion, apiCreator, apiCreatorTenantDomain, 'Server error occurred continuously for 5 or more times.'  as message,${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into ApiHealthMonitorAlertStreamTemp;\n\n@info(name='Query generating TempallApimAlertStream')\nfrom ApiHealthMonitorAlertStreamTemp\nselect 'ApiHealthMonitor' as type, apiCreatorTenantDomain, str:concat('API:', apiName,' ',apiVersion, '-', message) as message , severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into TempallApimAlertStream;\n\n--inserts data into ApimAllAlertSummary, if the same alert was not generated for a time defined in #window.time\n@info(name='Query generates ApimAllAlertSummary')\nfrom TempallApimAlertStream#window.length(1) as TA left outer join ApimAllAlertSummary#window.time(${alertSupressTime}) as AAS\non TA.message == AAS.message\nselect TA.type,TA.apiCreatorTenantDomain as tenantDomain,TA.message,TA.severity,TA.alertTimestamp\nhaving AAS.message is null\ninsert into ApimAllAlertSummary;\n\n@info(name='Query inserts data to ApimApiHealthMonitorAler')\n from ApiHealthMonitorAlertStreamTemp#window.length(1) as AH left outer join ApimApiHealthMonitorAlert#window.time(${alertSupressTime}) as AM\non AH.apiName==AM.apiName and AH.apiVersion==AM.apiVersion and AH.message==AM.message\nselect AH.apiName,AH.apiVersion,AH.apiCreator,AH.apiCreatorTenantDomain,AH.message,AH.severity,AH.alertTimestamp\nhaving AM.apiName is null and AM.apiVersion is null and AM.message is null\ninsert into ApimApiHealthMonitorAlert;\n\n@info(name='Query inserts data to ApimAllAlert')\nfrom ApimAllAlertSummary\nselect type,tenantDomain,message as message,severity,alertTimestamp\ninsert into ApimAllAlert;\n\n@info(name='Query inserts data to ApimApiAvailability')\nfrom ApiHealthMonitorAlertStreamTemp\nselect apiName,apiVersion,apiCreator,apiCreatorTenantDomain as tenantDomain,message as status\nupdate or insert into ApimApiAvailabilityInfo\nset ApimApiAvailabilityInfo.status=status\non ApimApiAvailabilityInfo.apiName==apiName and ApimApiAvailabilityInfo.apiVersion==apiVersion and ApimApiAvailabilityInfo.tenantDomain==tenantDomain;\n\n@info(name='Query inserting data to ApimApiAvailability when there is no alert for a defined time')\nfrom RequestAlertInfoStream#window.length(1) as R left outer join ApiHealthMonitorAlertStreamTemp#window.time(${availablityChange}) as AHM\non R.apiName==AHM.apiName and R.apiVersion==AHM.apiVersion\nselect R.apiName as apiName,R.apiVersion as apiVersion,R.apiCreator as apiCreator,R.apiCreatorTenantDomain as tenantDomain,\"Available\" as status\nhaving AHM.apiName is null\nupdate or insert into ApimApiAvailabilityInfo\nset ApimApiAvailabilityInfo.status=status\non ApimApiAvailabilityInfo.apiName==apiName and ApimApiAvailabilityInfo.apiVersion==apiVersion and ApimApiAvailabilityInfo.apiCreator==apiCreator and ApimApiAvailabilityInfo.tenantDomain==tenantDomain;\n\n@info(name='Query inserts data to TempStream')\n from ApiHealthMonitorAlertStreamTemp#window.length(1) as AH left outer join ApiHealthMonitorAlertStreamTemp#window.time(${alertSupressTime}) as AM\non AH.apiName==AM.apiName and AH.apiVersion==AM.apiVersion and AH.message==AM.message\nselect AH.apiName,AH.apiVersion,AH.apiCreator,AH.apiCreatorTenantDomain,AH.message,AH.severity,AH.alertTimestamp\nhaving AM.apiName is null and AM.apiVersion is null and AM.message is null\ninsert into ApiHealthMonitorAlertEmailStream;\n\n@info(name='Query inserting data to Alert Stream')\nfrom ApiHealthMonitorAlertEmailStream#window.length(1) join ApimAlertStakeholderInfo\non ((ApiHealthMonitorAlertEmailStream.apiCreator == ApimAlertStakeholderInfo.userId and true == ApimAlertStakeholderInfo.isPublisher ) or true == ApimAlertStakeholderInfo.isAdmin )\nselect 'ApiHealthMonitor' as type , str:concat('API:', apiName,' ',apiVersion, '-', message) as message, time:dateFormat(ApiHealthMonitorAlertEmailStream.alertTimestamp,'yyyy-MM-dd HH:mm:ss') as alertTimestamp, ApimAlertStakeholderInfo.emails\nhaving str:contains(ApimAlertStakeholderInfo.alertTypes, 'ApiHealthMonitor')\ninsert into EmailAlertStream;\n"
               }
            ],
            "properties": {
               "severityLevel": {
                  "fieldName": "Severity Level",
                  "description": "Severity level of the alert:(1:severe,2:moderate,3:mild)",
                  "defaultValue": "2",
                  "options": [<commit_msg>Fix apim health alert template<commit_after>{
   "templateGroup": {
      "uuid": "wso2-apim-analytics",
      "name": "WSO2 APIM Analytics",
      "description": "Real Time Analytics of APIM",
      "ruleTemplates": [
         {
            "uuid": "apim_frequent_tier_limit_hitting_alert",
            "name": "APIM Frequent Tier Limit Hitting Alert",
            "description": "Alerts when a user or an application goes beyond the subscribed quota frequently",
            "type": "template",
            "instanceCount": "one",
            "script": "",
            "templates": [
               {
                  "type": "siddhiApp",
                  "content": "@App:name(\"apim_frequent_tier_limit_hitting_alert_0\")\n@App:description(\"Alerts when a user or application goes beyond the subscribed quota frequently\")\n\n@source(type = 'wso2event', wso2.stream.id = 'org.wso2.apimgt.statistics.throttle:3.0.0', \n\t@map(type = 'wso2event'))\ndefine stream ThrottledOutStream(\n    meta_clientType string,\n    username string,\n    userTenantDomain string,\n    apiName string,\n    apiVersion string,\n    apiContext string,\n    apiCreator string,\n    apiCreatorTenantDomain string,\n    applicationId string,\n    applicationName string,\n    subscriber string,\t\n    throttledOutReason string,\n    gatewayType string,\n    throttledOutTimestamp long,\n hostname string \n);\n\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAllAlert (type string, tenantDomain string, message string, severity int, alertTimestamp long);\n\n@PrimaryKey('userId', 'isSubscriber', 'isPublisher', 'isAdmin')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAlertStakeholderInfo(userId string, alertTypes\tstring, emails\tstring, isSubscriber bool, isPublisher\tbool, isAdmin\tbool);\n\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimTierLimitHittingAlert (subscriber string, apiCreator string, apiName string, applicationId string, applicationName string, apiCreatorTenantDomain string, userTenantDomain string, message string, severity int, alertTimestamp long);\n\n@sink(type=\"inMemory\", topic=\"APIM_EMAIL_NOTIFICATION\", @map(type='passThrough'))\ndefine stream EmailAlertStream (type string, message string, alertTimestamp\tstring, emails\tstring);\n\ndefine stream TemporaryUserStream(username string, apiCreator string,apiName string, apiVersion string, applicationId string,applicationName string, apiCreatorTenantDomain string , userTenantDomain string, subscriber string, numHits long);\n\n--checks whether total throttled out count with the throttled out reson SUBSCRIPTION_LIMIT_EXCEEDED is higer than the specified value\n@info(name = 'TemporarySubscriberStream generating Query')\nfrom ThrottledOutStream[throttledOutReason == 'SUBSCRIPTION_LIMIT_EXCEEDED']#window.time(${countingTime})\nselect apiCreator, apiName, apiVersion, applicationId, applicationName,apiCreatorTenantDomain,userTenantDomain, subscriber, count() as numHits\ngroup by apiCreator,apiName,apiVersion, applicationId\nhaving numHits > ${numOfTierCrossing}\ninsert into TemporarySubscriberStream;\n\n--checks whether total throttled out count with the throttled out reson APPLICATION_LIMIT_EXCEEDED is higer than the specified value\n@info(name = 'TemporaryUserStream generating Query')\nfrom ThrottledOutStream[throttledOutReason == 'APPLICATION_LIMIT_EXCEEDED']#window.time(${countingTime})\nselect username, apiCreator, apiName, apiVersion, applicationId, applicationName, \napiCreatorTenantDomain,userTenantDomain, subscriber, count() as numHits\ngroup by username, apiName,apiVersion, applicationId\nhaving numHits > ${numOfTierCrossing}\ninsert into TemporaryUserStream;\n\n--this query ensures that the same type of alert is not generated for same apiCreator again for a time defined in #window.time(),\n@info(name = 'Query contains Suppression logic')\nfrom TemporarySubscriberStream#window.length(1) as a left outer join TemporarySubscriberStream#window.time(${alertSupression}) as b\non (a.apiCreator== b.apiCreator and a.apiVersion== b.apiVersion and a.applicationId==b.applicationId)\nselect ifThenElse(a.apiCreatorTenantDomain == 'carbon.super', str:concat(a.apiCreator, \"@carbon.super\"), a.apiCreator) as apiCreator, a.apiName, a.apiVersion, a.applicationId, a.applicationName, a.apiCreatorTenantDomain,a.userTenantDomain,\nifThenElse(a.userTenantDomain == 'carbon.super', str:concat(a.subscriber, \"@carbon.super\"), a.subscriber) as subscriber, a.numHits\nhaving b.apiCreator is null\ninsert into SuppressedTemporarySubscriberStream ;\n\n--this query ensures that the same type of alert is not generated for same user again for a time defined in #window.time()\n@info(name = 'query4')\nfrom TemporaryUserStream#window.length(1) as a left outer join TemporaryUserStream#window.time(${alertSupression}) as b\non (a.username== b.username and a.apiVersion== b.apiVersion and a.applicationId==b.applicationId)\nselect a.username, ifThenElse(a.apiCreatorTenantDomain == 'carbon.super', str:concat(a.apiCreator, \"@carbon.super\"), a.apiCreator) as apiCreator, a.apiName, a.apiVersion, a.applicationId, a.applicationName, a.apiCreatorTenantDomain, a.userTenantDomain,\nifThenElse(a.userTenantDomain == 'carbon.super', str:concat(a.subscriber, \"@carbon.super\"), a.subscriber) as subscriber, a.numHits\nhaving b.username is null\ninsert into SuppressedTemporaryUserStream;\n\n--send to the alert stream specific to this scenario\n@info(name = 'Query generates TierLimitHittingAlertStream')\nfrom SuppressedTemporarySubscriberStream\nselect subscriber, apiCreator, apiName, applicationId, applicationName, apiCreatorTenantDomain,userTenantDomain, str:concat(applicationName, \" Application frequently goes beyond the allocated quota when accessing \",apiName,' ',apiVersion) as message, ${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into TierLimitHittingAlertStream;\n\n@info(name = 'Query generates TierLimitHittingAlertStream from supressedUserStream')\nfrom SuppressedTemporaryUserStream\nselect subscriber, apiCreator, apiName, applicationId, applicationName, apiCreatorTenantDomain, userTenantDomain, str:concat(\"User \", username, \" frequently crosses the limit set.\") as message, ${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into TierLimitHittingAlertStream;\n\n@info(name='Query inserts data to ApimAllAlert Table') \nfrom TierLimitHittingAlertStream\nselect \"FrequentTierLimitHitting\" as type, userTenantDomain as tenantDomain,message,severity,alertTimestamp\ninsert into ApimAllAlert;\n\n@info(name='Query inserts data to ApimTierLimitHittingAlert table')\nfrom TierLimitHittingAlertStream\nselect *\ninsert into ApimTierLimitHittingAlert;\n\n@info(name='Email generation query') \nfrom TierLimitHittingAlertStream#window.length(1) as TL join ApimAlertStakeholderInfo as ASI\non ((TL.subscriber == ASI.userId and true == ASI.isSubscriber ) or true == ASI.isAdmin )\nselect 'FrequentTierLimitHitting' as type ,\nifThenElse(str:contains(TL.message, 'Application frequently goes beyond the allocated quota'),str:concat(\"The application \", TL.applicationName, \" owned by \", TL.subscriber, \" frequently goes beyond the allocated quota when accessing the \", TL.apiName,\" API.\"),\nstr:concat(TL.message , \" Using the \", TL.applicationName, \" application owned by \",TL.subscriber, \".\")) as message, time:dateFormat(TL.alertTimestamp,'yyyy-MM-dd HH:mm:ss') as alertTimestamp,ASI.emails\nhaving  str:contains(ASI.alertTypes, 'FrequentTierLimitHitting')\ninsert into EmailAlertStream;\n"
               }
            ],
            "properties": {
               "numOfTierCrossing": {
                  "fieldName": "No of Tier Crossing",
                  "description": "Max Number of tier crossings for the given time window",
                  "defaultValue": "10"
               },
               "severityLevel": {
                  "fieldName": "Severity Level",
                  "description": " Severity level of the alert:(1:severe,2:moderate,3:mild)",
                  "defaultValue": "3",
                  "options": [
                     "1",
                     "2",
                     "3"
                  ]
               },
               "countingTime": {
                  "fieldName": "Counting Time Interval",
                  "description": "Time period (day/hours/min/sec) of which the request count would be taken. ",
                  "defaultValue": "1 hours"
               },
               "alertSupression": {
                  "fieldName": "Alert Supression Period",
                  "description": "Time period to wait before resending the same alert ",
                  "defaultValue": "10 minute"
               }
            }
         },
         {
            "uuid": "apim_health_availability_alert",
            "name": "APIM Health Availability Alert",
            "description": "Monitors the Health of an API",
            "type": "template",
            "instanceCount": "one",
            "script": "",
            "templates": [
               {
                  "type": "siddhiApp",
                  "content": "@App:name(\"apim_health_availability_alert_0\")\n@App:description(\"Determines the availablity and health of an api\")\n\n@source(type ='inMemory', topic = 'APIM_REQUEST_ALERT_INFO')\ndefine stream RequestAlertInfoStream (apiContext string,apiName string, apiVersion string, apiResourceTemplate string, apiMethod string, apiCreator string, apiCreatorTenantDomain string, requestTimestamp long, responseTime long, backendTime long, thresholdBackendTime long, thresholdResponseTime long,responseCode int );\n\n--Table Definitions\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAllAlert (type string, tenantDomain string, message string, severity int, alertTimestamp long);\n\n@primaryKey('tenantApiVersion')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAlertTableResponseInfo (tenantApiVersion string, count int);\n\n@primaryKey('apiName','apiVersion','tenantDomain')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimApiAvailabilityInfo (apiName string,apiVersion string, apiCreator string , tenantDomain string, status string);\n\n@PrimaryKey('userId', 'isSubscriber', 'isPublisher', 'isAdmin')\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimAlertStakeholderInfo(userId string, alertTypes\tstring, emails string, isSubscriber bool, isPublisher\tbool, isAdmin\tbool);\n\n@store(type = 'rdbms', datasource = 'APIM_ANALYTICS_DB')\ndefine table ApimApiHealthMonitorAlert(apiName string,apiVersion string,apiCreator string, apiCreatorTenantDomain string,\n message string, severity int, alertTimestamp long);\n\n@sink(type=\"inMemory\", topic=\"APIM_EMAIL_NOTIFICATION\", @map(type='passThrough'))\ndefine stream EmailAlertStream (type string, message string, alertTimestamp\tstring, emails string);\n\ndefine stream ApimAllAlertSummary (type string, tenantDomain string, message string, severity int, alertTimestamp long);\n\npartition with (apiContext of RequestAlertInfoStream)\nbegin\n    -- checks whether the response time is higher than the threshold response time continously for 5 times\n    from every e1=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0],e2=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0],e3=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0], e4=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0],e5=RequestAlertInfoStream[responseTime>thresholdResponseTime and thresholdResponseTime>0]\n    select e1.apiName,e1.apiVersion,e1.apiContext,e1.apiCreator,e1.apiCreatorTenantDomain,e1.thresholdResponseTime\n    insert into TempResponseTimeAlertStream;\n\n    --checks whether the response code is between 500 - 600 to identify a server error\n     from every e1=RequestAlertInfoStream[responseCode>=500 and responseCode<600],e2=RequestAlertInfoStream[responseCode>=500 and responseCode<600],e3=RequestAlertInfoStream[responseCode>=500 and responseCode<600], e4=RequestAlertInfoStream[responseCode>=500 and responseCode<600],e5=RequestAlertInfoStream[responseCode>=500 and responseCode<600]\n    select e1.apiName,e1.apiVersion,e1.apiContext,e1.apiCreator,e1.apiCreatorTenantDomain\n    insert into TempResponseCodeAlertStream;\nend;\n\n@info(name='Query generates ApiHealthMonitorAlertStreamTemp with message for high response time alert')\nfrom TempResponseTimeAlertStream\nselect apiName,apiVersion, apiCreator, apiCreatorTenantDomain, str:concat('Response time is higher than ' ,thresholdResponseTime, ' ms continuously for 5 or more responses.') as message, ${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into ApiHealthMonitorAlertStreamTemp;\n\n@info(name='Query generates ApiHealthMonitorAlertStreamTemp with message for server error alert')\nfrom TempResponseCodeAlertStream\nselect apiName, apiVersion, apiCreator, apiCreatorTenantDomain, 'Server error occurred continuously for 5 or more times.'  as message,${severityLevel} as severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into ApiHealthMonitorAlertStreamTemp;\n\n@info(name='Query generating TempallApimAlertStream')\nfrom ApiHealthMonitorAlertStreamTemp\nselect 'ApiHealthMonitor' as type, apiCreatorTenantDomain, str:concat('API:', apiName,' ',apiVersion, '-', message) as message , severity, (time:timestampInMilliseconds()) as alertTimestamp\ninsert into TempallApimAlertStream;\n\n--inserts data into ApimAllAlertSummary, if the same alert was not generated for a time defined in #window.time\n@info(name='Query generates ApimAllAlertSummary')\nfrom TempallApimAlertStream#window.length(1) as TA left outer join ApimAllAlertSummary#window.time(${alertSupressTime}) as AAS\non TA.message == AAS.message\nselect TA.type,TA.apiCreatorTenantDomain as tenantDomain,TA.message,TA.severity,TA.alertTimestamp\nhaving AAS.message is null\ninsert into ApimAllAlertSummary;\n\n@info(name='Query inserts data to ApimApiHealthMonitorAler')\n from ApiHealthMonitorAlertStreamTemp#window.length(1) as AH left outer join ApiHealthMonitorAlertStreamTemp#window.time(${alertSupressTime}) as AM\non AH.apiName==AM.apiName and AH.apiVersion==AM.apiVersion and AH.message==AM.message\nselect AH.apiName,AH.apiVersion,AH.apiCreator,AH.apiCreatorTenantDomain,AH.message,AH.severity,AH.alertTimestamp\nhaving AM.apiName is null and AM.apiVersion is null and AM.message is null\ninsert into ApimApiHealthMonitorAlert;\n\n@info(name='Query inserts data to ApimAllAlert')\nfrom ApimAllAlertSummary\nselect type,tenantDomain,message as message,severity,alertTimestamp\ninsert into ApimAllAlert;\n\n@info(name='Query inserts data to ApimApiAvailability')\nfrom ApiHealthMonitorAlertStreamTemp\nselect apiName,apiVersion,apiCreator,apiCreatorTenantDomain as tenantDomain,message as status\nupdate or insert into ApimApiAvailabilityInfo\nset ApimApiAvailabilityInfo.status=status\non ApimApiAvailabilityInfo.apiName==apiName and ApimApiAvailabilityInfo.apiVersion==apiVersion and ApimApiAvailabilityInfo.tenantDomain==tenantDomain;\n\n@info(name='Query inserting data to ApimApiAvailability when there is no alert for a defined time')\nfrom RequestAlertInfoStream#window.length(1) as R left outer join ApiHealthMonitorAlertStreamTemp#window.time(${availablityChange}) as AHM\non R.apiName==AHM.apiName and R.apiVersion==AHM.apiVersion\nselect R.apiName as apiName,R.apiVersion as apiVersion,R.apiCreator as apiCreator,R.apiCreatorTenantDomain as tenantDomain,\"Available\" as status\nhaving AHM.apiName is null\nupdate or insert into ApimApiAvailabilityInfo\nset ApimApiAvailabilityInfo.status=status\non ApimApiAvailabilityInfo.apiName==apiName and ApimApiAvailabilityInfo.apiVersion==apiVersion and ApimApiAvailabilityInfo.apiCreator==apiCreator and ApimApiAvailabilityInfo.tenantDomain==tenantDomain;\n\n@info(name='Query inserts data to TempStream')\n from ApiHealthMonitorAlertStreamTemp#window.length(1) as AH left outer join ApiHealthMonitorAlertStreamTemp#window.time(${alertSupressTime}) as AM\non AH.apiName==AM.apiName and AH.apiVersion==AM.apiVersion and AH.message==AM.message\nselect AH.apiName,AH.apiVersion,AH.apiCreator,AH.apiCreatorTenantDomain,AH.message,AH.severity,AH.alertTimestamp\nhaving AM.apiName is null and AM.apiVersion is null and AM.message is null\ninsert into ApiHealthMonitorAlertEmailStream;\n\n@info(name='Query inserting data to Alert Stream')\nfrom ApiHealthMonitorAlertEmailStream#window.length(1) join ApimAlertStakeholderInfo\non ((ApiHealthMonitorAlertEmailStream.apiCreator == ApimAlertStakeholderInfo.userId and true == ApimAlertStakeholderInfo.isPublisher ) or true == ApimAlertStakeholderInfo.isAdmin )\nselect 'ApiHealthMonitor' as type , str:concat('API:', apiName,' ',apiVersion, '-', message) as message, time:dateFormat(ApiHealthMonitorAlertEmailStream.alertTimestamp,'yyyy-MM-dd HH:mm:ss') as alertTimestamp, ApimAlertStakeholderInfo.emails\nhaving str:contains(ApimAlertStakeholderInfo.alertTypes, 'ApiHealthMonitor')\ninsert into EmailAlertStream;\n"
               }
            ],
            "properties": {
               "severityLevel": {
                  "fieldName": "Severity Level",
                  "description": "Severity level of the alert:(1:severe,2:moderate,3:mild)",
                  "defaultValue": "2",
                  "options": [
{'fraction_non_alphanumeric': 0.10457961151283142, 'fraction_numerical': 0.005728058981993478, 'mean_word_length': 5.424849699398798, 'pattern_counts': {'":': 94, '<': 13, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1095383', 'n_tokens_mistral': 10316, 'n_tokens_neox': 9835, 'n_words': 2338}