Repository: fission/fission
Pull request #2420 (2022-04-24 14:42:27)

feat: 🎸 add runtime-env flags to the env update cmd
<!--  Thanks for sending a pull request! We request you provide detailed description as much as possible. -->

## Description
<!--- Describe your changes in detail. -->
<!-- Typically try to give details of what, why and how of the PR changes. -->

## Which issue(s) this PR fixes:
<!--
*Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->
Fixes #

## Testing
<!--- Please describe in detail how you tested your changes. -->

## Checklist:
<!-- Please tick following checkboxes as per your understanding. -->
- [ ] I ran tests as well as code linting locally to verify my changes. 
- [x] I have done manual verification of my changes, changes working as expected.
- [ ] I have added new tests to cover my changes.
- [ ] My changes follow contributing guidelines of Fission.
- [ ] I have signed all of my commits.



Patch:
diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml
index a458a595..28547299 100644
--- a/.github/workflows/lint.yaml
+++ b/.github/workflows/lint.yaml
@@ -25,7 +25,7 @@ jobs:
       - name: Set up Go
         uses: actions/setup-go@v2
         with:
-          go-version: 1.18
+          go-version: 1.18.1
 
       - name: Check out code
         uses: actions/checkout@v2
diff --git a/.github/workflows/push_pr.yaml b/.github/workflows/push_pr.yaml
index 8ad6da4f..ce5892e2 100644
--- a/.github/workflows/push_pr.yaml
+++ b/.github/workflows/push_pr.yaml
@@ -34,7 +34,7 @@ jobs:
       - name: setup go
         uses: actions/setup-go@v2
         with:
-          go-version: 1.18
+          go-version: 1.18.1
 
       - name: Checkout sources
         uses: actions/checkout@v2.3.4
@@ -84,7 +84,6 @@ jobs:
         uses: goreleaser/goreleaser-action@v2
         with:
           install-only: true
-          version: 1.7.0
 
       - name: Setup Prometheus Stack
         run: |
@@ -93,18 +92,19 @@ jobs:
           kubectl create ns monitoring
           helm install monitoring prometheus-community/prometheus -n monitoring
 
-      - name: Build and Install Fission
-        run: |
-          kubectl create ns fission
-          make create-crds
-          SKAFFOLD_PROFILE=kind-ci make skaffold-deploy
-
       - name: Build and Install Fission CLI
         run: |
+          make debug-vars
           make build-fission-cli
           sudo make install-fission-cli
           sudo chmod +x /usr/local/bin/fission
 
+      - name: Build and Install Fission
+        run: |
+          kubectl create ns fission
+          make create-crds
+          SKAFFOLD_PROFILE=kind-ci make skaffold-deploy
+
       - name: Port-forward fission components
         run: |
           kubectl port-forward svc/router 8888:80 -nfission &
diff --git a/.mergify.yml b/.mergify.yml
index 52df8870..c7697989 100644
--- a/.mergify.yml
+++ b/.mergify.yml
@@ -15,4 +15,3 @@ pull_request_rules:
     actions:
       merge:
         method: squash
-        commit_message: title+body
diff --git a/Makefile b/Makefile
index edfa0412..240f6262 100644
--- a/Makefile
+++ b/Makefile
@@ -22,6 +22,7 @@ COMMITSHA ?= $(shell git rev-parse HEAD)
 
 GOOS ?= $(shell go env GOOS)
 GOARCH ?= $(shell go env GOARCH)
+GOAMD64 ?= $(shell go env GOAMD64)
 
 FISSION-CLI-SUFFIX :=
 ifeq ($(GOOS), windows)
@@ -32,6 +33,11 @@ endif
 help:
 	@awk '/^#/{c=substr($$0,3);next}c&&/^[[:alpha:]][[:alnum:]_-]+:/{print substr($$1,1,index($$1,":")),c}1{c=0}' $(MAKEFILE_LIST) | column -s: -t
 
+print-%:
+	@echo '$*=$($*)'
+
+debug-vars: print-GOOS print-GOARCH print-GOAMD64 print-VERSION print-TIMESTAMP print-COMMITSHA print-FISSION-CLI-SUFFIX print-SKAFFOLD_PROFILE
+
 ### Static checks
 check: test-run build-fission-cli clean
 
@@ -47,10 +53,11 @@ test-run: code-checks
 
 ### Binaries
 build-fission-cli:
-	@GOOS=$(GOOS) GOARCH=$(GOARCH) GORELEASER_CURRENT_TAG=$(VERSION) goreleaser build --snapshot --rm-dist --single-target --id fission-cli
+	@GOOS=$(GOOS) GOARCH=$(GOARCH) GOAMD64=$(GOAMD64) GORELEASER_CURRENT_TAG=$(VERSION) goreleaser build --snapshot --rm-dist --single-target --id fission-cli
 
 install-fission-cli:
-	mv dist/fission-cli_$(GOOS)_$(GOARCH)/fission$(FISSION-CLI-SUFFIX) /usr/local/bin/fission
+	# TODO: Fix this hack, replace v1 with GOAMD64
+	mv dist/fission-cli_$(GOOS)_$(GOARCH)_v1/fission$(FISSION-CLI-SUFFIX) /usr/local/bin/fission
 
 ### Codegen
 codegen:
@@ -93,11 +100,11 @@ all-generators: codegen generate-crds generate-swagger-doc
 
 skaffold-prebuild:
 	@GOOS=linux GOARCH=amd64 GORELEASER_CURRENT_TAG=$(VERSION) goreleaser build --snapshot --rm-dist --single-target
-	@cp -v cmd/builder/Dockerfile.fission-builder dist/builder_linux_amd64/Dockerfile
-	@cp -v cmd/fetcher/Dockerfile.fission-fetcher dist/fetcher_linux_amd64/Dockerfile
-	@cp -v cmd/fission-bundle/Dockerfile.fission-bundle dist/fission-bundle_linux_amd64/Dockerfile
-	@cp -v cmd/reporter/Dockerfile.reporter dist/reporter_linux_amd64/Dockerfile
-	@cp -v cmd/preupgradechecks/Dockerfile.fission-preupgradechecks dist/pre-upgrade-checks_linux_amd64/Dockerfile
+	@cp -v cmd/builder/Dockerfile.fission-builder dist/builder_linux_amd64_v1/Dockerfile
+	@cp -v cmd/fetcher/Dockerfile.fission-fetcher dist/fetcher_linux_amd64_v1/Dockerfile
+	@cp -v cmd/fission-bundle/Dockerfile.fission-bundle dist/fission-bundle_linux_amd64_v1/Dockerfile
+	@cp -v cmd/reporter/Dockerfile.reporter dist/reporter_linux_amd64_v1/Dockerfile
+	@cp -v cmd/preupgradechecks/Dockerfile.fission-preupgradechecks dist/pre-upgrade-checks_linux_amd64_v1/Dockerfile
 
 skaffold-deploy: skaffold-prebuild
 	skaffold run -p $(SKAFFOLD_PROFILE)
diff --git a/charts/fission-all/templates/controller/servicemonitor.yaml b/charts/fission-all/templates/controller/servicemonitor.yaml
new file mode 100644
index 00000000..e4c68ccf
--- /dev/null
+++ b/charts/fission-all/templates/controller/servicemonitor.yaml
@@ -0,0 +1,18 @@
+{{- if .Values.serviceMonitor.enabled }}
+apiVersion: monitoring.coreos.com/v1
+kind: ServiceMonitor
+metadata:
+  name: controller-monitor
+  {{- if .Values.serviceMonitor.namespace }}
+  namespace: {{ .Values.serviceMonitor.namespace }}
+  {{- end }}
+spec:
+  namespaceSelector:
+    matchNames:
+      - {{ .Release.Namespace }}
+  selector:
+    matchLabels:
+      svc: controller
+  endpoints:
+  - targetPort: 8080
+{{- end -}}
\ No newline at end of file
diff --git a/charts/fission-all/templates/executor/servicemonitor.yaml b/charts/fission-all/templates/executor/servicemonitor.yaml
new file mode 100644
index 00000000..0a9ba668
--- /dev/null
+++ b/charts/fission-all/templates/executor/servicemonitor.yaml
@@ -0,0 +1,18 @@
+{{- if .Values.serviceMonitor.enabled }}
+apiVersion: monitoring.coreos.com/v1
+kind: ServiceMonitor
+metadata:
+  name: executor-monitor
+  {{- if .Values.serviceMonitor.namespace }}
+  namespace: {{ .Values.serviceMonitor.namespace }}
+  {{- end }}
+spec:
+  namespaceSelector:
+    matchNames:
+      - {{ .Release.Namespace }}
+  selector:
+    matchLabels:
+      svc: executor
+  endpoints:
+  - targetPort: 8080
+{{- end -}}
\ No newline at end of file
diff --git a/charts/fission-all/templates/router/servicemonitor.yaml b/charts/fission-all/templates/router/servicemonitor.yaml
new file mode 100644
index 00000000..7f1b4c61
--- /dev/null
+++ b/charts/fission-all/templates/router/servicemonitor.yaml
@@ -0,0 +1,18 @@
+{{- if .Values.serviceMonitor.enabled }}
+apiVersion: monitoring.coreos.com/v1
+kind: ServiceMonitor
+metadata:
+  name: router-monitor
+  {{- if .Values.serviceMonitor.namespace }}
+  namespace: {{ .Values.serviceMonitor.namespace }}
+  {{- end }}
+spec:
+  namespaceSelector:
+    matchNames:
+      - {{ .Release.Namespace }}
+  selector:
+    matchLabels:
+      svc: router
+  endpoints:
+  - targetPort: 8080
+{{- end -}}
\ No newline at end of file
diff --git a/charts/fission-all/templates/storagesvc/servicemonitor.yaml b/charts/fission-all/templates/storagesvc/servicemonitor.yaml
new file mode 100644
index 00000000..808f3855
--- /dev/null
+++ b/charts/fission-all/templates/storagesvc/servicemonitor.yaml
@@ -0,0 +1,18 @@
+{{- if .Values.serviceMonitor.enabled }}
+apiVersion: monitoring.coreos.com/v1
+kind: ServiceMonitor
+metadata:
+  name: storagesvc-monitor
+  {{- if .Values.serviceMonitor.namespace }}
+  namespace: {{ .Values.serviceMonitor.namespace }}
+  {{- end }}  
+spec:
+  namespaceSelector:
+    matchNames:
+      - {{ .Release.Namespace }}
+  selector:
+    matchLabels:
+      svc: storagesvc
+  endpoints:
+  - targetPort: 8080
+{{- end -}}
\ No newline at end of file
diff --git a/charts/fission-all/values.yaml b/charts/fission-all/values.yaml
index fd7a9344..83f32329 100644
--- a/charts/fission-all/values.yaml
+++ b/charts/fission-all/values.yaml
@@ -362,6 +362,12 @@ kafka:
   ##
   # version: "0.11.2.0"
 
+serviceMonitor:
+  enabled: false
+  ##namespace in which you want to deploy servicemonitor
+  ##
+  namespace: ""
+
 ## Persist data to a persistent volume.
 ##
 persistence:
diff --git a/crds/v1/fission.io_functions.yaml b/crds/v1/fission.io_functions.yaml
index 97a1ab56..ec540903 100644
--- a/crds/v1/fission.io_functions.yaml
+++ b/crds/v1/fission.io_functions.yaml
@@ -53,8 +53,404 @@ spec:
                         description: This is the timeout setting for executor to wait for pod specialization.
                         type: integer
                       TargetCPUPercent:
-                        description: This is only for newdeploy to set up target CPU utilization of HPA.
+                        description: 'Deprecated: use hpaMetrics instead. This is only for executor type newdeploy and container to set up target CPU utilization of HPA. Applicable for executor type newdeploy and container.'
                         type: integer
