-- Job 상태 표시를 위해 view table 생성
CREATE VIEW v_cmoa_job AS
    select Q.kube_flatting_time, Q.cluster_id, Q.metadata_ownerreferences_kind, Q.metadata_uid, K.status_phase
        from (select A.kube_flatting_time as job_flatting_time, A.metadata_uid as job_metadata_uid, B.kube_flatting_time as pod_flatting_time
                from (select metadata_uid, max(kube_flatting_time) as kube_flatting_time
                        from cmoa_job_base
                        where kind='Job' and kube_flatting_time > extract(epoch from (CURRENT_TIMESTAMP - INTERVAL '1 hours'))*1000
                        group by metadata_uid) A,
                     (select metadata_ownerreferences_uid, max(kube_flatting_time) as kube_flatting_time
                        from cmoa_pod_base
                        where metadata_ownerreferences_kind='Job' and kube_flatting_time > extract(epoch from (CURRENT_TIMESTAMP - INTERVAL '1 hours'))*1000
                        group by metadata_ownerreferences_uid) B
        where A.metadata_uid = B.metadata_ownerreferences_uid) J
    inner join cmoa_job_base Q on Q.metadata_uid = J.job_metadata_uid and Q.kube_flatting_time = J.job_flatting_time
    inner join cmoa_pod_base K on K.metadata_ownerreferences_uid = J.job_metadata_uid and K.kube_flatting_time = J.pod_flatting_time
    group by Q.kube_flatting_time, Q.cluster_id, Q.metadata_ownerreferences_kind, Q.metadata_uid, K.status_phase;

-- CLOUD-17051 | Dashboard > Redis 관련 이슈 대응
-- Auto-generated SQL script #202306011616
UPDATE public.metric_meta2
  SET expr='sum by (data_type, xm_clst_id, xm_namespace, xm_node_id, instance) (
label_replace(rate(redis_cpu_sys_seconds_total[1m]), "data_type", "system", "", "") or 
label_replace(rate(redis_cpu_user_seconds_total[1m]), "data_type", "user", "", "") )'
  WHERE id='redis_cpu_usage';
UPDATE public.metric_meta2
  SET expr='sum by (xm_clst_id, xm_namespace, xm_node_id, instance) (rate(redis_cpu_sys_children_seconds_total[1m]))'
  WHERE id='redis_used_cpu_sys_children';
UPDATE public.metric_meta2
  SET expr='sum by (xm_clst_id, xm_namespace, xm_node_id, instance) (rate(redis_cpu_user_seconds_total[1m]))'
  WHERE id='redis_used_cpu_user';
UPDATE public.metric_meta2
  SET expr='sum by (xm_clst_id, xm_namespace, xm_node_id, instance) (rate(redis_cpu_user_children_seconds_total [1m]))'
  WHERE id='redis_used_cpu_user_children';
UPDATE public.metric_meta2
  SET expr='sum by (xm_clst_id, xm_namespace, xm_node_id, instance) (rate(redis_cpu_sys_seconds_total[1m]))'
  WHERE id='redis_used_cpu_sys';

-- CLOUD-17354 | NginX 관련 metric meta 추가
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_up','Nginx Up','Nginx Up Time','sum by (instance) (nginx_up)','State','Nginx','','true','false','"Nginx Up Time : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_connections_accepted','Nginx Accepted Connection Count','Accepted connection count of Nginx','sum by (instance) (irate(nginx_connections_accepted[5m]))','Connection','Nginx','','true','false','"Nginx Connection : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_connections_handled','Nginx Handled Connection Count','Handled connection count of Nginx','sum by (instance) (irate(nginx_connections_handled[5m]))','Connection','Nginx','','true','false','"Nginx Connection : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_connections_active','Nginx Active Connection Count','Active connection count of Nginx','sum by (instance) (nginx_connections_active)','Connection','Nginx','','true','false','"Nginx Connection : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_connections_reading','Nginx Reading Connection Count','Reading connection count of Nginx','sum by (instance) (nginx_connections_reading)','Connection','Nginx','','true','false','"Nginx Connection : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_connections_waiting','Nginx Waiting Connection Count','Waiting connection count of Ngin','sum by (instance) (nginx_connections_waiting)','Connection','Nginx','','true','false','"Nginx Connection : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_connections_writing','Nginx Writing Connection Count','Writing connection count of NginX','sum by (instance) (nginx_connections_writing)','Connection','Nginx','','true','false','"Nginx Connection : {{$value}} , Threshold : {threshold}"');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('nginx_http_requests_total','Nginx Http Requests','Http request count of Nginx','sum by (instance) (irate(nginx_http_requests_total[1m]))','Request','Nginx','','true','false','"Http requests : {{$value}} , Threshold : {threshold}"');

