Repository: VictoriaMetrics/VictoriaMetrics
Pull request #1120 (2021-03-09 12:57:07)

Fixing examples of external.alert.source in documentation
- Removing trailing whitespaces in the documentation
- Fixing examples for using external.alert.source in the documentation, fixes https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1117


Patch:
diff --git a/app/vmalert/README.md b/app/vmalert/README.md
index adfed9bf2..5a286c289 100644
--- a/app/vmalert/README.md
+++ b/app/vmalert/README.md
@@ -16,7 +16,7 @@ rules against configured address.
 * Lightweight without extra dependencies.
 
 ### Limitations:
-* `vmalert` execute queries against remote datasource which has reliability risks because of network. 
+* `vmalert` execute queries against remote datasource which has reliability risks because of network.
 It is recommended to configure alerts thresholds and rules expressions with understanding that network request
 may fail;
 * by default, rules execution is sequential within one group, but persisting of execution results to remote
@@ -37,7 +37,7 @@ The build binary will be placed to `VictoriaMetrics/bin` folder.
 To start using `vmalert` you will need the following things:
 * list of rules - PromQL/MetricsQL expressions to execute;
 * datasource address - reachable VictoriaMetrics instance for rules execution;
-* notifier address - reachable [Alert Manager](https://github.com/prometheus/alertmanager) instance for processing, 
+* notifier address - reachable [Alert Manager](https://github.com/prometheus/alertmanager) instance for processing,
 aggregating alerts and sending notifications.
 * remote write address - [remote write](https://prometheus.io/docs/prometheus/latest/storage/#remote-storage-integrations)
 compatible storage address for storing recording rules results and alerts state in for of timeseries. This is optional.
@@ -56,11 +56,11 @@ Then configure `vmalert` accordingly:
 ```
 
 If you run multiple `vmalert` services for the same datastore or AlertManager - do not forget
-to specify different `external.label` flags in order to define which `vmalert` generated rules or alerts. 
+to specify different `external.label` flags in order to define which `vmalert` generated rules or alerts.
 
-Configuration for [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) 
-and [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) rules is very 
-similar to Prometheus rules and configured using YAML. Configuration examples may be found 
+Configuration for [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/)
+and [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) rules is very
+similar to Prometheus rules and configured using YAML. Configuration examples may be found
 in [testdata](https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/app/vmalert/config/testdata) folder.
 Every `rule` belongs to `group` and every configuration file may contain arbitrary number of groups:
 ```yaml
@@ -79,7 +79,7 @@ name: <string>
 [ interval: <duration> | default = global.evaluation_interval ]
 
 # How many rules execute at once. Increasing concurrency may speed
-# up round execution speed. 
+# up round execution speed.
 [ concurrency: <integer> | default = 1 ]
 
 # Optional type for expressions inside the rules. Supported values: "graphite" and "prometheus".
@@ -93,15 +93,15 @@ rules:
 #### Rules
 
 There are two types of Rules:
-* [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) - 
+* [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) -
 Alerting rules allows to define alert conditions via [MetricsQL](https://victoriametrics.github.io/MetricsQL.html)
 and to send notifications about firing alerts to [Alertmanager](https://github.com/prometheus/alertmanager).
-* [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) - 
-Recording rules allow you to precompute frequently needed or computationally expensive expressions 
+* [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) -
+Recording rules allow you to precompute frequently needed or computationally expensive expressions
 and save their result as a new set of time series.
 
 `vmalert` forbids to define duplicates - rules with the same combination of name, expression and labels
-within one group. 
+within one group.
 
 ##### Alerting rules
 
@@ -130,7 +130,7 @@ labels:
 # Annotations to add to each alert.
 annotations:
   [ <labelname>: <tmpl_string> ]
-``` 
+```
 
 ##### Recording rules
 
@@ -158,17 +158,17 @@ For recording rules to work `-remoteWrite.url` must specified.
 
 #### Alerts state on restarts
 
-`vmalert` has no local storage, so alerts state is stored in the process memory. Hence, after reloading of `vmalert` 
+`vmalert` has no local storage, so alerts state is stored in the process memory. Hence, after reloading of `vmalert`
 the process alerts state will be lost. To avoid this situation, `vmalert` should be configured via the following flags:
-* `-remoteWrite.url` - URL to VictoriaMetrics (Single) or VMInsert (Cluster). `vmalert` will persist alerts state 
-into the configured address in the form of time series named `ALERTS` and `ALERTS_FOR_STATE` via remote-write protocol. 
-These are regular time series and may be queried from VM just as any other time series. 
+* `-remoteWrite.url` - URL to VictoriaMetrics (Single) or VMInsert (Cluster). `vmalert` will persist alerts state
+into the configured address in the form of time series named `ALERTS` and `ALERTS_FOR_STATE` via remote-write protocol.
+These are regular time series and may be queried from VM just as any other time series.
 The state stored to the configured address on every rule evaluation.
-* `-remoteRead.url` - URL to VictoriaMetrics (Single) or VMSelect (Cluster). `vmalert` will try to restore alerts state 
+* `-remoteRead.url` - URL to VictoriaMetrics (Single) or VMSelect (Cluster). `vmalert` will try to restore alerts state
 from configured address by querying time series with name `ALERTS_FOR_STATE`.
 
 Both flags are required for the proper state restoring. Restore process may fail if time series are missing
-in configured `-remoteRead.url`, weren't updated in the last `1h` or received state doesn't match current `vmalert` 
+in configured `-remoteRead.url`, weren't updated in the last `1h` or received state doesn't match current `vmalert`
 rules configuration.
 
 
@@ -232,7 +232,7 @@ The shortlist of configuration flags is the following:
     	How often to evaluate the rules (default 1m0s)
   -external.alert.source string
     	External Alert Source allows to override the Source link for alerts sent to AlertManager for cases where you want to build a custom link to Grafana, Prometheus or any other service.
-    	eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|pathEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used
+    	eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|queryEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used
   -external.label array
     	Optional label in the form 'name=value' to add to all generated recording rules and alerts. Pass multiple -label flags in order to add multiple label sets.
     	Supports array of values separated by comma or specified via multiple flags.
@@ -348,11 +348,11 @@ The shortlist of configuration flags is the following:
   -remoteWrite.url string
     	Optional URL to Victoria Metrics or VMInsert where to persist alerts state and recording rules results in form of timeseries. E.g. http://127.0.0.1:8428
   -rule array
-    	Path to the file with alert rules. 
-    	Supports patterns. Flag can be specified multiple times. 
+    	Path to the file with alert rules.
+    	Supports patterns. Flag can be specified multiple times.
     	Examples:
     	 -rule="/path/to/file". Path to a single file with alerting rules
-    	 -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder, 
+    	 -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder,
     	absolute path to all .yaml files in root.
     	Rule files may contain %{ENV_VAR} placeholders, which are substituted by the corresponding env vars.
     	Supports array of values separated by comma or specified via multiple flags.
@@ -370,7 +370,7 @@ The shortlist of configuration flags is the following:
     	Show VictoriaMetrics version
 ```
 
-Pass `-help` to `vmalert` in order to see the full list of supported 
+Pass `-help` to `vmalert` in order to see the full list of supported
 command-line flags with their descriptions.
 
 To reload configuration without `vmalert` restart send SIGHUP signal
@@ -379,13 +379,13 @@ or send GET request to `/-/reload` endpoint.
 ### Contributing
 
 `vmalert` is mostly designed and built by VictoriaMetrics community.
-Feel free to share your experience and ideas for improving this 
+Feel free to share your experience and ideas for improving this
 software. Please keep simplicity as the main priority.
 
 ### How to build from sources
 
-It is recommended using 
-[binary releases](https://github.com/VictoriaMetrics/VictoriaMetrics/releases) 
+It is recommended using
+[binary releases](https://github.com/VictoriaMetrics/VictoriaMetrics/releases)
 - `vmalert` is located in `vmutils-*` archives there.
 
 
diff --git a/app/vmalert/main.go b/app/vmalert/main.go
index d04584eb2..baae921e3 100644
--- a/app/vmalert/main.go
+++ b/app/vmalert/main.go
@@ -26,11 +26,11 @@ import (
 )
 
 var (
-	rulePath = flagutil.NewArray("rule", `Path to the file with alert rules. 
-Supports patterns. Flag can be specified multiple times. 
+	rulePath = flagutil.NewArray("rule", `Path to the file with alert rules.
+Supports patterns. Flag can be specified multiple times.
 Examples:
  -rule="/path/to/file". Path to a single file with alerting rules
- -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder, 
+ -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder,
 absolute path to all .yaml files in root.
 Rule files may contain %{ENV_VAR} placeholders, which are substituted by the corresponding env vars.`)
 
@@ -41,7 +41,7 @@ Rule files may contain %{ENV_VAR} placeholders, which are substituted by the cor
 	validateExpressions = flag.Bool("rule.validateExpressions", true, "Whether to validate rules expressions via MetricsQL engine")
 	externalURL         = flag.String("external.url", "", "External URL is used as alert's source for sent alerts to the notifier")
 	externalAlertSource = flag.String("external.alert.source", "", `External Alert Source allows to override the Source link for alerts sent to AlertManager for cases where you want to build a custom link to Grafana, Prometheus or any other service.
-eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|pathEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used`)
+eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|queryEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used`)
 	externalLabels = flagutil.NewArray("external.label", "Optional label in the form 'name=value' to add to all generated recording rules and alerts. "+
 		"Pass multiple -label flags in order to add multiple label sets.")
 
diff --git a/deployment/docker/docker-compose.yml b/deployment/docker/docker-compose.yml
index 736d3f4bd..31869646c 100644
--- a/deployment/docker/docker-compose.yml
+++ b/deployment/docker/docker-compose.yml
@@ -70,8 +70,7 @@ services:
       - '--rule=/etc/alerts/*.yml'
       # display source of alerts in grafana
       - '-external.url=http://127.0.0.1:3000' #grafana outside container
-      - '--external.alert.source=explore?orgId=1&left=["now-1h","now","VictoriaMetrics",{"expr":"{{$$expr|quotesEscape|pathEscape}}"},{"mode":"Metrics"},{"ui":[true,true,true,"none"]}]' ## when copypaste the line be aware of '$$' for escaping in '$expr'
-    networks:
+      - '--external.alert.source=explore?orgId=1&left=["now-1h","now","VictoriaMetrics",{"expr":"{{$$expr|quotesEscape|crlfEscape|queryEscape}}"},{"mode":"Metrics"},{"ui":[true,true,true,"none"]}]' ## when copypaste the line be aware of '$$' for escaping in '$expr'    networks:
       - vm_net
     restart: always
   alertmanager:
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7a4fb6f23..fd48af9e8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -11,9 +11,11 @@
 * FATURE: vmagent: accept `scrape_offset` option at `scrape_config`. This option may be useful when scrapes must start at the specified offset of every scrape interval. See [these docs](https://victoriametrics.github.io/vmagent.html#troubleshooting) for details.
 * FEATURE: vmauth: allow using regexp paths in `url_map`. See [this issue](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1112) for details.
 
-
 * BUGFIX: vmagent: prevent from high CPU usage bug during failing scrapes with small `scrape_timeout` (less than a few seconds).
-* BUGFIX: vmagent: reduce memory usage when Kubernetes service discovery is used in big number of distinct jobs by sharing the cache. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1113
+* BUGFIX: vmagent: reduce memory usage when Kubernetes service discovery is used in big number of distinct scrape config jobs by sharing Kubernetes object cache. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1113
+* BUGFIX: vmagent: apply `sample_limit` only after `metric_relabel_configs` are applied as Prometheus does. Previously the `sample_limit` was applied before metrics relabeling.
+* BUGFIX: vmagent: properly apply `tls_config`, `basic_auth` and `bearer_token` to proxy connections if `proxy_url` option is set. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1116
+* BUGFIX: vmagent: properly scrape targets via https proxy specified in `proxy_url` if `insecure_skip_verify` flag isn't set in `tls_config` section. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1116
 * BUGFUX: avoid `duplicate time series` error if `prometheus_buckets()` covers a time range with distinct set of buckets.
 * BUGFIX: prevent exponent overflow when processing extremely small values close to zero such as `2.964393875E-314`. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1114
 
diff --git a/docs/vmalert.md b/docs/vmalert.md
index adfed9bf2..5a286c289 100644
--- a/docs/vmalert.md
+++ b/docs/vmalert.md
@@ -16,7 +16,7 @@ rules against configured address.
 * Lightweight without extra dependencies.
 
 ### Limitations:
-* `vmalert` execute queries against remote datasource which has reliability risks because of network. 
+* `vmalert` execute queries against remote datasource which has reliability risks because of network.
 It is recommended to configure alerts thresholds and rules expressions with understanding that network request
 may fail;
 * by default, rules execution is sequential within one group, but persisting of execution results to remote
@@ -37,7 +37,7 @@ The build binary will be placed to `VictoriaMetrics/bin` folder.
 To start using `vmalert` you will need the following things:
 * list of rules - PromQL/MetricsQL expressions to execute;
 * datasource address - reachable VictoriaMetrics instance for rules execution;
-* notifier address - reachable [Alert Manager](https://github.com/prometheus/alertmanager) instance for processing, 
+* notifier address - reachable [Alert Manager](https://github.com/prometheus/alertmanager) instance for processing,
 aggregating alerts and sending notifications.
 * remote write address - [remote write](https://prometheus.io/docs/prometheus/latest/storage/#remote-storage-integrations)
 compatible storage address for storing recording rules results and alerts state in for of timeseries. This is optional.
@@ -56,11 +56,11 @@ Then configure `vmalert` accordingly:
 ```
 
 If you run multiple `vmalert` services for the same datastore or AlertManager - do not forget
-to specify different `external.label` flags in order to define which `vmalert` generated rules or alerts. 
+to specify different `external.label` flags in order to define which `vmalert` generated rules or alerts.
 
-Configuration for [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) 
-and [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) rules is very 
-similar to Prometheus rules and configured using YAML. Configuration examples may be found 
+Configuration for [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/)
+and [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) rules is very
+similar to Prometheus rules and configured using YAML. Configuration examples may be found
 in [testdata](https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/app/vmalert/config/testdata) folder.
 Every `rule` belongs to `group` and every configuration file may contain arbitrary number of groups:
 ```yaml
@@ -79,7 +79,7 @@ name: <string>
 [ interval: <duration> | default = global.evaluation_interval ]
 
 # How many rules execute at once. Increasing concurrency may speed
-# up round execution speed. 
+# up round execution speed.
 [ concurrency: <integer> | default = 1 ]
 
 # Optional type for expressions inside the rules. Supported values: "graphite" and "prometheus".
@@ -93,15 +93,15 @@ rules:
 #### Rules
 
 There are two types of Rules:
-* [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) - 
+* [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) -
 Alerting rules allows to define alert conditions via [MetricsQL](https://victoriametrics.github.io/MetricsQL.html)
 and to send notifications about firing alerts to [Alertmanager](https://github.com/prometheus/alertmanager).
-* [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) - 
-Recording rules allow you to precompute frequently needed or computationally expensive expressions 
+* [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) -
+Recording rules allow you to precompute frequently needed or computationally expensive expressions
 and save their result as a new set of time series.
 
 `vmalert` forbids to define duplicates - rules with the same combination of name, expression and labels
-within one group. 
+within one group.
 
 ##### Alerting rules
 
@@ -130,7 +130,7 @@ labels:
 # Annotations to add to each alert.
 annotations:
   [ <labelname>: <tmpl_string> ]
-``` 
+```
 
 ##### Recording rules
 
@@ -158,17 +158,17 @@ For recording rules to work `-remoteWrite.url` must specified.
 
 #### Alerts state on restarts
 
-`vmalert` has no local storage, so alerts state is stored in the process memory. Hence, after reloading of `vmalert` 
+`vmalert` has no local storage, so alerts state is stored in the process memory. Hence, after reloading of `vmalert`
 the process alerts state will be lost. To avoid this situation, `vmalert` should be configured via the following flags:
-* `-remoteWrite.url` - URL to VictoriaMetrics (Single) or VMInsert (Cluster). `vmalert` will persist alerts state 
-into the configured address in the form of time series named `ALERTS` and `ALERTS_FOR_STATE` via remote-write protocol. 
-These are regular time series and may be queried from VM just as any other time series. 
+* `-remoteWrite.url` - URL to VictoriaMetrics (Single) or VMInsert (Cluster). `vmalert` will persist alerts state
+into the configured address in the form of time series named `ALERTS` and `ALERTS_FOR_STATE` via remote-write protocol.
+These are regular time series and may be queried from VM just as any other time series.
 The state stored to the configured address on every rule evaluation.
-* `-remoteRead.url` - URL to VictoriaMetrics (Single) or VMSelect (Cluster). `vmalert` will try to restore alerts state 
+* `-remoteRead.url` - URL to VictoriaMetrics (Single) or VMSelect (Cluster). `vmalert` will try to restore alerts state
 from configured address by querying time series with name `ALERTS_FOR_STATE`.
 
 Both flags are required for the proper state restoring. Restore process may fail if time series are missing
-in configured `-remoteRead.url`, weren't updated in the last `1h` or received state doesn't match current `vmalert` 
+in configured `-remoteRead.url`, weren't updated in the last `1h` or received state doesn't match current `vmalert`
 rules configuration.
 
 
@@ -232,7 +232,7 @@ The shortlist of configuration flags is the following:
     	How often to evaluate the rules (default 1m0s)
   -external.alert.source string
     	External Alert Source allows to override the Source link for alerts sent to AlertManager for cases where you want to build a custom link to Grafana, Prometheus or any other service.
-    	eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|pathEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used
+    	eg. 'explore?orgId=1&left=[\"now-1h\",\"now\",\"VictoriaMetrics\",{\"expr\": \"{{$expr|quotesEscape|crlfEscape|queryEscape}}\"},{\"mode\":\"Metrics\"},{\"ui\":[true,true,true,\"none\"]}]'.If empty '/api/v1/:groupID/alertID/status' is used
   -external.label array
     	Optional label in the form 'name=value' to add to all generated recording rules and alerts. Pass multiple -label flags in order to add multiple label sets.
     	Supports array of values separated by comma or specified via multiple flags.
@@ -348,11 +348,11 @@ The shortlist of configuration flags is the following:
   -remoteWrite.url string
     	Optional URL to Victoria Metrics or VMInsert where to persist alerts state and recording rules results in form of timeseries. E.g. http://127.0.0.1:8428
   -rule array
-    	Path to the file with alert rules. 
-    	Supports patterns. Flag can be specified multiple times. 
+    	Path to the file with alert rules.
+    	Supports patterns. Flag can be specified multiple times.
     	Examples:
     	 -rule="/path/to/file". Path to a single file with alerting rules
-    	 -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder, 
+    	 -rule="dir/*.yaml" -rule="/*.yaml". Relative path to all .yaml files in "dir" folder,
     	absolute path to all .yaml files in root.
     	Rule files may contain %{ENV_VAR} placeholders, which are substituted by the corresponding env vars.
     	Supports array of values separated by comma or specified via multiple flags.
@@ -370,7 +370,7 @@ The shortlist of configuration flags is the following:
     	Show VictoriaMetrics version
 ```
 
-Pass `-help` to `vmalert` in order to see the full list of supported 
+Pass `-help` to `vmalert` in order to see the full list of supported
 command-line flags with their descriptions.
 
 To reload configuration without `vmalert` restart send SIGHUP signal
@@ -379,13 +379,13 @@ or send GET request to `/-/reload` endpoint.
 ### Contributing
 
 `vmalert` is mostly designed and built by VictoriaMetrics community.
-Feel free to share your experience and ideas for improving this 
+Feel free to share your experience and ideas for improving this
 software. Please keep simplicity as the main priority.
 
 ### How to build from sources
 
-It is recommended using 
-[binary releases](https://github.com/VictoriaMetrics/VictoriaMetrics/releases) 
+It is recommended using
+[binary releases](https://github.com/VictoriaMetrics/VictoriaMetrics/releases)
 - `vmalert` is located in `vmutils-*` archives there.
 
 
diff --git a/go.mod b/go.mod
index dd0ac52ac..f1721e98c 100644
--- a/go.mod
+++ b/go.mod
@@ -7,7 +7,7 @@ require (
 
 	// Do not use the original github.com/valyala/fasthttp because of issues
 	// like https://github.com/valyala/fasthttp/commit/996610f021ff45fdc98c2ce7884d5fa4e7f9199b
-	github.com/VictoriaMetrics/fasthttp v1.0.13
+	github.com/VictoriaMetrics/fasthttp v1.0.14
 	github.com/VictoriaMetrics/metrics v1.15.2
 	github.com/VictoriaMetrics/metricsql v0.14.0
 	github.com/aws/aws-sdk-go v1.37.26
diff --git a/go.sum b/go.sum
index 7c821a6c5..0396ff841 100644
--- a/go.sum
+++ b/go.sum
@@ -82,8 +82,8 @@ github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWX
 github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI=
 github.com/VictoriaMetrics/fastcache v1.5.8 h1:XW+YVx9lEXITBVv35ugK9OyotdNJVcbza69o3jmqWuI=
 github.com/VictoriaMetrics/fastcache v1.5.8/go.mod h1:SiMZNgwEPJ9qWLshu9tyuE6bKc9ZWYhcNV/L7jurprQ=
-github.com/VictoriaMetrics/fasthttp v1.0.13 h1:5JNS4vSPdN4QyfcpAg3Y1Wznf0uXEuSOFpeIlFw3MgM=
-github.com/VictoriaMetrics/fasthttp v1.0.13/go.mod h1:3SeUL4zwB/p/a9aEeRc6gdlbrtNHXBJR6N376EgiSHU=
+github.com/VictoriaMetrics/fasthttp v1.0.14 h1:iWCdHg7JQ1SO0xvPAgw3QFpFT3he+Ugdshg+1clN6CQ=
+github.com/VictoriaMetrics/fasthttp v1.0.14/go.mod h1:eDVgYyGts3xXpYpVGDxQ3ZlQKW5TSvOqfc9FryjH1JA=
 github.com/VictoriaMetrics/metrics v1.12.2/go.mod h1:Z1tSfPfngDn12bTfZSCqArT3OPY3u88J12hSoOhuiRE=
 github.com/VictoriaMetrics/metrics v1.15.2 h1:w/GD8L9tm+gvx1oZvAofRRXwammiicdI0jgLghA2Gdo=
 github.com/VictoriaMetrics/metrics v1.15.2/go.mod h1:Z1tSfPfngDn12bTfZSCqArT3OPY3u88J12hSoOhuiRE=
@@ -507,7 +507,6 @@ github.com/klauspost/compress v1.4.0/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0
 github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
 github.com/klauspost/compress v1.10.7/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
 github.com/klauspost/compress v1.11.0/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
-github.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
 github.com/klauspost/compress v1.11.12 h1:famVnQVu7QwryBN4jNseQdUKES71ZAOnB6UQQJPZvqk=
 github.com/klauspost/compress v1.11.12/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
 github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
diff --git a/lib/promauth/config.go b/lib/promauth/config.go
index 184f872bf..f80b15ae2 100644
--- a/lib/promauth/config.go
+++ b/lib/promauth/config.go
@@ -65,13 +65,16 @@ func (ac *Config) tlsCertificateString() string {
 // NewTLSConfig returns new TLS config for the given ac.
 func (ac *Config) NewTLSConfig() *tls.Config {
 	tlsCfg := &tls.Config{
-		RootCAs:            ac.TLSRootCA,
 		ClientSessionCache: tls.NewLRUClientSessionCache(0),
 	}
+	if ac == nil {
+		return tlsCfg
+	}
 	if ac.TLSCertificate != nil {
 		// Do not set tlsCfg.GetClientCertificate, since tlsCfg.Certificates should work OK.
 		tlsCfg.Certificates = []tls.Certificate{*ac.TLSCertificate}
 	}
+	tlsCfg.RootCAs = ac.TLSRootCA
 	tlsCfg.ServerName = ac.TLSServerName
 	tlsCfg.InsecureSkipVerify = ac.TLSInsecureSkipVerify
 	return tlsCfg
diff --git a/lib/promscrape/client.go b/lib/promscrape/client.go
index 05a12f12f..958c06055 100644
--- a/lib/promscrape/client.go
+++ b/lib/promscrape/client.go
@@ -67,7 +67,7 @@ func newClient(sw *ScrapeWork) *client {
 			host += ":443"
 		}
 	}
-	dialFunc, err := newStatDialFunc(sw.ProxyURL, tlsCfg)
+	dialFunc, err := newStatDialFunc(sw.ProxyURL, sw.AuthConfig)
 	if err != nil {
 		logger.Fatalf("cannot create dial func: %s", err)
 	}
diff --git a/lib/promscrape/discovery/kubernetes/api_watcher.go b/lib/promscrape/discovery/kubernetes/api_watcher.go
index 10066dea6..b997f2832 100644
--- a/lib/promscrape/discovery/kubernetes/api_watcher.go
+++ b/lib/promscrape/discovery/kubernetes/api_watcher.go
@@ -159,9 +159,7 @@ func (aw *apiWatcher) startWatcherForURL(role, apiURL string, parseObject parseO
 	aw.wg.Add(1)
 	go func() {
 		defer aw.wg.Done()
-		logger.Infof("started watcher for %q", apiURL)
 		uw.watchForUpdates()
-		logger.Infof("stopped watcher for %q", apiURL)
 		uw.objectsByKey.decRef()
 
 		aw.mu.Lock()
@@ -291,6 +289,7 @@ func (uw *urlWatcher) reloadObjects() string {
 		}
 		return ""
 	}
+	logger.Infof("loaded %d objects from %q", len(objectsByKey), requestURL)
 	uw.objectsByKey.reload(objectsByKey)
 	swosByKey := make(map[string][]interface{})
 	for k, o := range objectsByKey {
diff --git a/lib/promscrape/discoveryutils/client.go b/lib/promscrape/discoveryutils/client.go
index 65b514d63..ecddf92cc 100644
--- a/lib/promscrape/discoveryutils/client.go
+++ b/lib/promscrape/discoveryutils/client.go
@@ -66,7 +66,7 @@ func NewClient(apiServer string, ac *promauth.Config, proxyURL proxy.URL) (*Clie
 
 	hostPort := string(u.Host())
 	isTLS := string(u.Scheme()) == "https"
-	if isTLS && ac != nil {
+	if isTLS {
 		tlsCfg = ac.NewTLSConfig()
 	}
 	if !strings.Contains(hostPort, ":") {
@@ -77,7 +77,7 @@ func NewClient(apiServer string, ac *promauth.Config, proxyURL proxy.URL) (*Clie
 		hostPort = net.JoinHostPort(hostPort, port)
 	}
 	if dialFunc == nil {
-		dialFunc, err = proxyURL.NewDialFunc(tlsCfg)
+		dialFunc, err = proxyURL.NewDialFunc(ac)
 		if err != nil {
 			return nil, err
 		}
diff --git a/lib/promscrape/scrapework.go b/lib/promscrape/scrapework.go
index e5e28ff42..003b0348a 100644
--- a/lib/promscrape/scrapework.go
+++ b/lib/promscrape/scrapework.go
@@ -290,27 +290,15 @@ func (sw *scrapeWork) scrapeInternal(scrapeTimestamp, realTimestamp int64) error
 	srcRows := wc.rows.Rows
 	samplesScraped := len(srcRows)
 	scrapedSamples.Update(float64(samplesScraped))
-	if sw.Config.SampleLimit > 0 && samplesScraped > sw.Config.SampleLimit {
-		srcRows = srcRows[:0]
-		up = 0
-		scrapesSkippedBySampleLimit.Inc()
-	}
-	samplesPostRelabeling := 0
 	for i := range srcRows {
 		sw.addRowToTimeseries(wc, &srcRows[i], scrapeTimestamp, true)
-		if len(wc.labels) > 40000 {
-			// Limit the maximum size of wc.writeRequest.
-			// This should reduce memory usage when scraping targets with millions of metrics and/or labels.
-			// For example, when scraping /federate handler from Prometheus - see https://prometheus.io/docs/prometheus/latest/federation/
-			samplesPostRelabeling += len(wc.writeRequest.Timeseries)
-			sw.updateSeriesAdded(wc)
-			startTime := time.Now()
-			sw.PushData(&wc.writeRequest)
-			pushDataDuration.UpdateDuration(startTime)
-			wc.resetNoRows()
-		}
 	}
-	samplesPostRelabeling += len(wc.writeRequest.Timeseries)
+	samplesPostRelabeling := len(wc.writeRequest.Timeseries)
+	if sw.Config.SampleLimit > 0 && samplesPostRelabeling > sw.Config.SampleLimit {
+		wc.resetNoRows()
+		up = 0
+		scrapesSkippedBySampleLimit.Inc()
+	}
 	sw.updateSeriesAdded(wc)
 	seriesAdded := sw.finalizeSeriesAdded(samplesPostRelabeling)
 	sw.addAutoTimeseries(wc, "up", float64(up), scrapeTimestamp)
diff --git a/lib/promscrape/statconn.go b/lib/promscrape/statconn.go
index 2fefaf420..d8bbdce9f 100644
--- a/lib/promscrape/statconn.go
+++ b/lib/promscrape/statconn.go
@@ -2,7 +2,6 @@ package promscrape
 
 import (
 	"context"
-	"crypto/tls"
 	"fmt"
 	"net"
 	"sync"
@@ -10,6 +9,7 @@ import (
 	"time"
 
 	"github.com/VictoriaMetrics/VictoriaMetrics/lib/netutil"
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 	"github.com/VictoriaMetrics/VictoriaMetrics/lib/proxy"
 	"github.com/VictoriaMetrics/fasthttp"
 	"github.com/VictoriaMetrics/metrics"
@@ -49,8 +49,8 @@ var (
 	stdDialerOnce sync.Once
 )
 
-func newStatDialFunc(proxyURL proxy.URL, tlsConfig *tls.Config) (fasthttp.DialFunc, error) {
-	dialFunc, err := proxyURL.NewDialFunc(tlsConfig)
+func newStatDialFunc(proxyURL proxy.URL, ac *promauth.Config) (fasthttp.DialFunc, error) {
+	dialFunc, err := proxyURL.NewDialFunc(ac)
 	if err != nil {
 		return nil, err
 	}
diff --git a/lib/proxy/proxy.go b/lib/proxy/proxy.go
index bb3c339ef..0bb6f9e8d 100644
--- a/lib/proxy/proxy.go
+++ b/lib/proxy/proxy.go
@@ -7,9 +7,11 @@ import (
 	"fmt"
 	"net"
 	"net/url"
+	"strings"
 	"time"
 
 	"github.com/VictoriaMetrics/VictoriaMetrics/lib/netutil"
+	"github.com/VictoriaMetrics/VictoriaMetrics/lib/promauth"
 	"github.com/VictoriaMetrics/fasthttp"
 )
 
@@ -48,8 +50,8 @@ func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {
 	return nil
 }
 
-// NewDialFunc returns dial func for the given pu and tlsConfig.
-func (u *URL) NewDialFunc(tlsConfig *tls.Config) (fasthttp.DialFunc, error) {
+// NewDialFunc returns dial func for the given u and ac.
+func (u *URL) NewDialFunc(ac *promauth.Config) (fasthttp.DialFunc, error) {
 	if u == nil || u.url == nil {
 		return defaultDialFunc, nil
 	}
@@ -57,20 +59,34 @@ func (u *URL) NewDialFunc(tlsConfig *tls.Config) (fasthttp.DialFunc, error) {
 	if pu.Scheme != "http" && pu.Scheme != "https" {
 		return nil, fmt.Errorf("unknown scheme=%q for proxy_url=%q, must be http or https", pu.Scheme, pu)
 	}
+	isTLS := pu.Scheme == "https"
+	proxyAddr := addMissingPort(pu.Host, isTLS)
 	var authHeader string
+	if ac != nil {
+		authHeader = ac.Authorization
+	}
 	if pu.User != nil && len(pu.User.Username()) > 0 {
 		userPasswordEncoded := base64.StdEncoding.EncodeToString([]byte(pu.User.String()))
-		authHeader = "Proxy-Authorization: Basic " + userPasswordEncoded + "\r\n"
+		authHeader = "Basic " + userPasswordEncoded
+	}
+	if authHeader != "" {
+		authHeader = "Proxy-Authorization: " + authHeader + "\r\n"
 	}
+	tlsCfg := ac.NewTLSConfig()
 	dialFunc := func(addr string) (net.Conn, error) {
-		proxyConn, err := defaultDialFunc(pu.Host)
+		proxyConn, err := defaultDialFunc(proxyAddr)
 		if err != nil {
 			return nil, fmt.Errorf("cannot connect to proxy %q: %w", pu, err)
 		}
-		if pu.Scheme == "https" {
-			proxyConn = tls.Client(proxyConn, tlsConfig)
+		if isTLS {
+			tlsCfgLocal := tlsCfg
+			if !tlsCfgLocal.InsecureSkipVerify && tlsCfgLocal.ServerName == "" {
+				tlsCfgLocal = tlsCfgLocal.Clone()
+				tlsCfgLocal.ServerName = tlsServerName(addr)
+			}
+			proxyConn = tls.Client(proxyConn, tlsCfgLocal)
 		}
-		conn, err := sendConnectRequest(proxyConn, addr, authHeader)
+		conn, err := sendConnectRequest(proxyConn, proxyAddr, addr, authHeader)
 		if err != nil {
 			_ = proxyConn.Close()
 			return nil, fmt.Errorf("error when sending CONNECT request to proxy %q: %w", pu, err)
@@ -80,6 +96,25 @@ func (u *URL) NewDialFunc(tlsConfig *tls.Config) (fasthttp.DialFunc, error) {
 	return dialFunc, nil
 }
 
+func addMissingPort(addr string, isTLS bool) string {
+	if strings.IndexByte(addr, ':') >= 0 {
+		return addr
+	}
+	port := "80"
+	if isTLS {
+		port = "443"
+	}
+	return addr + ":" + port
+}
+
+func tlsServerName(addr string) string {
+	host, _, err := net.SplitHostPort(addr)
+	if err != nil {
+		return addr
+	}
+	return host
+}
+
 func defaultDialFunc(addr string) (net.Conn, error) {
 	network := "tcp4"
 	if netutil.TCP6Enabled() {
@@ -90,8 +125,8 @@ func defaultDialFunc(addr string) (net.Conn, error) {
 }
 
 // sendConnectRequest sends CONNECT request to proxyConn for the given addr and authHeader and returns the established connection to dstAddr.
-func sendConnectRequest(proxyConn net.Conn, dstAddr, authHeader string) (net.Conn, error) {
-	req := "CONNECT " + dstAddr + " HTTP/1.1\r\nHost: " + dstAddr + "\r\n" + authHeader + "\r\n"
+func sendConnectRequest(proxyConn net.Conn, proxyAddr, dstAddr, authHeader string) (net.Conn, error) {
+	req := "CONNECT " + dstAddr + " HTTP/1.1\r\nHost: " + proxyAddr + "\r\n" + authHeader + "\r\n"
 	if _, err := proxyConn.Write([]byte(req)); err != nil {
 		return nil, fmt.Errorf("cannot send CONNECT request for dstAddr=%q: %w", dstAddr, err)
 	}
diff --git a/vendor/github.com/VictoriaMetrics/fasthttp/go.mod b/vendor/github.com/VictoriaMetrics/fasthttp/go.mod
index e738de9b0..155f42daa 100644
--- a/vendor/github.com/VictoriaMetrics/fasthttp/go.mod
+++ b/vendor/github.com/VictoriaMetrics/fasthttp/go.mod
@@ -3,7 +3,7 @@ module github.com/VictoriaMetrics/fasthttp
 go 1.13
 
 require (
-	github.com/klauspost/compress v1.11.3
+	github.com/klauspost/compress v1.11.12
 	github.com/valyala/bytebufferpool v1.0.0
 	github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a
 )
diff --git a/vendor/github.com/VictoriaMetrics/fasthttp/go.sum b/vendor/github.com/VictoriaMetrics/fasthttp/go.sum
index 6fc4f7e42..6b6e7262a 100644
--- a/vendor/github.com/VictoriaMetrics/fasthttp/go.sum
+++ b/vendor/github.com/VictoriaMetrics/fasthttp/go.sum
@@ -1,5 +1,5 @@
-github.com/klauspost/compress v1.11.3 h1:dB4Bn0tN3wdCzQxnS8r06kV74qN/TAfaIS0bVE8h3jc=
-github.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
+github.com/klauspost/compress v1.11.12 h1:famVnQVu7QwryBN4jNseQdUKES71ZAOnB6UQQJPZvqk=
+github.com/klauspost/compress v1.11.12/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
 github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
 github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
 github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a h1:0R4NLDRDZX6JcmhJgXi5E4b8Wg84ihbmUKp/GvSPEzc=
diff --git a/vendor/modules.txt b/vendor/modules.txt
index fec7c5692..af86f5e9f 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -13,7 +13,7 @@ cloud.google.com/go/storage
 # github.com/VictoriaMetrics/fastcache v1.5.8
 ## explicit
 github.com/VictoriaMetrics/fastcache
-# github.com/VictoriaMetrics/fasthttp v1.0.13
+# github.com/VictoriaMetrics/fasthttp v1.0.14
 ## explicit
 github.com/VictoriaMetrics/fasthttp
 github.com/VictoriaMetrics/fasthttp/fasthttputil


Test patch:
diff --git a/lib/promscrape/scrapework_test.go b/lib/promscrape/scrapework_test.go
index 74b6f67e8..79e6cb6ce 100644
--- a/lib/promscrape/scrapework_test.go
+++ b/lib/promscrape/scrapework_test.go
@@ -332,7 +332,7 @@ func TestScrapeWorkScrapeInternalSuccess(t *testing.T) {
 		up 0 123
 		scrape_samples_scraped 2 123
 		scrape_duration_seconds 0 123
-		scrape_samples_post_metric_relabeling 0 123
+		scrape_samples_post_metric_relabeling 2 123
 		scrape_series_added 0 123
 	`)
 }