+                      hpaBehavior:
+                        description: hpaBehavior is the behavior of HPA when scaling in up/down direction. Applicable for executor type newdeploy and container.
+                        properties:
+                          scaleDown:
+                            description: scaleDown is scaling policy for scaling Down. If not set, the default value is to allow to scale down to minReplicas pods, with a 300 second stabilization window (i.e., the highest recommendation for the last 300sec is used).
+                            properties:
+                              policies:
+                                description: policies is a list of potential scaling polices which can be used during scaling. At least one policy must be specified, otherwise the HPAScalingRules will be discarded as invalid
+                                items:
+                                  description: HPAScalingPolicy is a single policy which must hold true for a specified past interval.
+                                  properties:
+                                    periodSeconds:
+                                      description: PeriodSeconds specifies the window of time for which the policy should hold true. PeriodSeconds must be greater than zero and less than or equal to 1800 (30 min).
+                                      format: int32
+                                      type: integer
+                                    type:
+                                      description: Type is used to specify the scaling policy.
+                                      type: string
+                                    value:
+                                      description: Value contains the amount of change which is permitted by the policy. It must be greater than zero
+                                      format: int32
+                                      type: integer
+                                  required:
+                                  - periodSeconds
+                                  - type
+                                  - value
+                                  type: object
+                                type: array
+                              selectPolicy:
+                                description: selectPolicy is used to specify which policy should be used. If not set, the default value MaxPolicySelect is used.
+                                type: string
+                              stabilizationWindowSeconds:
+                                description: 'StabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long).'
+                                format: int32
+                                type: integer
+                            type: object
+                          scaleUp:
+                            description: 'scaleUp is scaling policy for scaling Up. If not set, the default value is the higher of:   * increase no more than 4 pods per 60 seconds   * double the number of pods per 60 seconds No stabilization is used.'
+                            properties:
+                              policies:
+                                description: policies is a list of potential scaling polices which can be used during scaling. At least one policy must be specified, otherwise the HPAScalingRules will be discarded as invalid
+                                items:
+                                  description: HPAScalingPolicy is a single policy which must hold true for a specified past interval.
+                                  properties:
+                                    periodSeconds:
+                                      description: PeriodSeconds specifies the window of time for which the policy should hold true. PeriodSeconds must be greater than zero and less than or equal to 1800 (30 min).
+                                      format: int32
+                                      type: integer
+                                    type:
+                                      description: Type is used to specify the scaling policy.
+                                      type: string
+                                    value:
+                                      description: Value contains the amount of change which is permitted by the policy. It must be greater than zero
+                                      format: int32
+                                      type: integer
+                                  required:
+                                  - periodSeconds
+                                  - type
+                                  - value
+                                  type: object
+                                type: array
+                              selectPolicy:
+                                description: selectPolicy is used to specify which policy should be used. If not set, the default value MaxPolicySelect is used.
+                                type: string
+                              stabilizationWindowSeconds:
+                                description: 'StabilizationWindowSeconds is the number of seconds for which past recommendations should be considered while scaling up or scaling down. StabilizationWindowSeconds must be greater than or equal to zero and less than or equal to 3600 (one hour). If not set, use the default values: - For scale up: 0 (i.e. no stabilization is done). - For scale down: 300 (i.e. the stabilization window is 300 seconds long).'
+                                format: int32
+                                type: integer
+                            type: object
+                        type: object
+                      hpaMetrics:
+                        description: hpaMetrics is the list of metrics used to determine the desired replica count of the Deployment created for the function. Applicable for executor type newdeploy and container.
+                        items:
+                          description: MetricSpec specifies how to scale based on a single metric (only `type` and one other matching field should be set at once).
+                          properties:
+                            containerResource:
+                              description: container resource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing a single container in each pod of the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the "pods" source. This is an alpha feature and can be enabled by the HPAContainerMetrics feature flag.
+                              properties:
+                                container:
+                                  description: container is the name of the container in the pods of the scaling target
+                                  type: string
+                                name:
+                                  description: name is the name of the resource in question.
+                                  type: string
+                                target:
+                                  description: target specifies the target value for the given metric
+                                  properties:
+                                    averageUtilization:
+                                      description: averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type
+                                      format: int32
+                                      type: integer
+                                    averageValue:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: averageValue is the target value of the average of the metric across all relevant pods (as a quantity)
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                    type:
+                                      description: type represents whether the metric type is Utilization, Value, or AverageValue
+                                      type: string
+                                    value:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: value is the target value of the metric (as a quantity).
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                  required:
+                                  - type
+                                  type: object
+                              required:
+                              - container
+                              - name
+                              - target
+                              type: object
+                            external:
+                              description: external refers to a global metric that is not associated with any Kubernetes object. It allows autoscaling based on information coming from components running outside of cluster (for example length of queue in cloud messaging service, or QPS from loadbalancer running outside of cluster).
+                              properties:
+                                metric:
+                                  description: metric identifies the target metric by name and selector
+                                  properties:
+                                    name:
+                                      description: name is the name of the given metric
+                                      type: string
+                                    selector:
+                                      description: selector is the string-encoded form of a standard kubernetes label selector for the given metric When set, it is passed as an additional parameter to the metrics server for more specific metrics scoping. When unset, just the metricName will be used to gather metrics.
+                                      properties:
+                                        matchExpressions:
+                                          description: matchExpressions is a list of label selector requirements. The requirements are ANDed.
+                                          items:
+                                            description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.
+                                            properties:
+                                              key:
+                                                description: key is the label key that the selector applies to.
+                                                type: string
+                                              operator:
+                                                description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.
+                                                type: string
+                                              values:
+                                                description: values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.
+                                                items:
+                                                  type: string
+                                                type: array
+                                            required:
+                                            - key
+                                            - operator
+                                            type: object
+                                          type: array
+                                        matchLabels:
+                                          additionalProperties:
+                                            type: string
+                                          description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed.
+                                          type: object
+                                      type: object
+                                  required:
+                                  - name
+                                  type: object
+                                target:
+                                  description: target specifies the target value for the given metric
+                                  properties:
+                                    averageUtilization:
+                                      description: averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type
+                                      format: int32
+                                      type: integer
+                                    averageValue:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: averageValue is the target value of the average of the metric across all relevant pods (as a quantity)
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                    type:
+                                      description: type represents whether the metric type is Utilization, Value, or AverageValue
+                                      type: string
+                                    value:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: value is the target value of the metric (as a quantity).
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                  required:
+                                  - type
+                                  type: object
+                              required:
+                              - metric
+                              - target
+                              type: object
+                            object:
+                              description: object refers to a metric describing a single kubernetes object (for example, hits-per-second on an Ingress object).
+                              properties:
+                                describedObject:
+                                  description: CrossVersionObjectReference contains enough information to let you identify the referred resource.
+                                  properties:
+                                    apiVersion:
+                                      description: API version of the referent
+                                      type: string
+                                    kind:
+                                      description: 'Kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds"'
+                                      type: string
+                                    name:
+                                      description: 'Name of the referent; More info: http://kubernetes.io/docs/user-guide/identifiers#names'
+                                      type: string
+                                  required:
+                                  - kind
+                                  - name
+                                  type: object
+                                metric:
+                                  description: metric identifies the target metric by name and selector
+                                  properties:
+                                    name:
+                                      description: name is the name of the given metric
+                                      type: string
+                                    selector:
+                                      description: selector is the string-encoded form of a standard kubernetes label selector for the given metric When set, it is passed as an additional parameter to the metrics server for more specific metrics scoping. When unset, just the metricName will be used to gather metrics.
+                                      properties:
+                                        matchExpressions:
+                                          description: matchExpressions is a list of label selector requirements. The requirements are ANDed.
+                                          items:
+                                            description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.
+                                            properties:
+                                              key:
+                                                description: key is the label key that the selector applies to.
+                                                type: string
+                                              operator:
+                                                description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.
+                                                type: string
+                                              values:
+                                                description: values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.
+                                                items:
+                                                  type: string
+                                                type: array
+                                            required:
+                                            - key
+                                            - operator
+                                            type: object
+                                          type: array
+                                        matchLabels:
+                                          additionalProperties:
+                                            type: string
+                                          description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed.
+                                          type: object
+                                      type: object
+                                  required:
+                                  - name
+                                  type: object
+                                target:
+                                  description: target specifies the target value for the given metric
+                                  properties:
+                                    averageUtilization:
+                                      description: averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type
+                                      format: int32
+                                      type: integer
+                                    averageValue:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: averageValue is the target value of the average of the metric across all relevant pods (as a quantity)
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                    type:
+                                      description: type represents whether the metric type is Utilization, Value, or AverageValue
+                                      type: string
+                                    value:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: value is the target value of the metric (as a quantity).
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                  required:
+                                  - type
+                                  type: object
+                              required:
+                              - describedObject
+                              - metric
+                              - target
+                              type: object
+                            pods:
+                              description: pods refers to a metric describing each pod in the current scale target (for example, transactions-processed-per-second).  The values will be averaged together before being compared to the target value.
+                              properties:
+                                metric:
+                                  description: metric identifies the target metric by name and selector
+                                  properties:
+                                    name:
+                                      description: name is the name of the given metric
+                                      type: string
+                                    selector:
+                                      description: selector is the string-encoded form of a standard kubernetes label selector for the given metric When set, it is passed as an additional parameter to the metrics server for more specific metrics scoping. When unset, just the metricName will be used to gather metrics.
+                                      properties:
+                                        matchExpressions:
+                                          description: matchExpressions is a list of label selector requirements. The requirements are ANDed.
+                                          items:
+                                            description: A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values.
+                                            properties:
+                                              key:
+                                                description: key is the label key that the selector applies to.
+                                                type: string
+                                              operator:
+                                                description: operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.
+                                                type: string
+                                              values:
+                                                description: values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.
+                                                items:
+                                                  type: string
+                                                type: array
+                                            required:
+                                            - key
+                                            - operator
+                                            type: object
+                                          type: array
+                                        matchLabels:
+                                          additionalProperties:
+                                            type: string
+                                          description: matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is "key", the operator is "In", and the values array contains only "value". The requirements are ANDed.
+                                          type: object
+                                      type: object
+                                  required:
+                                  - name
+                                  type: object
+                                target:
+                                  description: target specifies the target value for the given metric
+                                  properties:
+                                    averageUtilization:
+                                      description: averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type
+                                      format: int32
+                                      type: integer
+                                    averageValue:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: averageValue is the target value of the average of the metric across all relevant pods (as a quantity)
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                    type:
+                                      description: type represents whether the metric type is Utilization, Value, or AverageValue
+                                      type: string
+                                    value:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: value is the target value of the metric (as a quantity).
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                  required:
+                                  - type
+                                  type: object
+                              required:
+                              - metric
+                              - target
+                              type: object
+                            resource:
+                              description: resource refers to a resource metric (such as those specified in requests and limits) known to Kubernetes describing each pod in the current scale target (e.g. CPU or memory). Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the "pods" source.
+                              properties:
+                                name:
+                                  description: name is the name of the resource in question.
+                                  type: string
+                                target:
+                                  description: target specifies the target value for the given metric
+                                  properties:
+                                    averageUtilization:
+                                      description: averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type
+                                      format: int32
+                                      type: integer
+                                    averageValue:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: averageValue is the target value of the average of the metric across all relevant pods (as a quantity)
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                    type:
+                                      description: type represents whether the metric type is Utilization, Value, or AverageValue
+                                      type: string
+                                    value:
+                                      anyOf:
+                                      - type: integer
+                                      - type: string
+                                      description: value is the target value of the metric (as a quantity).
+                                      pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$
+                                      x-kubernetes-int-or-string: true
+                                  required:
+                                  - type
+                                  type: object
+                              required:
+                              - name
+                              - target
+                              type: object
+                            type:
+                              description: 'type is the type of metric source.  It should be one of "ContainerResource", "External", "Object", "Pods" or "Resource", each mapping to a matching field in the object. Note: "ContainerResource" type is available on when the feature-gate HPAContainerMetrics is enabled'
+                              type: string
+                          required:
+                          - type
+                          type: object
+                        type: array
                     type: object
                   StrategyType:
                     description: StrategyType is the strategy type of function. Now it only supports 'execution'.