-- CLOUD-17354 | NginX Dashboard 추가
INSERT INTO public.auth_resource3 (name, is_deleted, tenant_id) VALUES ('dashboard|admin|Nginx', false, null);
INSERT INTO public.dashboard2 (id, created_date, modified_date, layout, title, auth_resource_id, created_by, modified_by, description, "share")
  VALUES(nextval('hibernate_sequence'),'2023-06-28 15:16:36.511000','2023-06-29 09:33:06.665000','[{"i":"widget1","widget":{"header":"default-header","body":"stack-bar-chart-view","title":"Accepted Connections","description":"Accepted connection count of Nginx"},"w":18,"h":11,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_accepted","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":30,"y":11,"static":true},{"i":"widget2","widget":{"header":"default-header","body":"stack-bar-chart-view","title":"Handled Connections","description":"Handled connection count of Nginx"},"w":18,"h":14,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_handled","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":30,"y":22,"static":true},{"i":"widget3","widget":{"header":"default-header","body":"line-chart-view","title":"Active Connections","description":"Active connection count of Nginx"},"w":12,"h":14,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_active","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":0,"y":8,"static":true},{"i":"widget4","widget":{"header":"default-header","body":"line-chart-view","title":"Waiting Connections","description":"Waiting connection count of Nginx"},"w":12,"h":14,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_waiting","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":12,"y":8,"static":true},{"i":"widget5","widget":{"header":"default-header","body":"stack-bar-chart-view","title":"Reading Connections","description":"Reading connection count of Nginx"},"w":12,"h":14,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_reading","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":0,"y":22,"static":true},{"i":"widget6","widget":{"header":"default-header","body":"stack-bar-chart-view","title":"Writing Connection","description":"Writing connection count of Nginx"},"w":12,"h":14,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_writing","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":12,"y":22,"static":true},{"i":"widget7","widget":{"header":"default-header","body":"label-view","title":" "},"w":24,"h":3,"minW":2,"minH":1,"maxW":48,"maxH":36,"component":{"api":{},"visualization":{"background":null,"fontSize":20,"textAlign":"left","padding":[0,18],"sideways":false,"fontWeight":"bold","text":"Nginx Information"}},"x":0,"y":0,"static":true},{"i":"widget0","widget":{"header":"default-header","body":"stat-view","title":"Active"},"w":6,"h":5,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_active","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":0,"y":3,"static":true},{"i":"widget8","widget":{"header":"default-header","body":"stat-view","title":"Waiting"},"w":6,"h":5,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_waiting","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":6,"y":3,"static":true},{"i":"widget9","widget":{"header":"default-header","body":"stat-view","title":"Reading"},"w":6,"h":5,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_reading","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":12,"y":3,"static":true},{"i":"widget10","widget":{"header":"default-header","body":"stat-view","title":"Writing"},"w":6,"h":5,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_writing","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":18,"y":3,"static":true},{"i":"widget11","widget":{"header":"default-header","body":"line-chart-view","title":"Http Request"},"w":18,"h":11,"minW":8,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":false,"range":true,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_http_requests_total","entityId":"","type":"Nginx","filter":""}},"visualization":{"showLegend":true}},"x":30,"y":0,"static":true},{"i":"widget12","widget":{"header":"default-header","body":"stat-view","title":"Http Request"},"w":6,"h":11,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_http_requests_total","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":24,"y":0,"static":true},{"i":"widget13","widget":{"header":"default-header","body":"stat-view","title":"Accepted Count"},"w":6,"h":11,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_accepted","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":24,"y":11,"static":true},{"i":"widget14","widget":{"header":"default-header","body":"stat-view","title":"Handled Count"},"w":6,"h":14,"minW":6,"minH":4,"maxW":48,"maxH":18,"component":{"api":{"uri":"metric.chart","params":{"unique":true,"range":false,"clusterId":"cloudmoa","namespace":"","metricId":"nginx_connections_handled","entityId":"","type":"Nginx","filter":""}},"visualization":{"showGauge":false,"showPercent":false,"min":"0","max":null,"decimals":null,"baseColor":"#409EFF","thresholds":[]}},"x":24,"y":22,"static":true}]',
  'Nginx Dashboard',(select id from auth_resource3 where name='dashboard|admin|Nginx'),'admin','admin','Nginx Dashboard',true);

