CREATE TABLE public.cloud_user_setting (
    user_id character varying(255) NOT NULL,
    lang character varying(20) DEFAULT 'en',
    theme character varying(20) DEFAULT 'dark',
    access_token integer DEFAULT 30,
    refresh_token integer DEFAULT 10080,
    error_msg boolean DEFAULT false,
    alert_sound boolean DEFAULT false,
    session_persistence boolean DEFAULT true,
    gpu_acc_topology boolean DEFAULT true,
    created_date timestamp without time zone,
    modified_date timestamp without time zone
);

ALTER TABLE public.cloud_user_setting OWNER TO admin;

ALTER TABLE ONLY public.cloud_user_setting ADD CONSTRAINT cloud_user_setting_pkey PRIMARY KEY (user_id);

INSERT INTO public.cloud_user_setting
(user_id, lang, theme, access_token, refresh_token, error_msg, alert_sound, session_persistence, gpu_acc_topology, created_date, modified_date)
VALUES('admin', null, null, null, null, false, false, true, true, now(), null);

INSERT INTO public.cloud_user_setting
(user_id, lang, theme, access_token, refresh_token, error_msg, alert_sound, session_persistence, gpu_acc_topology, created_date, modified_date)
VALUES('owner', null, null, null, null, false, false, true, true, now(), null);

-- 더존(3.3.2) 에서 누락되었던 항목 모두 추가
INSERT INTO public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date) VALUES ('normal_score', '20', null, null, 'anomaly', '2020-07-07 18:15:55.000000', '2020-07-07 18:15:53.000000');
INSERT INTO public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date) VALUES ('attention_score', '60', null, null, 'anomaly', '2020-07-07 09:18:04.968765', '2020-07-07 09:18:04.968765');
INSERT INTO public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date) VALUES ('warning_score', '90', null, null, 'anomaly', '2020-07-07 09:18:17.091678', '2020-07-07 09:18:17.091678');
INSERT INTO public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date) VALUES ('collection_weeks', '5', null, null, 'anomaly', '2020-07-13 03:52:44.445408', '2020-07-13 03:52:44.445408');

insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('topology_storage_period', 7, 'retention period setting value for topology information', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('trace_storage_period', 3, 'retention period setting value for trace data', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('event_storage_period', 7, 'retention period setting value for event data', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('metric_storage_period', 7, 'retention period setting value for metric data', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('sparse_storage_period', 90, 'retention period setting value for sparse log', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('anomaly_storage_period', 7, 'retention period setting value for anomaly score', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('alert_storage_period', 7, 'retention period setting value for alert data', null, 'storage', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('audit_storage_period', 7, 'retention period setting value for audit data', null, 'storage', now(), null);

insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('topology_idx', 'kubernetes_cluster_info:kubernetes_cluster_history:kubernetes_cronjob_info:kubernetes_info:kubernetes_job_info:kubernetes_network_connectivity:kubernetes_pod_info:kubernetes_pod_history', 'elastic search topology type data index', null, 'storageidx', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('trace_idx', 'spaninfo:sta_httpapi:sta_httpsummary:sta_podinfo:sta_relation:sta_tracetrend:sta_externalrelation:sta_traceinfo:jspd_ilm', 'elastic search trace type data index', null, 'storageidx', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('event_idx', 'kubernetes_event_info', 'elastic search for event data index', null, 'storageidx', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('sparse_idx', 'sparse_model:sparse_log', 'elastic search sparse data index', null, 'storageidx', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('anomaly_idx', 'entity_score:metric_score:timeline_score', 'elastic search amomaly data index', null, 'storageidx', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('alert_idx', 'alert_event_history', 'elastic search alert data index', null, 'storageidx', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('audit_idx', 'kubernetes_audit_log', 'elastic search audit type data index', null, 'storageidx', now(), null);

-- insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date) values ('ratelimiting', 2.0, '{"type" : "int", "operator" : "range", "minVal" : "1", "maxVal" : "3000", "desc" : "The time-based sampling method allows input as an integer (e.g. 1 monitors only 1 trace per second)" }', null, 'tracesampling', '2020-07-30 13:54:52', null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('probabilistic', 0.1, '{"type" : "float", "operator" : "range", "minVal" : "0", "maxVal" : "1.0", "desc" : "Probability-based sampling method allows input between 0 and 1 (e.g. 0.1 monitors only 10% of trace information)" }', null, 'tracesampling', '2020-07-30 13:54:52', null);

INSERT INTO common_setting values('alert_expression','==,<=,<,>=,>', 'alert expression for user custom', null,'alert', now(), now());

INSERT INTO common_setting values('job_duration_range','86400', 'job duration range for average', null,'job', now(), now());

insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Topology Agent', 'topology-agent', 'topology agent deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Metric Agent', 'metric-agent', 'metric agent deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Trace Agent', 'trace-agent', 'trace agent deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Datagate', 'datagate', 'datagate deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Jspd Collector', 'jspd-lite-collector', 'jspd collector deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Metric Collector', 'metric-collector', 'metric collector deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Cloudmoa Collector', 'imxc-collector', 'cloudmoa collector deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Authentication Server', 'auth-server', 'authentication server deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Notification Server', 'noti-server', 'notification server deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Eureka Server', 'eureka', 'eureka server deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Zuul Server', 'zuul-deployment', 'zuul server deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Api Server', 'imxc-api-demo', 'api server deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Ui Server', 'imxc-ui-demo', 'ui server deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Metric Analyzer Master', 'metric-analyzer-master', 'metric analyzer master deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Metric Analyzer Worker', 'metric-analyzer-worker', 'metric analyzer worker deployment name', null, 'modules', now(), null);
insert into public.common_setting (code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
values ('Kafka Stream Txntrend', 'kafka-stream-txntrend-deployment', 'kafka stream txntrend deployment name', null, 'modules', now(), null);

INSERT INTO public.common_setting
(code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
VALUES('error_msg', 'false', 'Error Message default value', '', 'user_setting', now(), null);

INSERT INTO public.common_setting
(code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
VALUES('alert_sound', 'false', 'Alert Sound default value', '', 'user_setting', now(), null);

INSERT INTO public.common_setting
(code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
VALUES('session_persistence', 'true', 'Session Persistence default value', '', 'user_setting', now(), null);

INSERT INTO public.common_setting
(code_id, code_value, code_desc, code_auth, code_group, created_date, modified_date)
VALUES('gpu_acc_topology', 'true', 'GPU Accelerated Topology default value', '', 'user_setting', now(), null);

UPDATE public.agent_install_file_info
SET yaml = '---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cloudmoa-cluster-role
rules:
  - nonResourceURLs:
      - "*"
    verbs:
      - get
  - apiGroups:
      - metrics.k8s.io
    resources:
      - pods
      - nodes
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - pods
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - ""
    resources:
      - services
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - ""
    resources:
      - nodes/stats
      - endpoints
      - namespaces
      - events
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - apps
    resources:
      - daemonsets
      - deployments
      - deployments/scale
      - replicasets
      - replicasets/scale
      - statefulsets
      - statefulsets/scale
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - batch
    resources:
      - jobs
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - batch
    resources:
      - cronjobs
    verbs:
      - get
      - list
      - update
  - apiGroups:
      - storage.j8s.io
    resources:
      - storageclasses
    verbs:
      - get
      - list
  - apiGroups:
      - networking.k8s.io
    resources:
      - ingresses
    verbs:
      - get
      - list
  - apiGroups:
      - extensions
    resources:
      - ingresses
    verbs:
      - get
      - list
  - apiGroups:
      - policy
    resources:
      - podsecuritypolicies
    verbs:
      - use
    resourceNames:
      - imxc-ps
  - apiGroups:
      - certificates.k8s.io
    resourceNames:
      - kubernetes.io/kube-apiserver-client-kubelet
    resources:
      - signers
    verbs:
      - approve
  - apiGroups:
      - certificates.k8s.io
    resourceNames:
      - kubernetes.io/kubelet-serving
    resources:
      - signers
    verbs:
      - approve
  - apiGroups:
      - ""
    resources:
      - nodes
    verbs:
      - get
      - list
      - watch
      - proxy
  - apiGroups:
      - ""
    resources:
      - nodes/log
      - nodes/metrics
      - nodes/proxy
      - nodes/spec
      - nodes/stats
    verbs:
      - ''*''
  - apiGroups:
      - ''*''
    resources:
      - ''*''
    verbs:
      - get
      - list
      - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: cloudmoa-restricted-rb
  namespace: $CLOUDMOA_NAMESPACE
subjects:
  - kind: ServiceAccount
    name: default
    namespace: $CLOUDMOA_NAMESPACE
roleRef:
  kind: ClusterRole
  name: cloudmoa-cluster-role
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: cloudmoa-psp
  namespace: $CLOUDMOA_NAMESPACE
spec:
  privileged: true
  seLinux:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  runAsUser:
    rule: RunAsAny
  fsGroup:
    rule: RunAsAny
  hostPorts:
    - max: 65535
      min: 0
  hostNetwork: true
  hostPID: true
  volumes:
    - configMap
    - secret
    - emptyDir
    - hostPath
    - projected
    - downwardAPI
    - persistentVolumeClaim
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cloudmoa-topology-agent
  namespace: $CLOUDMOA_NAMESPACE
  labels:
    app: cloudmoa-topology-agent
spec:
  selector:
    matchLabels:
      app: cloudmoa-topology-agent
  template:
    metadata:
      labels:
        app: cloudmoa-topology-agent
    spec:
      hostNetwork: true
      hostPID: true
      tolerations:
      - effect: NoSchedule
        operator: Exists
      - effect: NoExecute
        operator: Exists
      containers:
      - name: cloudmoa-topology-agent
        image: $DOCKER_REGISTRY_URL/topology-agent:$IMAGE_TAG
        resources:
          requests:
            cpu: 200m
            memory: 512Mi
          limits:
            cpu: 500m
            memory: 600Mi
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /host/usr/bin
          name: bin-volume
        - mountPath: /var/run/docker.sock
          name: docker-volume
        - mountPath: /host/proc
          name: proc-volume
        - mountPath: /root
          name: root-volume
        - mountPath: /log
          name: log-volume
        env:
          - name: DATAGATE
            value: $COLLTION_SERVER_DATAGATE_IP:$COLLTION_SERVER_DATAGATE_PORT
          - name: CLUSTER_ID
            value: $CLOUDMOA_CLUSTER_ID
          - name: ROOT_DIRECTORY
            value: /root
          - name: NODE_NAME
            valueFrom:
              fieldRef:
                apiVersion: v1
                fieldPath: spec.nodeName
          - name: POD_ID
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
          - name: LOG_LEVEL
            value: "INFO"
      volumes:
      - name: bin-volume
        hostPath:88888889
          path: /usr/bin
          type: Directory
      - name: docker-volume
        hostPath:
          path: /var/run/docker.sock
      - name: proc-volume
        hostPath:
          path: /proc
      - name: root-volume
        hostPath:
          path: /
      - name: log-volume
        hostPath:
          path: /home'::text
WHERE id = 2::bigint;

UPDATE public.common_setting
SET code_group='storageidx'
WHERE code_id='topology_idx';

UPDATE public.common_setting
SET code_value='spaninfo:sta_httpapi:sta_httpsummary:sta_podinfo:sta_relation:sta_tracetrend:sta_externalrelation:sta_traceinfo:jspd_ilm',
    code_group='storageidx'
WHERE code_id='trace_idx';

UPDATE public.common_setting
SET code_group='storageidx'
WHERE code_id='event_idx';

UPDATE public.common_setting
SET code_group='storageidx'
WHERE code_id='sparse_idx';

UPDATE public.common_setting
SET code_group='storageidx'
WHERE code_id='anomaly_idx';

UPDATE public.common_setting
SET code_value='alert_event_history',
    code_group='storageidx'
WHERE code_id='alert_idx';

UPDATE public.common_setting
SET code_group='storageidx'
WHERE code_id='audit_idx';

UPDATE public.agent_install_file_info SET yaml = '---
apiVersion: v1
kind: Service
metadata:
  annotations:
    prometheus.io/scrape: ''true''
  labels:
    app: cloudmoa-node-exporter
    name: cloudmoa-node-exporter
  name: cloudmoa-node-exporter
  namespace: $CLOUDMOA_NAMESPACE
spec:
  clusterIP: None
  ports:
    - name: scrape
      port: 9110
      protocol: TCP
  selector:
    app: cloudmoa-node-exporter
  type: ClusterIP
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cloudmoa-node-exporter
  namespace: $CLOUDMOA_NAMESPACE
spec:
  selector:
    matchLabels:
      app: cloudmoa-node-exporter
  template:
    metadata:
      labels:
        app: cloudmoa-node-exporter
      name: cloudmoa-node-exporter
    spec:
      tolerations:
        - effect: NoSchedule
          operator: Exists
        - effect: NoExecute
          operator: Exists
      containers:
        - image: $DOCKER_REGISTRY_URL/node-exporter
          name: cloudmoa-node-exporter
          ports:
            - containerPort: 9110
              hostPort: 9110
              name: scrape
          args:
            - --path.procfs=/host/proc
            - --path.sysfs=/host/sys
            - --path.rootfs=/host/root
            - --collector.filesystem.ignored-mount-points=^/(dev|proc|sys|run|var/lib/docker/.+|var/lib/kubelet/pods/.+)($|/)
            - --collector.tcpstat
            - --web.listen-address=:9110
          # --log.level=debug
          resources:
            limits:
              cpu: 250m
              memory: 180Mi
            requests:
              cpu: 102m
              memory: 180Mi
          volumeMounts:
            - mountPath: /host/proc
              name: proc
              readOnly: false
            - mountPath: /host/sys
              name: sys
              readOnly: false
            - mountPath: /host/root
              mountPropagation: HostToContainer
              name: root
              readOnly: true
      hostNetwork: true
      hostPID: true
      securityContext:
        runAsNonRoot: true
        runAsUser: 65534
      volumes:
        - hostPath:
            path: /proc
          name: proc
        - hostPath:
            path: /sys
          name: sys
        - hostPath:
            path: /
          name: root
'::text WHERE id = 4::bigint;

UPDATE public.agent_install_file_info SET yaml = '---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: system:cloudmoa-aggregated-metrics-reader
  labels:
    rbac.authorization.k8s.io/aggregate-to-view: "true"
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
  - apiGroups: ["metrics.k8s.io"]
    resources: ["pods"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: cloudmoa-metrics-server:system:auth-delegator
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: cloudmoa-metrics-server
    namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: cloudmoa-metrics-server-auth-reader
  namespace: kube-system
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: extension-apiserver-authentication-reader
subjects:
  - kind: ServiceAccount
    name: cloudmoa-metrics-server
    namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: system:cloudmoa-metrics-server
rules:
  - apiGroups:
      - ""
    resources:
      - pods
      - nodes
      - nodes/stats
    verbs:
      - get
      - list
      - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: system:cloudmoa-metrics-server
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:cloudmoa-metrics-server
subjects:
  - kind: ServiceAccount
    name: cloudmoa-metrics-server
    namespace: kube-system
---
apiVersion: v1
kind: Service
metadata:
  name: cloudmoa-metrics-server
  namespace: kube-system
  labels:
    kubernetes.io/name: "Metrics-server"
spec:
  selector:
    k8s-app: cloudmoa-metrics-server
  ports:
    - port: 443
      protocol: TCP
      targetPort: 443
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: cloudmoa-metrics-server
  namespace: kube-system
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloudmoa-metrics-server
  namespace: kube-system
  labels:
    k8s-app: cloudmoa-metrics-server
spec:
  selector:
    matchLabels:
      k8s-app: cloudmoa-metrics-server
  template:
    metadata:
      name: cloudmoa-metrics-server
      labels:
        k8s-app: cloudmoa-metrics-server
    spec:
      serviceAccountName: cloudmoa-metrics-server
      volumes:
        # mount in tmp so we can safely use from-scratch images and/or read-only containers
        - name: tmp-dir
          emptyDir: {}
      containers:
        - name: cloudmoa-metrics-server
          image: $DOCKER_REGISTRY_URL/metrics-server-amd64
          command:
            - /metrics-server
            - --logtostderr
            - --v=4
            - --kubelet-insecure-tls=true
            - --kubelet-preferred-address-types=InternalIP,Hostname,InternalDNS,ExternalDNS,ExternalIP
          volumeMounts:
            - name: tmp-dir
              mountPath: /tmp1'::text WHERE id = 5::bigint;

UPDATE public.agent_install_file_info SET yaml = '---
apiVersion: v1
kind: ConfigMap
metadata:
  name: cloudmoa-metric-agent-config
  namespace: $CLOUDMOA_NAMESPACE
data:
  scaling.rules: |
    groups:
    - name: scaleup
      rules :
      - alert : ScaleUpRule
        expr: job:webapp_config_open_sessions_current_count:sum > 15
        annotations:
          summary: "Scale up when current sessions is greater than 15"
          description: "Firing when total sessions active greater than 15"
  metric-agent.yml: |
    global:
      scrape_interval:     15s

    scrape_configs:
      - job_name: ''kubernetes-kubelet''
        scheme: https
        tls_config:
          ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
        kubernetes_sd_configs:
        - role: node
        relabel_configs:
        - action: labelmap
          regex: __meta_kubernetes_node_label_(.+)
        - target_label: __address__
          replacement: kubernetes.default.svc:443
        - source_labels: [__meta_kubernetes_node_name]
          regex: (.+)
          target_label: __metrics_path__
          replacement: /api/v1/nodes/${1}/proxy/metrics
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: xm_node_id
        - target_label: xm_clst_id
          replacement: ''$CLOUDMOA_CLUSTER_ID''
        - target_label: xm_entity_type
          replacement: ''Node''

        metric_relabel_configs:
        - source_labels: [ __name__ ]
          regex: (kubelet_running_pod_count)
          action: keep

      - job_name: ''kubernetes-node-exporter''
        tls_config:
          ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
        kubernetes_sd_configs:
        - role: node

        relabel_configs:
        - action: labelmap
          regex: __meta_kubernetes_node_label_(.+)
        - source_labels: [__meta_kubernetes_role]
          action: replace
          target_label: kubernetes_role
        - source_labels: [__address__]
          regex: ''(.*):10250''
          replacement: ''${1}:9110''
          target_label: __address__
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: __instance__
          # set "name" value to "job"
        - source_labels: [job]
          regex: ''kubernetes-(.*)''
          replacement: ''${1}''
          target_label: name
        - target_label: xm_clst_id
          replacement: ''$CLOUDMOA_CLUSTER_ID''
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: xm_node_id
        - target_label: xm_entity_type
          replacement: ''Node''
        - source_labels: [__meta_kubernetes_namespace]
          separator: ;
          regex: (.*)
          target_label: xm_namespace
          replacement: $1
          action: replace
        metric_relabel_configs:
        - source_labels: [ __name__ ]
          regex: (node_boot_time_seconds|node_context_switches_total|node_cpu_frequency_max_hertz|node_cpu_package_throttles_total|node_cpu_seconds_total|node_disk_io_time_seconds_total|node_disk_read_bytes_total|node_disk_read_time_seconds_total|node_disk_reads_completed_total|node_disk_write_time_seconds_total|node_disk_writes_completed_total|node_disk_written_bytes_total|node_filefd_allocated|node_filesystem_avail_bytes|node_filesystem_free_bytes|node_filesystem_size_bytes|node_load1|node_load15|node_load5|node_memory_Active_bytes|node_memory_Buffers_bytes|node_memory_Cached_bytes|node_memory_MemAvailable_bytes|node_memory_MemFree_bytes|node_memory_MemTotal_bytes|node_memory_SwapCached_bytes|node_memory_SwapFree_bytes|node_memory_SwapTotal_bytes|node_network_receive_bytes_total|node_network_receive_bytes_total|node_network_transmit_bytes_total|node_network_transmit_bytes_total)
          action: keep


      - job_name: ''kubernetes-cadvisor''
        scheme: https
        tls_config:
          ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
          insecure_skip_verify: true
        bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
        kubernetes_sd_configs:
        - role: node
        metrics_path: /metrics/cadvisor

        relabel_configs:
        - action: labelmap
          regex: __meta_kubernetes_node_label_(.+)
        - target_label: xm_clst_id
          replacement: ''$CLOUDMOA_CLUSTER_ID''
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: xm_node_id
        - target_label: xm_entity_type
          replacement: ''Container''

        metric_relabel_configs:
        - source_labels: [namespace]
          target_label: xm_namespace
        - source_labels: [pod_name]
          target_label: xm_pod_id
        - source_labels: [container_name]
          target_label: xm_cont_name
        - source_labels: [id]
          target_label: xm_cont_id
        - source_labels: [container_name]
          regex: (.+)
          action: keep
        - source_labels: [ __name__ ]
          regex: (container_cpu_cfs_throttled_seconds_total|container_cpu_system_seconds_total|container_cpu_usage_seconds_total|container_cpu_user_seconds_total|container_fs_limit_bytes|container_fs_reads_bytes_total|container_fs_usage_bytes|container_fs_writes_bytes_total|container_last_seen|container_memory_cache|container_memory_max_usage_bytes|container_memory_swap|container_memory_usage_bytes|container_memory_working_set_bytes|container_network_receive_bytes_total|container_network_transmit_bytes_total|container_spec_memory_limit_bytes)
          action: keep
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloudmoa-metric-agent
  namespace: $CLOUDMOA_NAMESPACE
  labels:
    app: cloudmoa-metric-agent
spec:
  selector:
    matchLabels:
      app: cloudmoa-metric-agent
  replicas: 1
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: cloudmoa-metric-agent
    spec:
      containers:
        - name: cloudmoa-metric-agent
          image: $DOCKER_REGISTRY_URL/metric-agent:$IMAGE_TAG
          args:
            - --config.file=/etc/metric-agent/metric-agent.yml
          resources:
            requests:
              cpu: 100m
              memory: 512Mi
            limits:
              cpu: 300m
              memory: 1000Mi
          volumeMounts:
            - mountPath: /etc/metric-agent/
              name: config-volume
          env:
            - name: LOG_LEVEL
              value: "INFO"
            - name: CLUSTER_ID
              value: $CLOUDMOA_CLUSTER_ID
            - name: DATAGATE
              value: $COLLTION_SERVER_DATAGATE_IP:$COLLTION_SERVER_DATAGATE_PORT
            - name: STORAGE_TYPE
              value: datagate
      restartPolicy: Always
      volumes:
        - name: config-volume
          configMap:
            name: cloudmoa-metric-agent-config
'::text WHERE id = 3::bigint;

UPDATE public.agent_install_file_info SET yaml = '---
apiVersion: v1
kind: List
items:
- apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: cloudmoa-trace-agent
    namespace: $CLOUDMOA_NAMESPACE
    labels:
      app: cloudmoa-trace-agent
  spec:
    selector:
      matchLabels:
        app: cloudmoa-trace-agent
    replicas: 1
    strategy:
      type: Recreate
    template:
      metadata:
        labels:
          app: cloudmoa-trace-agent
      spec:
        securityContext:
          runAsNonRoot: true
          runAsUser: 65534
        containers:
          - image: $DOCKER_REGISTRY_URL/trace-agent:$IMAGE_TAG
            name: cloudmoa-trace-agent
            resources:
              requests:
                cpu: 100m
                memory: 50Mi
              limits:
                cpu: 200m
                memory: 100Mi
            ports:
              - containerPort: 5775
                protocol: UDP
              - containerPort: 6831
                protocol: UDP
              - containerPort: 6832
                protocol: UDP
              - containerPort: 5778
                protocol: TCP
            env:
              - name: LOG_LEVEL
                value: "INFO"
              - name: CLUSTER_ID
                value: $CLOUDMOA_CLUSTER_ID
              - name: DATAGATE
                value: $COLLTION_SERVER_DATAGATE_IP:$COLLTION_SERVER_DATAGATE_PORT
- apiVersion: v1
  kind: Service
  metadata:
    name: cloudmoa-trace-agent
    namespace: $CLOUDMOA_NAMESPACE
    labels:
      app: cloudmoa-trace-agent
  spec:
    ports:
      - name: agent-zipkin-thrift
        port: 5775
        protocol: UDP
        targetPort: 5775
      - name: agent-compact
        port: 6831
        protocol: UDP
        targetPort: 6831
      - name: agent-binary
        port: 6832
        protocol: UDP
        targetPort: 6832
      - name: agent-configs
        port: 5778
        protocol: TCP
        targetPort: 5778
    selector:
      app: cloudmoa-trace-agent
    type: ClusterIP'::text WHERE id = 7::bigint;

UPDATE public.agent_install_file_info SET yaml = '---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cloudmoa-cluster-role
rules:
  - nonResourceURLs:
      - "*"
    verbs:
      - get
  - apiGroups:
      - metrics.k8s.io
    resources:
      - pods
      - nodes
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - ""
    resources:
      - pods
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - ""
    resources:
      - services
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - ""
    resources:
      - nodes/stats
      - endpoints
      - namespaces
      - events
    verbs:
      - get
      - list
      - watch
  - apiGroups:
      - apps
    resources:
      - daemonsets
      - deployments
      - deployments/scale
      - replicasets
      - replicasets/scale
      - statefulsets
      - statefulsets/scale
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - batch
    resources:
      - jobs
    verbs:
      - get
      - list
      - watch
      - update
  - apiGroups:
      - batch
    resources:
      - cronjobs
    verbs:
      - get
      - list
      - update
  - apiGroups:
      - storage.j8s.io
    resources:
      - storageclasses
    verbs:
      - get
      - list
  - apiGroups:
      - networking.k8s.io
    resources:
      - ingresses
    verbs:
      - get
      - list
  - apiGroups:
      - extensions
    resources:
      - ingresses
    verbs:
      - get
      - list
  - apiGroups:
      - policy
    resources:
      - podsecuritypolicies
    verbs:
      - use
    resourceNames:
      - imxc-ps
  - apiGroups:
      - certificates.k8s.io
    resourceNames:
      - kubernetes.io/kube-apiserver-client-kubelet
    resources:
      - signers
    verbs:
      - approve
  - apiGroups:
      - certificates.k8s.io
    resourceNames:
      - kubernetes.io/kubelet-serving
    resources:
      - signers
    verbs:
      - approve
  - apiGroups:
      - ""
    resources:
      - nodes
    verbs:
      - get
      - list
      - watch
      - proxy
  - apiGroups:
      - ""
    resources:
      - nodes/log
      - nodes/metrics
      - nodes/proxy
      - nodes/spec
      - nodes/stats
    verbs:
      - ''*''
  - apiGroups:
      - ''*''
    resources:
      - ''*''
    verbs:
      - get
      - list
      - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: cloudmoa-restricted-rb
  namespace: $CLOUDMOA_NAMESPACE
subjects:
  - kind: ServiceAccount
    name: default
    namespace: $CLOUDMOA_NAMESPACE
roleRef:
  kind: ClusterRole
  name: cloudmoa-cluster-role
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: cloudmoa-psp
  namespace: $CLOUDMOA_NAMESPACE
spec:
  privileged: true
  seLinux:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  runAsUser:
    rule: RunAsAny
  fsGroup:
    rule: RunAsAny
  hostPorts:
    - max: 65535
      min: 0
  hostNetwork: true
  hostPID: true
  volumes:
    - configMap
    - secret
    - emptyDir
    - hostPath
    - projected
    - downwardAPI
    - persistentVolumeClaim
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cloudmoa-topology-agent
  namespace: $CLOUDMOA_NAMESPACE
  labels:
    app: cloudmoa-topology-agent
spec:
  selector:
    matchLabels:
      app: cloudmoa-topology-agent
  template:
    metadata:
      labels:
        app: cloudmoa-topology-agent
    spec:
      hostNetwork: true
      hostPID: true
      tolerations:
      - effect: NoSchedule
        operator: Exists
      - effect: NoExecute
        operator: Exists
      containers:
      - name: cloudmoa-topology-agent
        image: $DOCKER_REGISTRY_URL/topology-agent:$IMAGE_TAG
        resources:
          requests:
            cpu: 200m
            memory: 512Mi
          limits:
            cpu: 500m
            memory: 600Mi
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /host/usr/bin
          name: bin-volume
        - mountPath: /var/run/docker.sock
          name: docker-volume
        - mountPath: /host/proc
          name: proc-volume
        - mountPath: /root
          name: root-volume
        - mountPath: /log
          name: log-volume
        env:
          - name: DATAGATE
            value: $COLLTION_SERVER_DATAGATE_IP:$COLLTION_SERVER_DATAGATE_PORT
          - name: CLUSTER_ID
            value: $CLOUDMOA_CLUSTER_ID
          - name: ROOT_DIRECTORY
            value: /root
          - name: NODE_NAME
            valueFrom:
              fieldRef:
                apiVersion: v1
                fieldPath: spec.nodeName
          - name: POD_ID
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: NAMESPACE
            valueFrom:
              fieldRef:
                fieldPath: metadata.namespace
          - name: LOG_LEVEL
            value: "INFO"
      volumes:
      - name: bin-volume
        hostPath:
          path: /usr/bin
          type: Directory
      - name: docker-volume
        hostPath:
          path: /var/run/docker.sock
      - name: proc-volume
        hostPath:
          path: /proc
      - name: root-volume
        hostPath:
          path: /
      - name: log-volume
        hostPath:
          path: /home'::text WHERE id = 2::bigint;

UPDATE public.agent_install_file_info SET yaml = '---
apiVersion: v1
kind: ConfigMap
metadata:
  name: cloudmoa-metric-agent-config
  namespace: $CLOUDMOA_NAMESPACE
data:
  scaling.rules: |
    groups:
    - name: scaleup
      rules :
      - alert : ScaleUpRule
        expr: job:webapp_config_open_sessions_current_count:sum > 15
        annotations:
          summary: "Scale up when current sessions is greater than 15"
          description: "Firing when total sessions active greater than 15"
  metric-agent.yml: |
    global:
      scrape_interval:     15s

    scrape_configs:
      - job_name: ''kubernetes-kubelet''
        scheme: https
        tls_config:
          ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
        kubernetes_sd_configs:
        - role: node
        relabel_configs:
        - action: labelmap
          regex: __meta_kubernetes_node_label_(.+)
        - target_label: __address__
          replacement: kubernetes.default.svc:443
        - source_labels: [__meta_kubernetes_node_name]
          regex: (.+)
          target_label: __metrics_path__
          replacement: /api/v1/nodes/${1}/proxy/metrics
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: xm_node_id
        - target_label: xm_clst_id
          replacement: ''$CLOUDMOA_CLUSTER_ID''
        - target_label: xm_entity_type
          replacement: ''Node''
        metric_relabel_configs:
        - source_labels: [ __name__ ]
          regex: (kubelet_running_pod_count)
          action: keep

      - job_name: ''kubernetes-node-exporter''
        tls_config:
          ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
        bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
        kubernetes_sd_configs:
        - role: node

        relabel_configs:
        - action: labelmap
          regex: __meta_kubernetes_node_label_(.+)
        - source_labels: [__meta_kubernetes_role]
          action: replace
          target_label: kubernetes_role
        - source_labels: [__address__]
          regex: ''(.*):10250''
          replacement: ''${1}:9110''
          target_label: __address__
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: __instance__
          # set "name" value to "job"
        - source_labels: [job]
          regex: ''kubernetes-(.*)''
          replacement: ''${1}''
          target_label: name
        - target_label: xm_clst_id
          replacement: ''$CLOUDMOA_CLUSTER_ID''
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: xm_node_id
        - target_label: xm_entity_type
          replacement: ''Node''
        - source_labels: [__meta_kubernetes_namespace]
          separator: ;
          regex: (.*)
          target_label: xm_namespace
          replacement: $1
          action: replace
        metric_relabel_configs:
        - source_labels: [ __name__ ]
          regex: (node_boot_time_seconds|node_context_switches_total|node_cpu_frequency_max_hertz|node_cpu_package_throttles_total|node_cpu_seconds_total|node_disk_io_time_seconds_total|node_disk_read_bytes_total|node_disk_read_time_seconds_total|node_disk_reads_completed_total|node_disk_write_time_seconds_total|node_disk_writes_completed_total|node_disk_written_bytes_total|node_filefd_allocated|node_filesystem_avail_bytes|node_filesystem_free_bytes|node_filesystem_size_bytes|node_load1|node_load15|node_load5|node_memory_Active_bytes|node_memory_Buffers_bytes|node_memory_Cached_bytes|node_memory_MemAvailable_bytes|node_memory_MemFree_bytes|node_memory_MemTotal_bytes|node_memory_SwapCached_bytes|node_memory_SwapFree_bytes|node_memory_SwapTotal_bytes|node_network_receive_bytes_total|node_network_receive_bytes_total|node_network_transmit_bytes_total|node_network_transmit_bytes_total)
          action: keep

      - job_name: ''kubernetes-cadvisor''
        scheme: https
        tls_config:
          ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
          insecure_skip_verify: true
        bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token

        kubernetes_sd_configs:
        - role: node
        metrics_path: /metrics/cadvisor

        relabel_configs:
        - action: labelmap
          regex: __meta_kubernetes_node_label_(.+)
        - target_label: xm_clst_id
          replacement: ''$CLOUDMOA_CLUSTER_ID''
        - source_labels: [__meta_kubernetes_node_label_kubernetes_io_hostname]
          target_label: xm_node_id
        - target_label: xm_entity_type
          replacement: ''Container''

        metric_relabel_configs:
        - source_labels: [namespace]
          target_label: xm_namespace
        - source_labels: [pod]
          target_label: xm_pod_id
        - source_labels: [container]
          target_label: xm_cont_name
        - source_labels: [id]
          target_label: xm_cont_id
        - source_labels: [container]
          regex: (.+)
          action: keep
        - source_labels: [ __name__ ]
          regex: (container_cpu_cfs_throttled_seconds_total|container_cpu_system_seconds_total|container_cpu_usage_seconds_total|container_cpu_user_seconds_total|container_fs_limit_bytes|container_fs_reads_bytes_total|container_fs_usage_bytes|container_fs_writes_bytes_total|container_last_seen|container_memory_cache|container_memory_max_usage_bytes|container_memory_swap|container_memory_usage_bytes|container_memory_working_set_bytes|container_network_receive_bytes_total|container_network_transmit_bytes_total|container_spec_memory_limit_bytes)
          action: keep
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloudmoa-metric-agent
  namespace: $CLOUDMOA_NAMESPACE
  labels:
    app: cloudmoa-metric-agent
spec:
  selector:
    matchLabels:
      app: cloudmoa-metric-agent
  replicas: 1
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: cloudmoa-metric-agent
    spec:
      containers:
        - name: cloudmoa-metric-agent
          image: $DOCKER_REGISTRY_URL/metric-agent:$IMAGE_TAG
          args:
            - --config.file=/etc/metric-agent/metric-agent.yml
          resources:
            requests:
              cpu: 100m
              memory: 512Mi
            limits:
              cpu: 300m
              memory: 1000Mi
          volumeMounts:
            - mountPath: /etc/metric-agent/
              name: config-volume
          env:
            - name: LOG_LEVEL
              value: "INFO"
            - name: LOG_MAXAGE
              value: "1"
            - name: CLUSTER_ID
              value: $CLOUDMOA_CLUSTER_ID
            - name: DATAGATE
              value: $COLLTION_SERVER_DATAGATE_IP:$COLLTION_SERVER_DATAGATE_PORT
            - name: STORAGE_TYPE
              value: datagate
      restartPolicy: Always
      volumes:
        - name: config-volume
          configMap:
            name: cloudmoa-metric-agent-config
'::text WHERE id = 6::bigint;

ALTER TABLE public.alert_rule_config_info ALTER COLUMN config_data TYPE text;

update alert_rule_config_info
set config_data = '\n  - alert: "${ALERT}"\n    expr: "${EXPR}"\n    labels:\n      level: "${LEVEL}"\n    for: "${FOR}"\n    annotations:\n      xm_service_name: "{{ $labels.xm_service_name }}"\n      level: "${LEVEL}"\n      meta_id: "${META_ID}"\n      xm_node_id: "{{ $labels.xm_node_id }}"\n      threshold: ${THRESHOLD}\n      xm_container_id: "{{ $labels.xm_cont_name }}"\n      message: "${MESSAGE}"\n      rule_id: ${RULE_ID}\n      xm_pod_id: "{{ $labels.xm_pod_id }}"\n      xm_clst_id: "{{ $labels.xm_clst_id }}"\n      xm_namespace: "{{ $labels.xm_namespace }}"\n      value: "{{ $value }}"\n      xm_entity_type: "{{ $labels.xm_entity_type }}"\n      alert_entity_type: "${ALERT_ENTITY_TYPE}"'
where config_id = 'rules';

ALTER TABLE public.alert_config_info ALTER COLUMN config_data TYPE text, ALTER COLUMN config_default TYPE text;

insert into public.alert_config_info (config_id, created_date, modified_date, config_data, config_default, in_use) values ('routes', now(), null, '\n  - receiver: ''${ROUTES_RECEIVER}''\n    group_by: [${ROUTES_GROUP_BY}]\n    group_wait: ${ROUTES_GROUP_WAIT}\n    group_interval: ${ROUTES_GROUP_INTERVAL}\n    repeat_interval: ${ROUTES_REPEAT_INTERVAL}\n    match_re:\n      level: ${LEVEL}\n    continue: ${CONTINUE}', '\n  - receiver: ''cdms''\n    group_by: [xm_clst_id, level]\n    group_wait: 5s\n    group_interval: 5s\n    repeat_interval: 1m\n    match_re:\n      level: Critical\n    continue: true', true);