diff --git a/pkg/apis/core/v1/types.go b/pkg/apis/core/v1/types.go
index 99fdbe7e..1f01b898 100644
--- a/pkg/apis/core/v1/types.go
+++ b/pkg/apis/core/v1/types.go
@@ -17,6 +17,7 @@ limitations under the License.
 package v1
 
 import (
+	asv2beta2 "k8s.io/api/autoscaling/v2beta2"
 	apiv1 "k8s.io/api/core/v1"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/apimachinery/pkg/runtime/schema"
@@ -459,22 +460,36 @@ type (
 		// +optional
 		ExecutorType ExecutorType `json:"ExecutorType"`
 
-		// +optional
 		// This is only for newdeploy to set up minimum replicas of deployment.
+		// +optional
 		MinScale int `json:"MinScale"`
 
-		// +optional
 		// This is only for newdeploy to set up maximum replicas of deployment.
+		// +optional
 		MaxScale int `json:"MaxScale"`
 
+		// Deprecated: use hpaMetrics instead.
+		// This is only for executor type newdeploy and container to set up target CPU utilization of HPA.
+		// Applicable for executor type newdeploy and container.
 		// +optional
-		// This is only for newdeploy to set up target CPU utilization of HPA.
 		TargetCPUPercent int `json:"TargetCPUPercent"`
 
-		// +optional
 		// This is the timeout setting for executor to wait for pod specialization.
+		// +optional
 		SpecializationTimeout int `json:"SpecializationTimeout"`
+
+		// hpaMetrics is the list of metrics used to determine the desired replica count of the Deployment
+		// created for the function.
+		// Applicable for executor type newdeploy and container.
+		// +optional
+		Metrics []asv2beta2.MetricSpec `json:"hpaMetrics,omitempty"`
+
+		// hpaBehavior is the behavior of HPA when scaling in up/down direction.
+		// Applicable for executor type newdeploy and container.
+		// +optional
+		Behavior *asv2beta2.HorizontalPodAutoscalerBehavior `json:"hpaBehavior,omitempty"`
 	}
+
 	// FunctionReferenceType refers to type of Function
 	FunctionReferenceType string
 
diff --git a/pkg/apis/core/v1/validation.go b/pkg/apis/core/v1/validation.go
index 6de27292..6798f214 100644
--- a/pkg/apis/core/v1/validation.go
+++ b/pkg/apis/core/v1/validation.go
@@ -20,6 +20,7 @@ import (
 	"errors"
 	"fmt"
 	"net/http"
+	"reflect"
 	"regexp"
 	"strings"
 
@@ -270,7 +271,7 @@ func (spec FunctionSpec) Validate() error {
 		result = multierror.Append(result, c.Validate())
 	}
 
-	if spec.InvokeStrategy != (InvokeStrategy{}) {
+	if !reflect.DeepEqual(spec.InvokeStrategy, InvokeStrategy{}) {
 		result = multierror.Append(result, spec.InvokeStrategy.Validate())
 	}
 
@@ -309,7 +310,7 @@ func (es ExecutionStrategy) Validate() error {
 		result = multierror.Append(result, MakeValidationErr(ErrorUnsupportedType, "ExecutionStrategy.ExecutorType", es.ExecutorType, "not a valid executor type"))
 	}
 
-	if es.ExecutorType == ExecutorTypeNewdeploy {
+	if es.ExecutorType == ExecutorTypeNewdeploy || es.ExecutorType == ExecutorTypeContainer {
 		if es.MinScale < 0 {
 			result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "ExecutionStrategy.MinScale", es.MinScale, "minimum scale must be greater than or equal to 0"))
 		}
@@ -322,7 +323,7 @@ func (es ExecutionStrategy) Validate() error {
 			result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "ExecutionStrategy.MaxScale", es.MaxScale, "maximum scale must be greater than or equal to minimum scale"))
 		}
 
-		if es.TargetCPUPercent <= 0 || es.TargetCPUPercent > 100 {
+		if es.TargetCPUPercent < 0 || es.TargetCPUPercent > 100 {
 			result = multierror.Append(result, MakeValidationErr(ErrorInvalidValue, "ExecutionStrategy.TargetCPUPercent", es.TargetCPUPercent, "TargetCPUPercent must be a value between 1 - 100"))
 		}
 
diff --git a/pkg/apis/core/v1/zz_generated.deepcopy.go b/pkg/apis/core/v1/zz_generated.deepcopy.go
index fe03e18e..7651a349 100644
--- a/pkg/apis/core/v1/zz_generated.deepcopy.go
+++ b/pkg/apis/core/v1/zz_generated.deepcopy.go
@@ -22,6 +22,7 @@ limitations under the License.
 package v1
 
 import (
+	v2beta2 "k8s.io/api/autoscaling/v2beta2"
 	corev1 "k8s.io/api/core/v1"
 	runtime "k8s.io/apimachinery/pkg/runtime"
 )
@@ -313,6 +314,18 @@ func (in *EnvironmentSpec) DeepCopy() *EnvironmentSpec {
 // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
 func (in *ExecutionStrategy) DeepCopyInto(out *ExecutionStrategy) {
 	*out = *in
+	if in.Metrics != nil {
+		in, out := &in.Metrics, &out.Metrics
+		*out = make([]v2beta2.MetricSpec, len(*in))
+		for i := range *in {
+			(*in)[i].DeepCopyInto(&(*out)[i])
+		}
+	}
+	if in.Behavior != nil {
+		in, out := &in.Behavior, &out.Behavior
+		*out = new(v2beta2.HorizontalPodAutoscalerBehavior)
+		(*in).DeepCopyInto(*out)
+	}
 	return
 }
 
@@ -442,7 +455,7 @@ func (in *FunctionSpec) DeepCopyInto(out *FunctionSpec) {
 		copy(*out, *in)
 	}
 	in.Resources.DeepCopyInto(&out.Resources)
-	out.InvokeStrategy = in.InvokeStrategy
+	in.InvokeStrategy.DeepCopyInto(&out.InvokeStrategy)
 	if in.IdleTimeout != nil {
 		in, out := &in.IdleTimeout, &out.IdleTimeout
 		*out = new(int)
@@ -580,7 +593,7 @@ func (in *IngressConfig) DeepCopy() *IngressConfig {
 // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
 func (in *InvokeStrategy) DeepCopyInto(out *InvokeStrategy) {
 	*out = *in
-	out.ExecutionStrategy = in.ExecutionStrategy
+	in.ExecutionStrategy.DeepCopyInto(&out.ExecutionStrategy)
 	return
 }
 
diff --git a/pkg/apis/core/v1/zz_generated.swagger_doc_generated.go b/pkg/apis/core/v1/zz_generated.swagger_doc_generated.go
index 7fcc4ad4..cdb0fc9d 100644
--- a/pkg/apis/core/v1/zz_generated.swagger_doc_generated.go
+++ b/pkg/apis/core/v1/zz_generated.swagger_doc_generated.go
@@ -143,8 +143,10 @@ var map_ExecutionStrategy = map[string]string{
 	"ExecutorType":          "ExecutorType is the executor type of function used. Defaults to \"poolmgr\".\n\nAvailable value:\n - poolmgr\n - newdeploy\n - container",
 	"MinScale":              "This is only for newdeploy to set up minimum replicas of deployment.",
 	"MaxScale":              "This is only for newdeploy to set up maximum replicas of deployment.",
-	"TargetCPUPercent":      "This is only for newdeploy to set up target CPU utilization of HPA.",
+	"TargetCPUPercent":      "Deprecated: use hpaMetrics instead. This is only for executor type newdeploy and container to set up target CPU utilization of HPA. Applicable for executor type newdeploy and container.",
 	"SpecializationTimeout": "This is the timeout setting for executor to wait for pod specialization.",
+	"hpaMetrics":            "hpaMetrics is the list of metrics used to determine the desired replica count of the Deployment created for the function. Applicable for executor type newdeploy and container.",
+	"hpaBehavior":           "hpaBehavior is the behavior of HPA when scaling in up/down direction. Applicable for executor type newdeploy and container.",
 }
 
 func (ExecutionStrategy) SwaggerDoc() map[string]string {
diff --git a/pkg/executor/executortype/container/common.go b/pkg/executor/executortype/container/common.go
index d5dfa0ea..8a79e26a 100644
--- a/pkg/executor/executortype/container/common.go
+++ b/pkg/executor/executortype/container/common.go
@@ -77,7 +77,7 @@ func (cn *Container) cleanupContainer(ctx context.Context, ns string, name strin
 		result = multierror.Append(result, err)
 	}
 
-	err = cn.deleteHpa(ctx, ns, name)
+	err = cn.hpaops.DeleteHpa(ctx, ns, name)
 	if err != nil && !k8s_err.IsNotFound(err) {
 		cn.logger.Error("error deleting HPA for Container function",
 			zap.Error(err),
diff --git a/pkg/executor/executortype/container/containermgr.go b/pkg/executor/executortype/container/containermgr.go
index 4c507cb2..bd0e7d89 100644
--- a/pkg/executor/executortype/container/containermgr.go
+++ b/pkg/executor/executortype/container/containermgr.go
@@ -46,6 +46,7 @@ import (
 	"github.com/fission/fission/pkg/executor/fscache"
 	"github.com/fission/fission/pkg/executor/metrics"
 	"github.com/fission/fission/pkg/executor/reaper"
+	hpautils "github.com/fission/fission/pkg/executor/util/hpa"
 	"github.com/fission/fission/pkg/generated/clientset/versioned"
 	finformerv1 "github.com/fission/fission/pkg/generated/informers/externalversions/core/v1"
 	"github.com/fission/fission/pkg/throttler"
@@ -81,6 +82,8 @@ type (
 
 		deplListerSynced k8sCache.InformerSynced
 		svcListerSynced  k8sCache.InformerSynced
+
+		hpaops *hpautils.HpaOperations
 	}
 )
 
@@ -120,6 +123,8 @@ func MakeContainer(
 		useIstio:               enableIstio,
 		// Time is set slightly higher than NewDeploy as cold starts are longer for CaaF
 		defaultIdlePodReapTime: 1 * time.Minute,
+
+		hpaops: hpautils.NewHpaOperations(logger, kubernetesClient, instanceID),
 	}
 	caaf.deplLister = deplInformer.Lister()
 	caaf.deplListerSynced = deplInformer.Informer().HasSynced
@@ -395,7 +400,7 @@ func (caaf *Container) fnCreate(ctx context.Context, fn *fv1.Function) (*fscache
 		return nil, errors.Wrapf(err, "error creating deployment %v", objName)
 	}
 
-	hpa, err := caaf.createOrGetHpa(ctx, objName, &fn.Spec.InvokeStrategy.ExecutionStrategy, depl, deployLabels, deployAnnotations)
+	hpa, err := caaf.hpaops.CreateOrGetHpa(ctx, objName, &fn.Spec.InvokeStrategy.ExecutionStrategy, depl, deployLabels, deployAnnotations)
 	if err != nil {
 		caaf.logger.Error("error creating HPA", zap.Error(err), zap.String("hpa", objName))
 		go cleanupFunc(ns, objName)
@@ -484,8 +489,7 @@ func (caaf *Container) updateFunction(ctx context.Context, oldFn *fv1.Function,
 		return err
 	}
 
-	if oldFn.Spec.InvokeStrategy != newFn.Spec.InvokeStrategy {
-
+	if !reflect.DeepEqual(oldFn.Spec.InvokeStrategy, newFn.Spec.InvokeStrategy) {
 		// to support backward compatibility, if the function was created in default ns, we fall back to creating the
 		// deployment of the function in fission-function ns, so cleaning up resources there
 		ns := caaf.namespace
@@ -499,7 +503,7 @@ func (caaf *Container) updateFunction(ctx context.Context, oldFn *fv1.Function,
 			return err
 		}
 
-		hpa, err := caaf.getHpa(ctx, ns, fsvc.Name)
+		hpa, err := caaf.hpaops.GetHpa(ctx, ns, fsvc.Name)
 		if err != nil {
 			caaf.updateStatus(oldFn, err, "error getting HPA while updating function")
 			return err
@@ -518,14 +522,18 @@ func (caaf *Container) updateFunction(ctx context.Context, oldFn *fv1.Function,
 			hpaChanged = true
 		}
 
-		if newFn.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent != oldFn.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent {
-			targetCpupercent := int32(newFn.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent)
-			hpa.Spec.TargetCPUUtilizationPercentage = &targetCpupercent
+		if !reflect.DeepEqual(newFn.Spec.InvokeStrategy.ExecutionStrategy.Metrics, oldFn.Spec.InvokeStrategy.ExecutionStrategy.Metrics) {
+			hpa.Spec.Metrics = newFn.Spec.InvokeStrategy.ExecutionStrategy.Metrics
+			hpaChanged = true
+		}
+
+		if !reflect.DeepEqual(newFn.Spec.InvokeStrategy.ExecutionStrategy.Behavior, oldFn.Spec.InvokeStrategy.ExecutionStrategy.Behavior) {
+			hpa.Spec.Behavior = newFn.Spec.InvokeStrategy.ExecutionStrategy.Behavior
 			hpaChanged = true
 		}
 
 		if hpaChanged {
-			err := caaf.updateHpa(ctx, hpa)
+			err := caaf.hpaops.UpdateHpa(ctx, hpa)
 			if err != nil {
 				caaf.updateStatus(oldFn, err, "error updating HPA while updating function")
 				return err
diff --git a/pkg/executor/executortype/container/hpa.go b/pkg/executor/executortype/container/hpa.go
deleted file mode 100644
index 9be8763d..00000000
--- a/pkg/executor/executortype/container/hpa.go
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
-Copyright 2020 The Fission Authors.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
-    http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package container
-
-import (
-	"context"
-
-	"github.com/pkg/errors"
-	"go.uber.org/zap"
-	appsv1 "k8s.io/api/apps/v1"
-	asv1 "k8s.io/api/autoscaling/v1"
-	k8s_err "k8s.io/apimachinery/pkg/api/errors"
-	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
-
-	fv1 "github.com/fission/fission/pkg/apis/core/v1"
-	otelUtils "github.com/fission/fission/pkg/utils/otel"
-)
-
-const (
-	DeploymentKind    = "Deployment"
-	DeploymentVersion = "apps/v1"
-)
-
-func (cn *Container) createOrGetHpa(ctx context.Context, hpaName string, execStrategy *fv1.ExecutionStrategy,
-	depl *appsv1.Deployment, deployLabels map[string]string, deployAnnotations map[string]string) (*asv1.HorizontalPodAutoscaler, error) {
-
-	if depl == nil {
-		return nil, errors.New("failed to create HPA, found empty deployment")
-	}
-
-	logger := otelUtils.LoggerWithTraceID(ctx, cn.logger)
-	minRepl := int32(execStrategy.MinScale)
-	if minRepl == 0 {
-		minRepl = 1
-	}
-	maxRepl := int32(execStrategy.MaxScale)
-	if maxRepl == 0 {
-		maxRepl = minRepl
-	}
-	targetCPU := int32(execStrategy.TargetCPUPercent)
-
-	hpa := &asv1.HorizontalPodAutoscaler{
-		ObjectMeta: metav1.ObjectMeta{
-			Name:        hpaName,
-			Labels:      deployLabels,
-			Annotations: deployAnnotations,
-		},
-		Spec: asv1.HorizontalPodAutoscalerSpec{
-			ScaleTargetRef: asv1.CrossVersionObjectReference{
-				Kind:       DeploymentKind,
-				Name:       depl.ObjectMeta.Name,
-				APIVersion: DeploymentVersion,
-			},
-			MinReplicas:                    &minRepl,
-			MaxReplicas:                    maxRepl,
-			TargetCPUUtilizationPercentage: &targetCPU,
-		},
-	}
-
-	existingHpa, err := cn.getHpa(ctx, depl.ObjectMeta.Namespace, hpaName)
-	if err == nil {
-		// to adopt orphan service
-		if existingHpa.Annotations[fv1.EXECUTOR_INSTANCEID_LABEL] != cn.instanceID {
-			existingHpa.Annotations = hpa.Annotations
-			existingHpa.Labels = hpa.Labels
-			existingHpa.Spec = hpa.Spec
-			existingHpa, err = cn.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Update(ctx, existingHpa, metav1.UpdateOptions{})
-			if err != nil {
-				logger.Warn("error adopting HPA", zap.Error(err),
-					zap.String("HPA", hpaName), zap.String("ns", depl.ObjectMeta.Namespace))
-				return nil, err
-			}
-		}
-		return existingHpa, err
-	} else if k8s_err.IsNotFound(err) {
-		cHpa, err := cn.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Create(ctx, hpa, metav1.CreateOptions{})
-		if err != nil {
-			if k8s_err.IsAlreadyExists(err) {
-				cHpa, err = cn.getHpa(ctx, depl.ObjectMeta.Namespace, hpaName)
-			}
-			if err != nil {
-				return nil, err
-			}
-		}
-		otelUtils.SpanTrackEvent(ctx, "hpaCreated", otelUtils.GetAttributesForHPA(cHpa)...)
-		return cHpa, nil
-	}
-	return nil, err
-}
-
-func (cn *Container) getHpa(ctx context.Context, ns, name string) (*asv1.HorizontalPodAutoscaler, error) {
-	return cn.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(ns).Get(ctx, name, metav1.GetOptions{})
-}
-
-func (cn *Container) updateHpa(ctx context.Context, hpa *asv1.HorizontalPodAutoscaler) error {
-	_, err := cn.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(hpa.ObjectMeta.Namespace).Update(ctx, hpa, metav1.UpdateOptions{})
-	return err
-}
-
-func (cn *Container) deleteHpa(ctx context.Context, ns string, name string) error {
-	return cn.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(ns).Delete(ctx, name, metav1.DeleteOptions{})
-}
diff --git a/pkg/executor/executortype/newdeploy/newdeploy.go b/pkg/executor/executortype/newdeploy/newdeploy.go
index 2c269831..56cd7f50 100644
--- a/pkg/executor/executortype/newdeploy/newdeploy.go
+++ b/pkg/executor/executortype/newdeploy/newdeploy.go
@@ -23,10 +23,8 @@ import (
 	"time"
 
 	multierror "github.com/hashicorp/go-multierror"
-	"github.com/pkg/errors"
 	"go.uber.org/zap"
 	appsv1 "k8s.io/api/apps/v1"
-	asv1 "k8s.io/api/autoscaling/v1"
 	apiv1 "k8s.io/api/core/v1"
 	k8s_err "k8s.io/apimachinery/pkg/api/errors"
 	"k8s.io/apimachinery/pkg/api/resource"
@@ -40,12 +38,6 @@ import (
 	otelUtils "github.com/fission/fission/pkg/utils/otel"
 )
 
-// Deployment Constants
-const (
-	DeploymentKind    = "Deployment"
-	DeploymentVersion = "apps/v1"
-)
-
 func (deploy *NewDeploy) createOrGetDeployment(ctx context.Context, fn *fv1.Function, env *fv1.Environment,
 	deployName string, deployLabels map[string]string, deployAnnotations map[string]string, deployNamespace string) (*appsv1.Deployment, error) {
 
@@ -367,86 +359,6 @@ func (deploy *NewDeploy) getResources(env *fv1.Environment, fn *fv1.Function) ap
 	return resources
 }
 
-func (deploy *NewDeploy) createOrGetHpa(ctx context.Context, hpaName string, execStrategy *fv1.ExecutionStrategy,
-	depl *appsv1.Deployment, deployLabels map[string]string, deployAnnotations map[string]string) (*asv1.HorizontalPodAutoscaler, error) {
-
-	if depl == nil {
-		return nil, errors.New("failed to create HPA, found empty deployment")
-	}
-	logger := otelUtils.LoggerWithTraceID(ctx, deploy.logger)
-
-	minRepl := int32(execStrategy.MinScale)
-	if minRepl == 0 {
-		minRepl = 1
-	}
-	maxRepl := int32(execStrategy.MaxScale)
-	if maxRepl == 0 {
-		maxRepl = minRepl
-	}
-	targetCPU := int32(execStrategy.TargetCPUPercent)
-
-	hpa := &asv1.HorizontalPodAutoscaler{
-		ObjectMeta: metav1.ObjectMeta{
-			Name:        hpaName,
-			Labels:      deployLabels,
-			Annotations: deployAnnotations,
-		},
-		Spec: asv1.HorizontalPodAutoscalerSpec{
-			ScaleTargetRef: asv1.CrossVersionObjectReference{
-				Kind:       DeploymentKind,
-				Name:       depl.ObjectMeta.Name,
-				APIVersion: DeploymentVersion,
-			},
-			MinReplicas:                    &minRepl,
-			MaxReplicas:                    maxRepl,
-			TargetCPUUtilizationPercentage: &targetCPU,
-		},
-	}
-
-	existingHpa, err := deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Get(ctx, hpaName, metav1.GetOptions{})
-	if err == nil {
-		// to adopt orphan service
-		if existingHpa.Annotations[fv1.EXECUTOR_INSTANCEID_LABEL] != deploy.instanceID {
-			existingHpa.Annotations = hpa.Annotations
-			existingHpa.Labels = hpa.Labels
-			existingHpa.Spec = hpa.Spec
-			existingHpa, err = deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Update(ctx, existingHpa, metav1.UpdateOptions{})
-			if err != nil {
-				logger.Warn("error adopting HPA", zap.Error(err),
-					zap.String("HPA", hpaName), zap.String("ns", depl.ObjectMeta.Namespace))
-				return nil, err
-			}
-		}
-		return existingHpa, err
-	} else if k8s_err.IsNotFound(err) {
-		cHpa, err := deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Create(ctx, hpa, metav1.CreateOptions{})
-		if err != nil {
-			if k8s_err.IsAlreadyExists(err) {
-				cHpa, err = deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Get(ctx, hpaName, metav1.GetOptions{})
-			}
-			if err != nil {
-				return nil, err
-			}
-		}
-		otelUtils.SpanTrackEvent(ctx, "createdService", otelUtils.GetAttributesForHPA(cHpa)...)
-		return cHpa, nil
-	}
-	return nil, err
-}
-
-func (deploy *NewDeploy) getHpa(ctx context.Context, ns, name string) (*asv1.HorizontalPodAutoscaler, error) {
-	return deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(ns).Get(ctx, name, metav1.GetOptions{})
-}
-
-func (deploy *NewDeploy) updateHpa(ctx context.Context, hpa *asv1.HorizontalPodAutoscaler) error {
-	_, err := deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(hpa.ObjectMeta.Namespace).Update(ctx, hpa, metav1.UpdateOptions{})
-	return err
-}
-
-func (deploy *NewDeploy) deleteHpa(ctx context.Context, ns string, name string) error {
-	return deploy.kubernetesClient.AutoscalingV1().HorizontalPodAutoscalers(ns).Delete(ctx, name, metav1.DeleteOptions{})
-}
-
 func (deploy *NewDeploy) createOrGetSvc(ctx context.Context, deployLabels map[string]string, deployAnnotations map[string]string, svcName string, svcNamespace string) (*apiv1.Service, error) {
 	logger := otelUtils.LoggerWithTraceID(ctx, deploy.logger)
 	service := &apiv1.Service{
@@ -554,7 +466,7 @@ func (deploy *NewDeploy) cleanupNewdeploy(ctx context.Context, ns string, name s
 		result = multierror.Append(result, err)
 	}
 
-	err = deploy.deleteHpa(ctx, ns, name)
+	err = deploy.hpaops.DeleteHpa(ctx, ns, name)
 	if err != nil && !k8s_err.IsNotFound(err) {
 		deploy.logger.Error("error deleting HPA for newdeploy function",
 			zap.Error(err),
diff --git a/pkg/executor/executortype/newdeploy/newdeploymgr.go b/pkg/executor/executortype/newdeploy/newdeploymgr.go
index 5308b9ca..349fe1c1 100644
--- a/pkg/executor/executortype/newdeploy/newdeploymgr.go
+++ b/pkg/executor/executortype/newdeploy/newdeploymgr.go
@@ -20,6 +20,7 @@ import (
 	"context"
 	"fmt"
 	"os"
+	"reflect"
 	"strconv"
 	"strings"
 	"sync"
@@ -46,6 +47,7 @@ import (
 	"github.com/fission/fission/pkg/executor/fscache"
 	"github.com/fission/fission/pkg/executor/metrics"
 	"github.com/fission/fission/pkg/executor/reaper"
+	hpautils "github.com/fission/fission/pkg/executor/util/hpa"
 	fetcherConfig "github.com/fission/fission/pkg/fetcher/config"
 	"github.com/fission/fission/pkg/generated/clientset/versioned"
 	finformerv1 "github.com/fission/fission/pkg/generated/informers/externalversions/core/v1"
@@ -82,6 +84,8 @@ type (
 
 		deplListerSynced k8sCache.InformerSynced
 		svcListerSynced  k8sCache.InformerSynced
+
+		hpaops *hpautils.HpaOperations
 	}
 )
 
@@ -123,6 +127,8 @@ func MakeNewDeploy(
 		useIstio:               enableIstio,
 
 		defaultIdlePodReapTime: 2 * time.Minute,
+
+		hpaops: hpautils.NewHpaOperations(logger, kubernetesClient, instanceID),
 	}
 
 	nd.deplLister = deplInformer.Lister()
@@ -434,7 +440,7 @@ func (deploy *NewDeploy) fnCreate(ctx context.Context, fn *fv1.Function) (*fscac
 		return nil, errors.Wrapf(err, "error creating deployment %v", objName)
 	}
 
-	hpa, err := deploy.createOrGetHpa(ctx, objName, &fn.Spec.InvokeStrategy.ExecutionStrategy, depl, deployLabels, deployAnnotations)
+	hpa, err := deploy.hpaops.CreateOrGetHpa(ctx, objName, &fn.Spec.InvokeStrategy.ExecutionStrategy, depl, deployLabels, deployAnnotations)
 	if err != nil {
 		deploy.logger.Error("error creating HPA", zap.Error(err), zap.String("hpa", objName))
 		go cleanupFunc(ns, objName)
@@ -526,7 +532,7 @@ func (deploy *NewDeploy) updateFunction(ctx context.Context, oldFn *fv1.Function
 
 	deployChanged := false
 
-	if oldFn.Spec.InvokeStrategy != newFn.Spec.InvokeStrategy {
+	if !reflect.DeepEqual(oldFn.Spec.InvokeStrategy, newFn.Spec.InvokeStrategy) {
 
 		// to support backward compatibility, if the function was created in default ns, we fall back to creating the
 		// deployment of the function in fission-function ns, so cleaning up resources there
@@ -541,7 +547,7 @@ func (deploy *NewDeploy) updateFunction(ctx context.Context, oldFn *fv1.Function
 			return err
 		}
 
-		hpa, err := deploy.getHpa(ctx, ns, fsvc.Name)
+		hpa, err := deploy.hpaops.GetHpa(ctx, ns, fsvc.Name)
 		if err != nil {
 			deploy.updateStatus(oldFn, err, "error getting HPA while updating function")
 			return err
@@ -560,14 +566,18 @@ func (deploy *NewDeploy) updateFunction(ctx context.Context, oldFn *fv1.Function
 			hpaChanged = true
 		}
 
-		if newFn.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent != oldFn.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent {
-			targetCpupercent := int32(newFn.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent)
-			hpa.Spec.TargetCPUUtilizationPercentage = &targetCpupercent
+		if !reflect.DeepEqual(newFn.Spec.InvokeStrategy.ExecutionStrategy.Metrics, oldFn.Spec.InvokeStrategy.ExecutionStrategy.Metrics) {
+			hpa.Spec.Metrics = newFn.Spec.InvokeStrategy.ExecutionStrategy.Metrics
+			hpaChanged = true
+		}
+
+		if !reflect.DeepEqual(newFn.Spec.InvokeStrategy.ExecutionStrategy.Behavior, oldFn.Spec.InvokeStrategy.ExecutionStrategy.Behavior) {
+			hpa.Spec.Behavior = newFn.Spec.InvokeStrategy.ExecutionStrategy.Behavior
 			hpaChanged = true
 		}
 
 		if hpaChanged {
-			err := deploy.updateHpa(ctx, hpa)
+			err := deploy.hpaops.UpdateHpa(ctx, hpa)
 			if err != nil {
 				deploy.updateStatus(oldFn, err, "error updating HPA while updating function")
 				return err
diff --git a/pkg/executor/reaper/reaper.go b/pkg/executor/reaper/reaper.go
index da828783..2c028e0c 100644
--- a/pkg/executor/reaper/reaper.go
+++ b/pkg/executor/reaper/reaper.go
@@ -23,7 +23,7 @@ import (
 
 	"go.uber.org/zap"
 	apiv1 "k8s.io/api/core/v1"
-	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/client-go/kubernetes"
 
 	fv1 "github.com/fission/fission/pkg/apis/core/v1"
@@ -32,21 +32,21 @@ import (
 )
 
 var (
-	deletePropagation = meta_v1.DeletePropagationBackground
-	delOpt            = meta_v1.DeleteOptions{PropagationPolicy: &deletePropagation}
+	deletePropagation = metav1.DeletePropagationBackground
+	delOpt            = metav1.DeleteOptions{PropagationPolicy: &deletePropagation}
 )
 
 // CleanupKubeObject deletes given kubernetes object
 func CleanupKubeObject(ctx context.Context, logger *zap.Logger, kubeClient kubernetes.Interface, kubeobj *apiv1.ObjectReference) {
 	switch strings.ToLower(kubeobj.Kind) {
 	case "pod":
-		err := kubeClient.CoreV1().Pods(kubeobj.Namespace).Delete(ctx, kubeobj.Name, meta_v1.DeleteOptions{})
+		err := kubeClient.CoreV1().Pods(kubeobj.Namespace).Delete(ctx, kubeobj.Name, metav1.DeleteOptions{})
 		if err != nil {
 			logger.Error("error cleaning up pod", zap.Error(err), zap.String("pod", kubeobj.Name))
 		}
 
 	case "service":
-		err := kubeClient.CoreV1().Services(kubeobj.Namespace).Delete(ctx, kubeobj.Name, meta_v1.DeleteOptions{})
+		err := kubeClient.CoreV1().Services(kubeobj.Namespace).Delete(ctx, kubeobj.Name, metav1.DeleteOptions{})
 		if err != nil {
 			logger.Error("error cleaning up service", zap.Error(err), zap.String("service", kubeobj.Name))
 		}
@@ -58,7 +58,7 @@ func CleanupKubeObject(ctx context.Context, logger *zap.Logger, kubeClient kuber
 		}
 
 	case "horizontalpodautoscaler":
-		err := kubeClient.AutoscalingV1().HorizontalPodAutoscalers(kubeobj.Namespace).Delete(ctx, kubeobj.Name, meta_v1.DeleteOptions{})
+		err := kubeClient.AutoscalingV2beta2().HorizontalPodAutoscalers(kubeobj.Namespace).Delete(ctx, kubeobj.Name, metav1.DeleteOptions{})
 		if err != nil {
 			logger.Error("error cleaning up horizontalpodautoscaler", zap.Error(err), zap.String("horizontalpodautoscaler", kubeobj.Name))
 		}
@@ -70,8 +70,8 @@ func CleanupKubeObject(ctx context.Context, logger *zap.Logger, kubeClient kuber
 }
 
 // CleanupDeployments deletes deployment(s) for a given instanceID
-func CleanupDeployments(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps meta_v1.ListOptions) error {
-	deploymentList, err := client.AppsV1().Deployments(meta_v1.NamespaceAll).List(ctx, listOps)
+func CleanupDeployments(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps metav1.ListOptions) error {
+	deploymentList, err := client.AppsV1().Deployments(metav1.NamespaceAll).List(ctx, listOps)
 	if err != nil {
 		return err
 	}
@@ -97,8 +97,8 @@ func CleanupDeployments(ctx context.Context, logger *zap.Logger, client kubernet
 }
 
 // CleanupPods deletes pod(s) for a given instanceID
-func CleanupPods(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps meta_v1.ListOptions) error {
-	podList, err := client.CoreV1().Pods(meta_v1.NamespaceAll).List(ctx, listOps)
+func CleanupPods(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps metav1.ListOptions) error {
+	podList, err := client.CoreV1().Pods(metav1.NamespaceAll).List(ctx, listOps)
 	if err != nil {
 		return err
 	}
@@ -110,7 +110,7 @@ func CleanupPods(ctx context.Context, logger *zap.Logger, client kubernetes.Inte
 		}
 		if ok && id != instanceID {
 			logger.Info("cleaning up pod", zap.String("pod", pod.ObjectMeta.Name))
-			err := client.CoreV1().Pods(pod.ObjectMeta.Namespace).Delete(ctx, pod.ObjectMeta.Name, meta_v1.DeleteOptions{})
+			err := client.CoreV1().Pods(pod.ObjectMeta.Namespace).Delete(ctx, pod.ObjectMeta.Name, metav1.DeleteOptions{})
 			if err != nil {
 				logger.Error("error cleaning up pod",
 					zap.Error(err),
@@ -124,8 +124,8 @@ func CleanupPods(ctx context.Context, logger *zap.Logger, client kubernetes.Inte
 }
 
 // CleanupServices deletes service(s) for a given instanceID
-func CleanupServices(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps meta_v1.ListOptions) error {
-	svcList, err := client.CoreV1().Services(meta_v1.NamespaceAll).List(ctx, listOps)
+func CleanupServices(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps metav1.ListOptions) error {
+	svcList, err := client.CoreV1().Services(metav1.NamespaceAll).List(ctx, listOps)
 	if err != nil {
 		return err
 	}
@@ -137,7 +137,7 @@ func CleanupServices(ctx context.Context, logger *zap.Logger, client kubernetes.
 		}
 		if ok && id != instanceID {
 			logger.Info("cleaning up service", zap.String("service", svc.ObjectMeta.Name))
-			err := client.CoreV1().Services(svc.ObjectMeta.Namespace).Delete(ctx, svc.ObjectMeta.Name, meta_v1.DeleteOptions{})
+			err := client.CoreV1().Services(svc.ObjectMeta.Namespace).Delete(ctx, svc.ObjectMeta.Name, metav1.DeleteOptions{})
 			if err != nil {
 				logger.Error("error cleaning up service",
 					zap.Error(err),
@@ -151,8 +151,8 @@ func CleanupServices(ctx context.Context, logger *zap.Logger, client kubernetes.
 }
 
 // CleanupHpa deletes horizontal pod autoscaler(s) for a given instanceID
-func CleanupHpa(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps meta_v1.ListOptions) error {
-	hpaList, err := client.AutoscalingV1().HorizontalPodAutoscalers(meta_v1.NamespaceAll).List(ctx, listOps)
+func CleanupHpa(ctx context.Context, logger *zap.Logger, client kubernetes.Interface, instanceID string, listOps metav1.ListOptions) error {
+	hpaList, err := client.AutoscalingV2beta2().HorizontalPodAutoscalers(metav1.NamespaceAll).List(ctx, listOps)
 	if err != nil {
 		return err
 	}
@@ -165,7 +165,7 @@ func CleanupHpa(ctx context.Context, logger *zap.Logger, client kubernetes.Inter
 		}
 		if ok && id != instanceID {
 			logger.Info("cleaning up HPA", zap.String("hpa", hpa.ObjectMeta.Name))
-			err := client.AutoscalingV1().HorizontalPodAutoscalers(hpa.ObjectMeta.Namespace).Delete(ctx, hpa.ObjectMeta.Name, meta_v1.DeleteOptions{})
+			err := client.AutoscalingV2beta2().HorizontalPodAutoscalers(hpa.ObjectMeta.Namespace).Delete(ctx, hpa.ObjectMeta.Name, metav1.DeleteOptions{})
 			if err != nil {
 				logger.Error("error cleaning up HPA",
 					zap.Error(err),
@@ -187,7 +187,7 @@ func CleanupRoleBindings(ctx context.Context, logger *zap.Logger, client kuberne
 
 		logger.Debug("starting cleanupRoleBindings cycle")
 		// get all rolebindings ( just to be efficient, one call to kubernetes )
-		rbList, err := client.RbacV1().RoleBindings(meta_v1.NamespaceAll).List(ctx, meta_v1.ListOptions{})
+		rbList, err := client.RbacV1().RoleBindings(metav1.NamespaceAll).List(ctx, metav1.ListOptions{})
 		if err != nil {
 			// something wrong, but next iteration hopefully succeeds
 			logger.Error("error listing role bindings in all namespaces", zap.Error(err))
@@ -208,7 +208,7 @@ func CleanupRoleBindings(ctx context.Context, logger *zap.Logger, client kuberne
 
 			// in order to find out if there are any functions that need this role-binding in role-binding namespace,
 			// we can list the functions once per role-binding.
-			funcList, err := fissionClient.CoreV1().Functions(roleBinding.Namespace).List(ctx, meta_v1.ListOptions{})
+			funcList, err := fissionClient.CoreV1().Functions(roleBinding.Namespace).List(ctx, metav1.ListOptions{})
 			if err != nil {
 				logger.Error("error fetching function list in namespace", zap.Error(err), zap.String("namespace", roleBinding.Namespace))
 				continue
@@ -235,7 +235,7 @@ func CleanupRoleBindings(ctx context.Context, logger *zap.Logger, client kuberne
 				isInReservedNS := false
 				if subj.Namespace == functionNs ||
 					subj.Namespace == envBuilderNs {
-					saNs = meta_v1.NamespaceDefault
+					saNs = metav1.NamespaceDefault
 					isInReservedNS = true
 				}
 
@@ -259,7 +259,7 @@ func CleanupRoleBindings(ctx context.Context, logger *zap.Logger, client kuberne
 				// else if its a secret-configmap-rb, we have only one SA which is fission-fetcher
 				if roleBinding.Name == fv1.PackageGetterRB {
 					// check if there is an env obj in saNs
-					envList, err := fissionClient.CoreV1().Environments(saNs).List(ctx, meta_v1.ListOptions{})
+					envList, err := fissionClient.CoreV1().Environments(saNs).List(ctx, metav1.ListOptions{})
 					if err != nil {
 						logger.Error("error fetching environment list in service account namespace", zap.Error(err), zap.String("namespace", saNs))
 						continue
diff --git a/pkg/executor/util/hpa/hpa.go b/pkg/executor/util/hpa/hpa.go
new file mode 100644
index 00000000..67f6e1e7
--- /dev/null
+++ b/pkg/executor/util/hpa/hpa.go
@@ -0,0 +1,158 @@
+/*
+Copyright 2022 The Fission Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+package hpa
+
+import (
+	"context"
+	"errors"
+
+	"go.uber.org/zap"
+	appsv1 "k8s.io/api/apps/v1"
+	asv2beta2 "k8s.io/api/autoscaling/v2beta2"
+	corev1 "k8s.io/api/core/v1"
+	k8s_err "k8s.io/apimachinery/pkg/api/errors"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/client-go/kubernetes"
+
+	fv1 "github.com/fission/fission/pkg/apis/core/v1"
+	otelUtils "github.com/fission/fission/pkg/utils/otel"
+)
+
+// Deployment Constants
+const (
+	DeploymentKind    = "Deployment"
+	DeploymentVersion = "apps/v1"
+)
+
+type HpaOperations struct {
+	logger           *zap.Logger
+	kubernetesClient kubernetes.Interface
+	instanceID       string
+}
+
+func NewHpaOperations(logger *zap.Logger, kubernetesClient kubernetes.Interface, instanceID string) *HpaOperations {
+	return &HpaOperations{
+		logger:           logger,
+		kubernetesClient: kubernetesClient,
+		instanceID:       instanceID,
+	}
+}
+
+func ConvertTargetCPUToCustomMetric(targetCPUVal int32) asv2beta2.MetricSpec {
+	return asv2beta2.MetricSpec{
+		Type: asv2beta2.ResourceMetricSourceType,
+		Resource: &asv2beta2.ResourceMetricSource{
+			Name: corev1.ResourceCPU,
+			Target: asv2beta2.MetricTarget{
+				Type:               asv2beta2.UtilizationMetricType,
+				AverageUtilization: &targetCPUVal,
+			},
+		},
+	}
+}
+
+func getScaleTargetRef(deployment *appsv1.Deployment) asv2beta2.CrossVersionObjectReference {
+	return asv2beta2.CrossVersionObjectReference{
+		APIVersion: DeploymentVersion,
+		Kind:       DeploymentKind,
+		Name:       deployment.ObjectMeta.Name,
+	}
+}
+
+func (hpaops *HpaOperations) CreateOrGetHpa(ctx context.Context, hpaName string, execStrategy *fv1.ExecutionStrategy,
+	depl *appsv1.Deployment, deployLabels map[string]string, deployAnnotations map[string]string) (*asv2beta2.HorizontalPodAutoscaler, error) {
+
+	if depl == nil {
+		return nil, errors.New("failed to create HPA, found empty deployment")
+	}
+	logger := otelUtils.LoggerWithTraceID(ctx, hpaops.logger)
+
+	minRepl := int32(execStrategy.MinScale)
+	if minRepl == 0 {
+		minRepl = 1
+	}
+	maxRepl := int32(execStrategy.MaxScale)
+	if maxRepl == 0 {
+		maxRepl = minRepl
+	}
+	targetCPU := int32(execStrategy.TargetCPUPercent) // nolint: staticcheck
+	var hpaMetrics []asv2beta2.MetricSpec
+	if targetCPU > 0 && targetCPU < 100 {
+		hpaMetrics = append(hpaMetrics, ConvertTargetCPUToCustomMetric(targetCPU))
+	}
+
+	if execStrategy.Metrics != nil {
+		hpaMetrics = append(hpaMetrics, execStrategy.Metrics...)
+	}
+
+	hpa := &asv2beta2.HorizontalPodAutoscaler{
+		ObjectMeta: metav1.ObjectMeta{
+			Name:        hpaName,
+			Labels:      deployLabels,
+			Annotations: deployAnnotations,
+		},
+		Spec: asv2beta2.HorizontalPodAutoscalerSpec{
+			ScaleTargetRef: getScaleTargetRef(depl),
+			MinReplicas:    &minRepl,
+			MaxReplicas:    maxRepl,
+			Metrics:        hpaMetrics,
+			Behavior:       execStrategy.Behavior,
+		},
+	}
+
+	existingHpa, err := hpaops.GetHpa(ctx, depl.ObjectMeta.Namespace, hpaName)
+	if err == nil {
+		// to adopt orphan service
+		if existingHpa.Annotations[fv1.EXECUTOR_INSTANCEID_LABEL] != hpaops.instanceID {
+			existingHpa.Annotations = hpa.Annotations
+			existingHpa.Labels = hpa.Labels
+			existingHpa.Spec = hpa.Spec
+			existingHpa, err = hpaops.kubernetesClient.AutoscalingV2beta2().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Update(ctx, existingHpa, metav1.UpdateOptions{})
+			if err != nil {
+				logger.Warn("error adopting HPA", zap.Error(err),
+					zap.String("HPA", hpaName), zap.String("ns", depl.ObjectMeta.Namespace))
+				return nil, err
+			}
+		}
+		return existingHpa, err
+	} else if k8s_err.IsNotFound(err) {
+		cHpa, err := hpaops.kubernetesClient.AutoscalingV2beta2().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Create(ctx, hpa, metav1.CreateOptions{})
+		if err != nil {
+			if k8s_err.IsAlreadyExists(err) {
+				cHpa, err = hpaops.kubernetesClient.AutoscalingV2beta2().HorizontalPodAutoscalers(depl.ObjectMeta.Namespace).Get(ctx, hpaName, metav1.GetOptions{})
+			}
+			if err != nil {
+				return nil, err
+			}
+		}
+		otelUtils.SpanTrackEvent(ctx, "hpaCreated", otelUtils.GetAttributesForHPA(cHpa)...)
+		return cHpa, nil
+	}
+	return nil, err
+}
+
+func (hpaops *HpaOperations) GetHpa(ctx context.Context, ns, name string) (*asv2beta2.HorizontalPodAutoscaler, error) {
+	return hpaops.kubernetesClient.AutoscalingV2beta2().HorizontalPodAutoscalers(ns).Get(ctx, name, metav1.GetOptions{})
+}
+
+func (hpaops *HpaOperations) UpdateHpa(ctx context.Context, hpa *asv2beta2.HorizontalPodAutoscaler) error {
+	_, err := hpaops.kubernetesClient.AutoscalingV2beta2().HorizontalPodAutoscalers(hpa.ObjectMeta.Namespace).Update(ctx, hpa, metav1.UpdateOptions{})
+	return err
+}
+
+func (hpaops *HpaOperations) DeleteHpa(ctx context.Context, ns string, name string) error {
+	return hpaops.kubernetesClient.AutoscalingV2beta2().HorizontalPodAutoscalers(ns).Delete(ctx, name, metav1.DeleteOptions{})
+}
diff --git a/pkg/fission-cli/cmd/environment/command.go b/pkg/fission-cli/cmd/environment/command.go
index feea1f0b..df19f13b 100644
--- a/pkg/fission-cli/cmd/environment/command.go
+++ b/pkg/fission-cli/cmd/environment/command.go
@@ -59,7 +59,7 @@ func Commands() *cobra.Command {
 		Optional: []flag.Flag{flag.EnvImage, flag.EnvPoolsize,
 			flag.EnvBuilderImage, flag.EnvBuildCmd, flag.EnvImagePullSecret,
 			flag.RunTimeMinCPU, flag.RunTimeMaxCPU, flag.RunTimeMinMemory, flag.RunTimeMaxMemory,
-			flag.EnvTerminationGracePeriod, flag.EnvKeepArchive,
+			flag.EnvTerminationGracePeriod, flag.EnvKeepArchive, flag.EnvRuntime,
 			flag.NamespaceEnvironment, flag.EnvExternalNetwork,
 			flag.Labels, flag.Annotation},
 	})
diff --git a/pkg/fission-cli/cmd/environment/update.go b/pkg/fission-cli/cmd/environment/update.go
index 8e05d09b..3d5b871c 100644
--- a/pkg/fission-cli/cmd/environment/update.go
+++ b/pkg/fission-cli/cmd/environment/update.go
@@ -163,6 +163,12 @@ func updateExistingEnvironmentWithCmd(env *fv1.Environment, input cli.Input) (*f
 		env.Spec.Resources.Limits[v1.ResourceMemory] = memLimit
 	}
 
+	if input.IsSet(flagkey.EnvRuntime) {
+		runtimeEnvParams := input.StringSlice(flagkey.EnvRuntime)
+		runtimeEnvList := util.GetEnvVarFromStringSlice(runtimeEnvParams)
+		env.Spec.Runtime.Container.Env = runtimeEnvList
+	}
+
 	limitCPU := env.Spec.Resources.Limits[v1.ResourceCPU]
 	requestCPU := env.Spec.Resources.Requests[v1.ResourceCPU]
 
diff --git a/pkg/fission-cli/cmd/function/create.go b/pkg/fission-cli/cmd/function/create.go
index 0ba21799..430198a8 100644
--- a/pkg/fission-cli/cmd/function/create.go
+++ b/pkg/fission-cli/cmd/function/create.go
@@ -21,12 +21,14 @@ import (
 
 	"github.com/pkg/errors"
 	uuid "github.com/satori/go.uuid"
+	asv2beta2 "k8s.io/api/autoscaling/v2beta2"
 	apiv1 "k8s.io/api/core/v1"
 	k8serrors "k8s.io/apimachinery/pkg/api/errors"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 
 	fv1 "github.com/fission/fission/pkg/apis/core/v1"
 	ferror "github.com/fission/fission/pkg/error"
+	"github.com/fission/fission/pkg/executor/util/hpa"
 	"github.com/fission/fission/pkg/fission-cli/cliwrapper/cli"
 	"github.com/fission/fission/pkg/fission-cli/cmd"
 	"github.com/fission/fission/pkg/fission-cli/cmd/httptrigger"
@@ -38,9 +40,8 @@ import (
 )
 
 const (
-	DEFAULT_MIN_SCALE             = 1
-	DEFAULT_TARGET_CPU_PERCENTAGE = 80
-	DEFAULT_CONCURRENCY           = 500
+	DEFAULT_MIN_SCALE   = 1
+	DEFAULT_CONCURRENCY = 500
 )
 
 type CreateSubCommand struct {
@@ -463,13 +464,6 @@ func getExecutionStrategy(fnExecutor fv1.ExecutorType, input cli.Input) (strateg
 			SpecializationTimeout: specializationTimeout,
 		}
 	} else {
-		targetCPU := DEFAULT_TARGET_CPU_PERCENTAGE
-		if input.IsSet(flagkey.RuntimeTargetcpu) {
-			targetCPU, err = getTargetCPU(input)
-			if err != nil {
-				return nil, err
-			}
-		}
 
 		minScale := DEFAULT_MIN_SCALE
 		if input.IsSet(flagkey.ReplicasMinscale) {
@@ -494,9 +488,16 @@ func getExecutionStrategy(fnExecutor fv1.ExecutorType, input cli.Input) (strateg
 			ExecutorType:          fnExecutor,
 			MinScale:              minScale,
 			MaxScale:              maxScale,
-			TargetCPUPercent:      targetCPU,
 			SpecializationTimeout: specializationTimeout,
 		}
+
+		if input.IsSet(flagkey.RuntimeTargetcpu) {
+			targetCPU, err := getTargetCPU(input)
+			if err != nil {
+				return nil, err
+			}
+			strategy.Metrics = []asv2beta2.MetricSpec{hpa.ConvertTargetCPUToCustomMetric(int32(targetCPU))}
+		}
 	}
 
 	return strategy, nil
@@ -547,27 +548,14 @@ func updateExecutionStrategy(input cli.Input, existingExecutionStrategy *fv1.Exe
 			SpecializationTimeout: specializationTimeout,
 		}
 	} else {
-		targetCPU := existingExecutionStrategy.TargetCPUPercent
 		minScale := existingExecutionStrategy.MinScale
 		maxScale := existingExecutionStrategy.MaxScale
 
 		if fnExecutor != oldExecutor { // from poolmanager to newdeploy
-			targetCPU = DEFAULT_TARGET_CPU_PERCENTAGE
 			minScale = DEFAULT_MIN_SCALE
 			maxScale = minScale
 		}
 
-		if input.IsSet(flagkey.RuntimeTargetcpu) {
-			targetCPU, err = getTargetCPU(input)
-			if err != nil {
-				return nil, err
-			}
-		} else {
-			if targetCPU <= 0 || targetCPU > 100 {
-				targetCPU = DEFAULT_TARGET_CPU_PERCENTAGE
-			}
-		}
-
 		if input.IsSet(flagkey.ReplicasMinscale) {
 			minScale = input.Int(flagkey.ReplicasMinscale)
 		}
@@ -593,9 +581,17 @@ func updateExecutionStrategy(input cli.Input, existingExecutionStrategy *fv1.Exe
 			ExecutorType:          fnExecutor,
 			MinScale:              minScale,
 			MaxScale:              maxScale,
-			TargetCPUPercent:      targetCPU,
 			SpecializationTimeout: specializationTimeout,
 		}
+
+		if input.IsSet(flagkey.RuntimeTargetcpu) {
+			targetCPU, err := getTargetCPU(input)
+			if err != nil {
+				return nil, err
+			}
+			strategy.Metrics = []asv2beta2.MetricSpec{hpa.ConvertTargetCPUToCustomMetric(int32(targetCPU))}
+		}
+
 	}
 
 	return strategy, nil
diff --git a/pkg/fission-cli/cmd/function/list.go b/pkg/fission-cli/cmd/function/list.go
index b9af9483..dee6b2d6 100644
--- a/pkg/fission-cli/cmd/function/list.go
+++ b/pkg/fission-cli/cmd/function/list.go
@@ -47,7 +47,7 @@ func (opts *ListSubCommand) do(input cli.Input) error {
 
 	w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
 
-	fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", "NAME", "ENV", "EXECUTORTYPE", "MINSCALE", "MAXSCALE", "MINCPU", "MAXCPU", "MINMEMORY", "MAXMEMORY", "TARGETCPU", "SECRETS", "CONFIGMAPS")
+	fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", "NAME", "ENV", "EXECUTORTYPE", "MINSCALE", "MAXSCALE", "MINCPU", "MAXCPU", "MINMEMORY", "MAXMEMORY", "SECRETS", "CONFIGMAPS")
 	for _, f := range fns {
 		secrets := f.Spec.Secrets
 		configMaps := f.Spec.ConfigMaps
@@ -59,7 +59,7 @@ func (opts *ListSubCommand) do(input cli.Input) error {
 			configMapList = append(configMapList, configMap.Name)
 		}
 
-		fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
+		fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
 			f.ObjectMeta.Name, f.Spec.Environment.Name,
 			f.Spec.InvokeStrategy.ExecutionStrategy.ExecutorType,
 			f.Spec.InvokeStrategy.ExecutionStrategy.MinScale,
@@ -68,7 +68,6 @@ func (opts *ListSubCommand) do(input cli.Input) error {
 			f.Spec.Resources.Limits.Cpu().String(),
 			f.Spec.Resources.Requests.Memory().String(),
 			f.Spec.Resources.Limits.Memory().String(),
-			f.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent,
 			strings.Join(secretsList, ","),
 			strings.Join(configMapList, ","))
 	}
diff --git a/pkg/fission-cli/cmd/spec/list.go b/pkg/fission-cli/cmd/spec/list.go
index 378aac5d..14729307 100644
--- a/pkg/fission-cli/cmd/spec/list.go
+++ b/pkg/fission-cli/cmd/spec/list.go
@@ -218,7 +218,7 @@ func ShowFunctions(fns []fv1.Function) {
 	if len(fns) > 0 {
 		w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
 		fmt.Fprintf(w, "%v\n", "Functions:")
-		fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", "NAME", "ENV", "EXECUTORTYPE", "MINSCALE", "MAXSCALE", "MINCPU", "MAXCPU", "MINMEMORY", "MAXMEMORY", "TARGETCPU", "SECRETS", "CONFIGMAPS")
+		fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n", "NAME", "ENV", "EXECUTORTYPE", "MINSCALE", "MAXSCALE", "MINCPU", "MAXCPU", "MINMEMORY", "MAXMEMORY", "SECRETS", "CONFIGMAPS")
 
 		for _, f := range fns {
 			secrets := f.Spec.Secrets
@@ -231,7 +231,7 @@ func ShowFunctions(fns []fv1.Function) {
 				configMapList = append(configMapList, configMap.Name)
 			}
 
-			fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
+			fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
 				f.ObjectMeta.Name, f.Spec.Environment.Name,
 				f.Spec.InvokeStrategy.ExecutionStrategy.ExecutorType,
 				f.Spec.InvokeStrategy.ExecutionStrategy.MinScale,
@@ -240,7 +240,6 @@ func ShowFunctions(fns []fv1.Function) {
 				f.Spec.Resources.Limits.Cpu().String(),
 				f.Spec.Resources.Requests.Memory().String(),
 				f.Spec.Resources.Limits.Memory().String(),
-				f.Spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent,
 				strings.Join(secretsList, ","),
 				strings.Join(configMapList, ","))
 		}
diff --git a/pkg/fission-cli/cmd/support/resources/kubernetes.go b/pkg/fission-cli/cmd/support/resources/kubernetes.go
index ad655fc7..381b31bc 100644
--- a/pkg/fission-cli/cmd/support/resources/kubernetes.go
+++ b/pkg/fission-cli/cmd/support/resources/kubernetes.go
@@ -116,7 +116,7 @@ func (res KubernetesObjectDumper) Dump(dumpDir string) {
 		}
 
 	case KubernetesHPA:
-		objs, err := res.client.AutoscalingV2beta1().HorizontalPodAutoscalers(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{LabelSelector: res.selector})
+		objs, err := res.client.AutoscalingV2beta2().HorizontalPodAutoscalers(metav1.NamespaceAll).List(context.TODO(), metav1.ListOptions{LabelSelector: res.selector})
 		if err != nil {
 			console.Error(fmt.Sprintf("Error getting %v list with selector %v: %v", res.objType, res.selector, err))
 			return
diff --git a/pkg/fission-cli/util/portforward.go b/pkg/fission-cli/util/portforward.go
index b394e631..2a48fa10 100644
--- a/pkg/fission-cli/util/portforward.go
+++ b/pkg/fission-cli/util/portforward.go
@@ -28,7 +28,7 @@ import (
 
 	"github.com/pkg/errors"
 	v1 "k8s.io/api/core/v1"
-	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
 	"k8s.io/client-go/tools/portforward"
 	"k8s.io/client-go/transport/spdy"
 
@@ -120,12 +120,12 @@ func runPortForward(ctx context.Context, labelSelector string, localPort string,
 
 	// if namespace is unset, try to find a pod in any namespace
 	if len(ns) == 0 {
-		ns = meta_v1.NamespaceAll
+		ns = metav1.NamespaceAll
 	}
 
 	// get the pod; if there is more than one, ask the user to disambiguate
 	podList, err := clientset.CoreV1().Pods(ns).
-		List(ctx, meta_v1.ListOptions{LabelSelector: labelSelector})
+		List(ctx, metav1.ListOptions{LabelSelector: labelSelector})
 	if err != nil {
 		return nil, nil, errors.Wrapf(err, "error getting pod for port-forwarding with label selector %v", labelSelector)
 	} else if len(podList.Items) == 0 {
@@ -171,7 +171,7 @@ func runPortForward(ctx context.Context, labelSelector string, localPort string,
 
 	// get the service and the target port
 	svcs, err := clientset.CoreV1().Services(podNameSpace).
-		List(ctx, meta_v1.ListOptions{LabelSelector: labelSelector})
+		List(ctx, metav1.ListOptions{LabelSelector: labelSelector})
 	if err != nil {
 		return nil, nil, errors.Wrapf(err, "Error getting %v service", labelSelector)
 	}
diff --git a/pkg/utils/otel/attributes.go b/pkg/utils/otel/attributes.go
index 162a8122..2c8177b1 100644
--- a/pkg/utils/otel/attributes.go
+++ b/pkg/utils/otel/attributes.go
@@ -6,7 +6,8 @@ import (
 	"go.opentelemetry.io/otel/attribute"
 	"go.opentelemetry.io/otel/trace"
 	appsv1 "k8s.io/api/apps/v1"
-	asv1 "k8s.io/api/autoscaling/v1"
+	asv2beta2 "k8s.io/api/autoscaling/v2beta2"
+
 	apiv1 "k8s.io/api/core/v1"
 
 	fv1 "github.com/fission/fission/pkg/apis/core/v1"
@@ -74,7 +75,7 @@ func GetAttributesForDeployment(deployment *appsv1.Deployment) []attribute.KeyVa
 	}
 }
 
-func GetAttributesForHPA(hpa *asv1.HorizontalPodAutoscaler) []attribute.KeyValue {
+func GetAttributesForHPA(hpa *asv2beta2.HorizontalPodAutoscaler) []attribute.KeyValue {
 	if hpa == nil {
 		return []attribute.KeyValue{}
 	}
diff --git a/skaffold.yaml b/skaffold.yaml
index b75f7786..3aec6abe 100644
--- a/skaffold.yaml
+++ b/skaffold.yaml
@@ -15,13 +15,13 @@ kind: Config
 build:
   artifacts:
   - image: fission-bundle
-    context: dist/fission-bundle_linux_amd64
+    context: dist/fission-bundle_linux_amd64_v1
   - image: fetcher
-    context: dist/fetcher_linux_amd64
+    context: dist/fetcher_linux_amd64_v1
   - image: pre-upgrade-checks
-    context: dist/pre-upgrade-checks_linux_amd64
+    context: dist/pre-upgrade-checks_linux_amd64_v1
   - image: reporter
-    context: dist/reporter_linux_amd64
+    context: dist/reporter_linux_amd64_v1
 deploy:
   helm:
     releases:


Test patch:
diff --git a/.github/workflows/upgrade_test.yaml b/.github/workflows/upgrade_test.yaml
index 77cdba94..e77c1a0a 100644
--- a/.github/workflows/upgrade_test.yaml
+++ b/.github/workflows/upgrade_test.yaml
@@ -33,7 +33,7 @@ jobs:
     - name: Setup go
       uses: actions/setup-go@v2
       with:
-        go-version: 1.18
+        go-version: 1.18.1
 
     - name: Checkout action sources
       uses: actions/checkout@v2.3.4
@@ -60,7 +60,6 @@ jobs:
       uses: goreleaser/goreleaser-action@v2
       with:
         install-only: true
-        version: 1.7.0
 
     - name: Setup kubectl & fetch node information
       run: |
diff --git a/pkg/executor/util/hpa/hpa_test.go b/pkg/executor/util/hpa/hpa_test.go
new file mode 100644
index 00000000..d648887b
--- /dev/null
+++ b/pkg/executor/util/hpa/hpa_test.go
@@ -0,0 +1,147 @@
+/*
+Copyright 2022 The Fission Authors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+package hpa
+
+import (
+	"context"
+	"strings"
+	"testing"
+
+	"github.com/dchest/uniuri"
+	appsv1 "k8s.io/api/apps/v1"
+	asv2beta2 "k8s.io/api/autoscaling/v2beta2"
+	corev1 "k8s.io/api/core/v1"
+	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+	"k8s.io/client-go/kubernetes/fake"
+
+	fv1 "github.com/fission/fission/pkg/apis/core/v1"
+	"github.com/fission/fission/pkg/utils/loggerfactory"
+)
+
+func TestConvertTargetCPUToCustomMetric(t *testing.T) {
+	metricSpec := ConvertTargetCPUToCustomMetric(50)
+	if metricSpec.Type != asv2beta2.ResourceMetricSourceType {
+		t.Errorf("Expected metric type to be Resource, got %v", metricSpec.Type)
+	}
+	if metricSpec.Resource.Name != corev1.ResourceCPU {
+		t.Errorf("Expected metric name to be cpu, got %v", metricSpec.Resource.Name)
+	}
+	if metricSpec.Resource.Target.Type != asv2beta2.UtilizationMetricType {
+		t.Errorf("Expected metric target type to be Utilization, got %v", metricSpec.Resource.Target.Type)
+	}
+	if metricSpec.Resource.Target.AverageUtilization == nil {
+		t.Errorf("Expected metric target average utilization to be set, got nil")
+	}
+}
+
+func TestHpaOps(t *testing.T) {
+	logger := loggerfactory.GetLogger()
+	kubernetesClient := fake.NewSimpleClientset()
+	instanceID := strings.ToLower(uniuri.NewLen(8))
+	ns := "test-namespace"
+	hpaops := NewHpaOperations(logger, kubernetesClient, instanceID)
+	if hpaops.instanceID != instanceID {
+		t.Errorf("Expected instanceID to be %v, got %v", instanceID, hpaops.instanceID)
+	}
+
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+
+	deployLabels := map[string]string{
+		"test-label": "test-label-value",
+	}
+	deployAnnotations := map[string]string{
+		"test-annotation": "test-annotation-value",
+	}
+	// Test CreateHPA
+	hpa, err := hpaops.CreateOrGetHpa(ctx, "test-hpa",
+		&fv1.ExecutionStrategy{
+			ExecutorType:          fv1.ExecutorTypeNewdeploy,
+			MinScale:              1,
+			MaxScale:              5,
+			TargetCPUPercent:      50,
+			SpecializationTimeout: 300,
+		},
+		&appsv1.Deployment{
+			ObjectMeta: metav1.ObjectMeta{
+				Name:      "test-deployment",
+				Namespace: ns,
+			},
+		},
+		deployLabels,
+		deployAnnotations)
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+	if *hpa.Spec.MinReplicas != 1 {
+		t.Errorf("Expected min replicas to be 1, got %v", hpa.Spec.MinReplicas)
+	}
+	if hpa.Spec.MaxReplicas != 5 {
+		t.Errorf("Expected max replicas to be 5, got %v", hpa.Spec.MaxReplicas)
+	}
+	if hpa.Spec.Metrics[0].Type != asv2beta2.ResourceMetricSourceType {
+		t.Errorf("Expected metric type to be Resource, got %v", hpa.Spec.Metrics[0].Type)
+	}
+	if hpa.Spec.Metrics[0].Resource.Name != corev1.ResourceCPU {
+		t.Errorf("Expected metric name to be cpu, got %v", hpa.Spec.Metrics[0].Resource.Name)
+	}
+	if hpa.Spec.Metrics[0].Resource.Target.Type != asv2beta2.UtilizationMetricType {
+		t.Errorf("Expected metric target type to be Utilization, got %v", hpa.Spec.Metrics[0].Resource.Target.Type)
+	}
+	if hpa.Spec.Metrics[0].Resource.Target.AverageUtilization == nil {
+		t.Errorf("Expected metric target average utilization to be set, got nil")
+	}
+	if *hpa.Spec.Metrics[0].Resource.Target.AverageUtilization != 50 {
+		t.Errorf("Expected metric target average utilization to be 50, got %v", *hpa.Spec.Metrics[0].Resource.Target.AverageUtilization)
+	}
+	if hpa.ObjectMeta.Labels["test-label"] != "test-label-value" {
+		t.Errorf("Expected label to be set, got %v", hpa.ObjectMeta.Labels["test-label"])
+	}
+	if hpa.ObjectMeta.Annotations["test-annotation"] != "test-annotation-value" {
+		t.Errorf("Expected annotation to be set, got %v", hpa.ObjectMeta.Annotations["test-annotation"])
+	}
+
+	hpa, err = hpaops.GetHpa(ctx, ns, "test-hpa")
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+	hpa.Spec.MaxReplicas = 10
+
+	// Test UpdateHPA
+	err = hpaops.UpdateHpa(ctx, hpa)
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+
+	hpa, err = hpaops.GetHpa(ctx, ns, "test-hpa")
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+	if hpa.Spec.MaxReplicas != 10 {
+		t.Errorf("Expected max replicas to be 10, got %v", hpa.Spec.MaxReplicas)
+	}
+
+	// Test DeleteHPA
+	err = hpaops.DeleteHpa(ctx, ns, "test-hpa")
+	if err != nil {
+		t.Errorf("Unexpected error: %v", err)
+	}
+
+	_, err = hpaops.GetHpa(ctx, ns, "test-hpa")
+	if err == nil {
+		t.Errorf("Expected error, got nil")
+	}
+}
diff --git a/pkg/fission-cli/cmd/function/function_test.go b/pkg/fission-cli/cmd/function/function_test.go
index c00cef75..ee2cb2eb 100644
--- a/pkg/fission-cli/cmd/function/function_test.go
+++ b/pkg/fission-cli/cmd/function/function_test.go
@@ -21,8 +21,10 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	asv2beta2 "k8s.io/api/autoscaling/v2beta2"
 
 	fv1 "github.com/fission/fission/pkg/apis/core/v1"
+	"github.com/fission/fission/pkg/executor/util/hpa"
 	"github.com/fission/fission/pkg/fission-cli/cliwrapper/driver/dummy"
 	flagkey "github.com/fission/fission/pkg/fission-cli/flag/key"
 )
@@ -71,7 +73,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              DEFAULT_MIN_SCALE,
 					MaxScale:              DEFAULT_MIN_SCALE,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -92,7 +93,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              DEFAULT_MIN_SCALE,
 					MaxScale:              DEFAULT_MIN_SCALE,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -107,7 +107,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              DEFAULT_MIN_SCALE,
 					MaxScale:              DEFAULT_MIN_SCALE,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -134,7 +133,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              3,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -164,7 +162,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              5,
 					MaxScale:              5,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -183,7 +180,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              DEFAULT_MIN_SCALE,
 					MaxScale:              3,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -211,7 +207,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              5,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -230,7 +225,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              5,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -240,7 +234,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              9,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -257,7 +250,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              5,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -267,7 +259,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              5,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -286,7 +277,7 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              DEFAULT_MIN_SCALE,
 					MaxScale:              DEFAULT_MIN_SCALE,
-					TargetCPUPercent:      50,
+					Metrics:               []asv2beta2.MetricSpec{hpa.ConvertTargetCPUToCustomMetric(50)},
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -304,7 +295,7 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              5,
-					TargetCPUPercent:      88,
+					Metrics:               []asv2beta2.MetricSpec{hpa.ConvertTargetCPUToCustomMetric(88)},
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -314,7 +305,7 @@ func TestGetInvokeStrategy(t *testing.T) {
 					ExecutorType:          fv1.ExecutorTypeNewdeploy,
 					MinScale:              2,
 					MaxScale:              5,
-					TargetCPUPercent:      20,
+					Metrics:               []asv2beta2.MetricSpec{hpa.ConvertTargetCPUToCustomMetric(20)},
 					SpecializationTimeout: fv1.DefaultSpecializationTimeOut,
 				},
 			},
@@ -329,10 +320,9 @@ func TestGetInvokeStrategy(t *testing.T) {
 			existingInvokeStrategy: &fv1.InvokeStrategy{
 				StrategyType: fv1.StrategyTypeExecution,
 				ExecutionStrategy: fv1.ExecutionStrategy{
-					ExecutorType:     fv1.ExecutorTypeNewdeploy,
-					MinScale:         2,
-					MaxScale:         5,
-					TargetCPUPercent: DEFAULT_TARGET_CPU_PERCENTAGE,
+					ExecutorType: fv1.ExecutorTypeNewdeploy,
+					MinScale:     2,
+					MaxScale:     5,
 				},
 			},
 			expectedResult: &fv1.InvokeStrategy{
@@ -342,7 +332,6 @@ func TestGetInvokeStrategy(t *testing.T) {
 					MinScale:              2,
 					MaxScale:              5,
 					SpecializationTimeout: 200,
-					TargetCPUPercent:      DEFAULT_TARGET_CPU_PERCENTAGE,
 				},
 			},
 			expectError: false,
diff --git a/test/tests/test_fn_update/test_scale_change.sh b/test/tests/test_fn_update/test_scale_change.sh
index 61a6f15a..85a8ec15 100755
--- a/test/tests/test_fn_update/test_scale_change.sh
+++ b/test/tests/test_fn_update/test_scale_change.sh
@@ -49,7 +49,7 @@ sleep 5
 func=function
 actualMinScale=$(kubectl -n default get $func $fn -ojsonpath='{.spec.InvokeStrategy.ExecutionStrategy.MinScale}')
 actualMaxScale=$(kubectl -n default get $func $fn -ojsonpath='{.spec.InvokeStrategy.ExecutionStrategy.MaxScale}')
-actualTargetCPU=$(kubectl -n default get $func $fn -ojsonpath='{.spec.InvokeStrategy.ExecutionStrategy.TargetCPUPercent}')
+actualTargetCPU=$(kubectl -n default get $func $fn -ojsonpath='{.spec.InvokeStrategy.ExecutionStrategy.hpaMetrics[0].target.averageUtilization}')
 
 if [ "$actualMinScale" -ne "$targetMinScale" ]
 then
diff --git a/test/upgrade_test/fission_objects.sh b/test/upgrade_test/fission_objects.sh
index 3e814681..08be3d2a 100644
--- a/test/upgrade_test/fission_objects.sh
+++ b/test/upgrade_test/fission_objects.sh
@@ -83,11 +83,11 @@ test_fission_objects() {
 build_docker_images() {
     echo "Building new docker images"
     make skaffold-prebuild
-    doit docker build -t fission-bundle dist/fission-bundle_linux_amd64
-    doit docker build -t fetcher dist/fetcher_linux_amd64
-    doit docker build -t builder dist/builder_linux_amd64
-    doit docker build -t reporter dist/reporter_linux_amd64
-    doit docker build -t preupgradechecks dist/pre-upgrade-checks_linux_amd64
+    doit docker build -t fission-bundle dist/fission-bundle_linux_amd64_v1
+    doit docker build -t fetcher dist/fetcher_linux_amd64_v1
+    doit docker build -t builder dist/builder_linux_amd64_v1
+    doit docker build -t reporter dist/reporter_linux_amd64_v1
+    doit docker build -t preupgradechecks dist/pre-upgrade-checks_linux_amd64_v1
 }
 
 kind_image_load() {