-- CLOUD-17326 | Kube Event 관련 metric meta 추가
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_node','Kubernetes Node Event','Kubernetes Node Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="Node"})','Event','Node','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_job','Kubernetes Job Event','Kubernetes Job Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="Job"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_cronjob','Kubernetes CronJob Event','Kubernetes CronJob Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="CronJob"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_daemonset','Kubernetes DaemonSet Event','Kubernetes DaemonSet Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="DaemonSet"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_deployment','Kubernetes Deployment Event','Kubernetes Deployment Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="Deployment"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_endpoints','Kubernetes Endpoints Event','Kubernetes Endpoints Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="Endpoints"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_persistentvolumeclaim','Kubernetes PersistentVolumeClaim Event','Kubernetes PersistentVolumeClaim Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="PersistentVolumeClaim"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_pod','Kubernetes Pod Event','Kubernetes Pod Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="Pod"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_warning','Kubernetes Warning Event','Kubernetes Warning Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{type="Warning"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}} Name: {{$involved_name}} Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_replicaset','Kubernetes ReplicaSet Event','Kubernetes ReplicaSet Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="ReplicaSet"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('kube_event_statefulset','Kubernetes StatefulSet Event','Kubernetes StatefulSet Event','count by (xm_clst_id,xm_namespace,entity_type,involved_kind,involved_name,reason,type) (imxc_kubernetes_event_in_last_min{involved_kind="StatefulSet"})','Event','Workload','','true','false','CLST:{{$labels.xm_clst_id}} NS:{{$labels.xm_namespace}}  Reason : {{$labels.reason}} Level : {{$labels.type}} ');

-- Container 의 Limit 대비 CPU/Memory 사용량 metric meta 추가
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('container_cpu_usage_against_limit','Container CPU Usage Against Limits (%)','Conatiner CPU Usage Against Limits ( % ) ','sum by(xm_clst_id,xm_namespace,owner_name,xm_pod_id,xm_cont_name,xm_entity_type) (rate(imxc_kubernetes_container_resource_limit_cpu{xm_cont_name!="POD"} [1m])+ on (xm_clst_id,xm_namespace,xm_pod_id,xm_cont_name) group_left(owner_name) (sum (imxc_kubernetes_container_resource_limit_cpu{container_state="Running",pod_state="Running",{filter}}) without (instance)) * 0)','CPU','Workload','','true','false','CLST:{{$labels.xm_clst_id}} DP:{{$labels.owner_name}} CT:{{$labels.xm_cont_name}} PD:{{$labels.xm_pod_id}} CPU Usage (%):{{humanize $value}}%|{threshold}%.');
INSERT INTO public.metric_meta2 (id,meta_name,description,expr,resource_type,entity_type,groupby_keys,in_use,anomaly_score,message) VALUES('container_memory_usage_against_limit','Container Memory Usage Against Limit','Container Memory Usage Against Limit','sum by(xm_clst_id,xm_namespace,xm_pod_id,xm_cont_name,xm_entity_type,owner_name) (container_memory_usage_bytes{xm_cont_name!="POD"} / on (xm_clst_id,xm_namespace,xm_cont_name,xm_pod_id) group_left(owner_name) (sum (imxc_kubernetes_container_resource_limit_memory{container_state="Running",pod_state="Running",xm_cont_name!="POD",{filter}}) without (instance))) * 100','Memory','Workload','','true','false','CLST:{{$labels.xm_clst_id}} DP:{{$labels.owner_name}} CT:{{$labels.xm_cont_name}} PD:{{$labels.xm_pod_id}} Memory Limit Against Usage:{{humanize $value}}%|{threshold}%.');


commit;
