Merge "Change to file.managed to pick up changes when the key is modified"
diff --git a/.kitchen.yml b/.kitchen.yml
index 8513cd7..7e8343d 100644
--- a/.kitchen.yml
+++ b/.kitchen.yml
@@ -38,7 +38,7 @@
 platforms:
   - name: <%=ENV['PLATFORM'] ||  'saltstack-ubuntu-xenial-salt-stable' %>
     driver_config:
-      image: <%=ENV['PLATFORM'] || 'epcim/salt:saltstack-ubuntu-xenial-salt-stable'%>
+      image: <%=ENV['PLATFORM'] || 'docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-stable/salt:2018_11_19'%>
       platform: ubuntu
 
 suites:
diff --git a/.travis.yml b/.travis.yml
index 42b967e..d2a1609 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,32 +9,21 @@
   - pip install PyYAML
   - pip install virtualenv
   - |
-    test -e Gemfile || cat <<EOF > Gemfile
-    source 'https://rubygems.org'
-    gem 'rake'
-    gem 'test-kitchen'
-    gem 'kitchen-docker'
-    gem 'kitchen-inspec'
-    gem 'inspec'
-    gem 'kitchen-salt', :git => 'https://github.com/salt-formulas/kitchen-salt.git'
+    if [ ! -e Gemfile ]; then
+      curl -s -o ./Gemfile 'https://gerrit.mcp.mirantis.com/gitweb?p=salt-formulas/salt-formulas-scripts.git;a=blob_plain;f=Gemfile;hb=refs/heads/master'
+    fi
   - bundle install
 
 env:
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2016.3 SUITE=ceph-client-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2016.3 SUITE=ceph-mon-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2016.3 SUITE=ceph-osd-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2017.7 SUITE=ceph-client-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2017.7 SUITE=ceph-mon-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2017.7 SUITE=ceph-osd-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2018.3 SUITE=ceph-client-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2018.3 SUITE=ceph-mon-single
-    - PLATFORM=epcim/salt:saltstack-ubuntu-xenial-salt-2018.3 SUITE=ceph-osd-single
-#    - PLATFORM=epcim/salt:saltstack-ubuntu-bionic-salt-2017.7 SUITE=ceph-client-single
-#    - PLATFORM=epcim/salt:saltstack-ubuntu-bionic-salt-2017.7 SUITE=ceph-mon-single
-#    - PLATFORM=epcim/salt:saltstack-ubuntu-bionic-salt-2017.7 SUITE=ceph-osd-single
-#    - PLATFORM=epcim/salt:saltstack-ubuntu-bionic-salt-2018.3 SUITE=ceph-client-single
-#    - PLATFORM=epcim/salt:saltstack-ubuntu-bionic-salt-2018.3 SUITE=ceph-mon-single
-#    - PLATFORM=epcim/salt:saltstack-ubuntu-bionic-salt-2018.3 SUITE=ceph-osd-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-2016.3/salt:2018_11_19 SUITE=ceph-client-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-2016.3/salt:2018_11_19 SUITE=ceph-mon-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-2016.3/salt:2018_11_19 SUITE=ceph-osd-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-2017.7/salt:2018_11_19 SUITE=ceph-client-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-2017.7/salt:2018_11_19 SUITE=ceph-mon-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-2017.7/salt:2018_11_19 SUITE=ceph-osd-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-stable/salt:2018_11_19 SUITE=ceph-client-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-stable/salt:2018_11_19 SUITE=ceph-mon-single
+    - PLATFORM=docker-dev-local.docker.mirantis.net/epcim/salt/saltstack-ubuntu-xenial-salt-stable/salt:2018_11_19 SUITE=ceph-osd-single
 
 before_script:
   - set -o pipefail
diff --git a/Makefile b/Makefile
index d166862..fb69046 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,11 @@
 JOBS := 1
 endif
 
+ifeq (,$(wildcard ./.kitchen.openstack.yml))
+KITCHEN_LOCAL_YAML?=.kitchen.openstack.yml
+else
 KITCHEN_LOCAL_YAML?=.kitchen.yml
+endif
 KITCHEN_OPTS?="--concurrency=$(JOBS)"
 KITCHEN_OPTS_CREATE?=""
 KITCHEN_OPTS_CONVERGE?=""
diff --git a/README.rst b/README.rst
index bc8e2b6..e4488fa 100644
--- a/README.rst
+++ b/README.rst
@@ -357,6 +357,21 @@
               enabled: false
 
 
+In case some custom block devices should be used (like loop devices for testing purpose),
+it is needed to indicate proper partition prefix.
+
+.. code-block:: yaml
+
+    ceph:
+      osd:
+        backend:
+          bluestore:
+            disks:
+            - dev: /dev/loop20
+              block_db: /dev/loop21
+              data_partition_prefix: 'p'
+
+
 Ceph client roles - ...Deprecated - use ceph:common instead
 --------------------------------------------------------
 
@@ -453,6 +468,7 @@
         swift:
           versioning:
             enabled: true
+          enforce_content_length: true
 
 
 Ceph setup role
@@ -678,12 +694,21 @@
         space_used_critical_threshold: 0.85
         apply_latency_threshold: 0.007
         commit_latency_threshold: 0.7
-        pool_space_used_utilization_warning_threshold: 0.75
-        pool_space_used_critical_threshold: 0.85
-        pool_write_ops_threshold: 200
-        pool_write_bytes_threshold: 70000000
-        pool_read_bytes_threshold: 70000000
-        pool_read_ops_threshold: 1000
+        pool:
+          vms:
+            pool_space_used_utilization_warning_threshold: 0.75
+            pool_space_used_critical_threshold: 0.85
+            pool_write_ops_threshold: 200
+            pool_write_bytes_threshold: 70000000
+            pool_read_bytes_threshold: 70000000
+            pool_read_ops_threshold: 1000
+          images:
+            pool_space_used_utilization_warning_threshold: 0.50
+            pool_space_used_critical_threshold: 0.95
+            pool_write_ops_threshold: 100
+            pool_write_bytes_threshold: 50000000
+            pool_read_bytes_threshold: 50000000
+            pool_read_ops_threshold: 500
 
 Ceph monitor backups
 --------------------
diff --git a/ceph/backup.sls b/ceph/backup.sls
index e590490..7963e5c 100644
--- a/ceph/backup.sls
+++ b/ceph/backup.sls
@@ -63,6 +63,7 @@
   - hour: 2
 {%- endif %}
 {%- else %}
+  - minute: 0
   - hour: 2
 {%- endif %}
   - require:
@@ -163,6 +164,7 @@
   - hour: 2
 {%- endif %}
 {%- else %}
+  - minute: 0
   - hour: 2
 {%- endif %}
   - require:
diff --git a/ceph/common.sls b/ceph/common.sls
index 265d1f0..c6067b0 100644
--- a/ceph/common.sls
+++ b/ceph/common.sls
@@ -25,6 +25,8 @@
 common_config:
   file.managed:
   - name: {{ common.prefix_dir }}/etc/ceph/{{ common.get('cluster_name', 'ceph') }}.conf
+  - user: ceph
+  - group: ceph
   - source: salt://ceph/files/{{ common.version }}/ceph.conf.{{ grains.os_family }}
   - template: jinja
   {% if not common.get('container_mode', False) %}
@@ -71,5 +73,3 @@
 {%- endif %}
 
 {%- endfor %}
-
-
diff --git a/ceph/files/backup/ceph-backup-client-runner-call.sh b/ceph/files/backup/ceph-backup-client-runner-call.sh
index 51a0d8d..74d6e92 100644
--- a/ceph/files/backup/ceph-backup-client-runner-call.sh
+++ b/ceph/files/backup/ceph-backup-client-runner-call.sh
@@ -93,7 +93,7 @@
     echo "----------------------------"
     echo "Cleanup. Keeping only $KEEP full backups"
     AGE=$(($FULLBACKUPLIFE * $KEEP / 60))
-    find $BACKUPDIR -maxdepth 1 -type d -mmin +$AGE -execdir echo "removing: "$BACKUPDIR/{} \; -execdir rm -rf $BACKUPDIR/{} \;
+    find $BACKUPDIR/$HOSTNAME -maxdepth 1 -type f -mmin +$AGE -execdir echo "removing: "$BACKUPDIR/$HOSTNAME/{} \; -execdir rm -rf $BACKUPDIR/$HOSTNAME/{} \;
     {%- else %}
     echo "----------------------------"
     echo "Cleanup. Keeping only $KEEP full backups"
diff --git a/ceph/files/grafana_dashboards/ceph_pools_prometheus.json b/ceph/files/grafana_dashboards/ceph_pools_prometheus.json
index 74ca5de..61e2780 100644
--- a/ceph/files/grafana_dashboards/ceph_pools_prometheus.json
+++ b/ceph/files/grafana_dashboards/ceph_pools_prometheus.json
@@ -158,7 +158,7 @@
           "steppedLine": false,
           "targets": [
             {
-              "expr": "avg(ceph_pool_usage_max_avail{name=\"$pool\"}) - avg(ceph_pool_usage_bytes_used{name=\"$pool\"})",
+              "expr": "avg(ceph_pool_usage_max_avail{name=\"$pool\"})",
               "format": "time_series",
               "interval": "",
               "intervalFactor": 1,
@@ -178,7 +178,7 @@
               "step": 60
             },
             {
-              "expr": "avg(ceph_pool_usage_max_avail{name=\"$pool\"})",
+              "expr": "avg(ceph_pool_usage_max_avail{name=\"$pool\"}) + avg(ceph_pool_usage_bytes_used{name=\"$pool\"})",
               "format": "time_series",
               "interval": "",
               "intervalFactor": 1,
@@ -284,7 +284,7 @@
           "tableColumn": "",
           "targets": [
             {
-              "expr": "avg(ceph_pool_usage_bytes_used{name=\"$pool\"}) / avg(ceph_pool_usage_max_avail{name=\"$pool\"})",
+              "expr": "avg(ceph_pool_usage_bytes_used{name=\"$pool\"}) / (avg(ceph_pool_usage_max_avail{name=\"$pool\"}) + avg(ceph_pool_usage_bytes_used{name=\"$pool\"}))",
               "format": "time_series",
               "interval": "",
               "intervalFactor": 1,
diff --git a/ceph/files/jewel/ceph.conf.Debian b/ceph/files/jewel/ceph.conf.Debian
index ca1c233..351eae2 100644
--- a/ceph/files/jewel/ceph.conf.Debian
+++ b/ceph/files/jewel/ceph.conf.Debian
@@ -98,6 +98,7 @@
 rgw frontends = civetweb port={{ radosgw.bind.address }}:{{ radosgw.bind.port }} num_threads={{ radosgw.threads }}
 rgw dns name = {{ radosgw.get('hostname', grains.host) }}
 rgw swift versioning enabled = {{ radosgw.get('swift', {}).get('versioning', {}).get('enabled', 'false') }}
+rgw swift enforce content length = {{ radosgw.get('swift', {}).get('enforce_content_length', 'false') }}
 {%- if radosgw.identity.engine == 'keystone' %}
 {%- set ident = radosgw.identity %}
 rgw keystone api version = {{ ident.get('api_version', 3) }}
diff --git a/ceph/files/kraken/ceph.conf.Debian b/ceph/files/kraken/ceph.conf.Debian
index ca1c233..351eae2 100644
--- a/ceph/files/kraken/ceph.conf.Debian
+++ b/ceph/files/kraken/ceph.conf.Debian
@@ -98,6 +98,7 @@
 rgw frontends = civetweb port={{ radosgw.bind.address }}:{{ radosgw.bind.port }} num_threads={{ radosgw.threads }}
 rgw dns name = {{ radosgw.get('hostname', grains.host) }}
 rgw swift versioning enabled = {{ radosgw.get('swift', {}).get('versioning', {}).get('enabled', 'false') }}
+rgw swift enforce content length = {{ radosgw.get('swift', {}).get('enforce_content_length', 'false') }}
 {%- if radosgw.identity.engine == 'keystone' %}
 {%- set ident = radosgw.identity %}
 rgw keystone api version = {{ ident.get('api_version', 3) }}
diff --git a/ceph/files/luminous/ceph.conf.Debian b/ceph/files/luminous/ceph.conf.Debian
index ca1c233..351eae2 100644
--- a/ceph/files/luminous/ceph.conf.Debian
+++ b/ceph/files/luminous/ceph.conf.Debian
@@ -98,6 +98,7 @@
 rgw frontends = civetweb port={{ radosgw.bind.address }}:{{ radosgw.bind.port }} num_threads={{ radosgw.threads }}
 rgw dns name = {{ radosgw.get('hostname', grains.host) }}
 rgw swift versioning enabled = {{ radosgw.get('swift', {}).get('versioning', {}).get('enabled', 'false') }}
+rgw swift enforce content length = {{ radosgw.get('swift', {}).get('enforce_content_length', 'false') }}
 {%- if radosgw.identity.engine == 'keystone' %}
 {%- set ident = radosgw.identity %}
 rgw keystone api version = {{ ident.get('api_version', 3) }}
diff --git a/ceph/meta/prometheus.yml b/ceph/meta/prometheus.yml
index e8dc6ca..9af58c2 100644
--- a/ceph/meta/prometheus.yml
+++ b/ceph/meta/prometheus.yml
@@ -99,10 +99,15 @@
 {% endraw %}
 {%- if setup.pool is defined %}
 {%- for pool_name, pool in setup.pool.iteritems() %}
+    {%- if monitoring.pool is defined and monitoring.pool[pool_name] is defined %}
+       {%- set monitoring_pool = monitoring.pool[pool_name] %}
+    {%- else %}
+       {%- set monitoring_pool = monitoring %}
+    {%- endif %}
     CephPool{{pool_name|replace(".", "")|replace("-", "")}}SpaceUsageWarning:
-      {%- set threshold = monitoring.pool_space_used_utilization_warning_threshold|default('0.75')|float %}
+      {%- set threshold = monitoring_pool.pool_space_used_utilization_warning_threshold|default('0.75')|float %}
       if: >-
-        ceph_pool_usage_bytes_used{name="{{pool_name}}"} / ceph_pool_usage_max_avail{name="{{pool_name}}"} > {{threshold}}
+        ceph_pool_usage_bytes_used{name="{{pool_name}}"} / (ceph_pool_usage_max_avail{name="{{pool_name}}"} + ceph_pool_usage_bytes_used{name="{{pool_name}}"}) > {{threshold}}
       for: 3m
       labels:
         severity: warning
@@ -111,7 +116,7 @@
         summary: "{{100*threshold}}% of Ceph pool space is used"
         description: "The Ceph {{pool_name}} pool uses {{100*threshold}}% of available space for 3 minutes. For details, run 'ceph df'."
     CephPool{{pool_name|replace(".", "")|replace("-", "")}}SpaceUsageMinor:
-      {%- set threshold = monitoring.pool_space_used_critical_threshold|default('0.85')|float %}
+      {%- set threshold = monitoring_pool.pool_space_used_critical_threshold|default('0.85')|float %}
       if: >-
         ceph_pool_usage_bytes_used{name="{{pool_name}}"} / ceph_pool_usage_max_avail{name="{{pool_name}}"} > {{threshold}}
       for: 3m
@@ -122,7 +127,7 @@
         summary: "{{100*threshold}}% of Ceph pool space is used"
         description: "The Ceph {{pool_name}} pool uses {{100*threshold}}% of available space for 3 minutes. For details, run 'ceph df'."
     CephPool{{pool_name|replace(".", "")|replace("-", "")}}WriteOpsTooHigh:
-      {%- set threshold = monitoring.pool_write_ops_threshold|default('200')|float %}
+      {%- set threshold = monitoring_pool.pool_write_ops_threshold|default('200')|float %}
       if: >-
         ceph_pool_stats_write_op_per_sec{name="{{pool_name}}"} > {{threshold}}
       for: 3m
@@ -133,7 +138,7 @@
         summary: "{{threshold}} Ceph pool write operations per second"
         description: "The number of Ceph {{pool_name}} pool write operations per second is {{threshold}} for 3 minutes."
     CephPool{{pool_name|replace(".", "")|replace("-", "")}}WriteBytesTooHigh:
-      {%- set threshold = monitoring.pool_write_bytes_threshold|default('70000000')|float %}
+      {%- set threshold = monitoring_pool.pool_write_bytes_threshold|default('70000000')|float %}
       if: >-
         ceph_pool_stats_write_bytes_sec{name="{{pool_name}}"} > {{threshold}}
       for: 3m
@@ -144,7 +149,7 @@
         summary: "{{threshold}} Ceph pool write bytes per second"
         description: "The number of Ceph {{pool_name}} pool write bytes per second is {{threshold}} for 3 minutes."
     CephPool{{pool_name|replace(".", "")|replace("-", "")}}ReadOpsTooHigh:
-      {%- set threshold = monitoring.pool_read_ops_threshold|default('1000')|float %}
+      {%- set threshold = monitoring_pool.pool_read_ops_threshold|default('1000')|float %}
       if: >-
         ceph_pool_stats_read_op_per_sec{name="{{pool_name}}"} > {{threshold}}
       for: 3m
@@ -155,7 +160,7 @@
         summary: "{{threshold}} Ceph pool read operations per second"
         description: "The number of Ceph {{pool_name}} pool read operations per second is {{threshold}} for 3 minutes."
     CephPool{{pool_name|replace(".", "")|replace("-", "")}}ReadBytesTooHigh:
-      {%- set threshold = monitoring.pool_read_bytes_threshold|default('70000000')|float %}
+      {%- set threshold = monitoring_pool.pool_read_bytes_threshold|default('70000000')|float %}
       if: >-
         ceph_pool_stats_read_bytes_sec{name="{{pool_name}}"} > {{threshold}}
       for: 3m
diff --git a/ceph/osd/custom.sls b/ceph/osd/custom.sls
index abdd6b9..a004663 100644
--- a/ceph/osd/custom.sls
+++ b/ceph/osd/custom.sls
@@ -1,4 +1,4 @@
-{%- from "ceph/map.jinja" import osd with context %}
+{%- from "ceph/map.jinja" import common, osd with context %}
 
 {% set ceph_version = pillar.ceph.common.version %}
 
diff --git a/ceph/osd/setup.sls b/ceph/osd/setup.sls
index b927881..852bfe5 100644
--- a/ceph/osd/setup.sls
+++ b/ceph/osd/setup.sls
@@ -24,7 +24,7 @@
 {% set dev = disk.dev %}
 
 # for uniqueness
-{% set dev_device = dev + disk.get('data_partition', 1)|string %}
+{% set dev_device = dev + disk.get('data_partition_prefix', '') + disk.get('data_partition', 1)|string %}
 
 #{{ dev }}{{ disk.get('data_partition', 1) }}
 
diff --git a/metadata/service/mgr/cluster.yml b/metadata/service/mgr/cluster.yml
index 2c4d0ea..923363b 100644
--- a/metadata/service/mgr/cluster.yml
+++ b/metadata/service/mgr/cluster.yml
@@ -8,6 +8,6 @@
     mgr:
       enabled: true
       dashboard:
-        enabled: true
+        enabled: false
         host: ${_param:single_address}
         port: 7000
diff --git a/metadata/service/mgr/single.yml b/metadata/service/mgr/single.yml
index 9cad788..d7c4b99 100644
--- a/metadata/service/mgr/single.yml
+++ b/metadata/service/mgr/single.yml
@@ -8,6 +8,6 @@
     mgr:
       enabled: true
       dashboard:
-        enabled: true
+        enabled: false
         host: ${_param:single_address}
         port: 7000
diff --git a/metadata/service/radosgw/cluster.yml b/metadata/service/radosgw/cluster.yml
index 69f09f7..fdc44c5 100644
--- a/metadata/service/radosgw/cluster.yml
+++ b/metadata/service/radosgw/cluster.yml
@@ -14,3 +14,5 @@
       bind:
         address: ${_param:single_address}
         port: ${_param:ceph_radosgw_bind_port}
+      swift:
+        enforce_content_length: true
\ No newline at end of file
diff --git a/metadata/service/radosgw/single.yml b/metadata/service/radosgw/single.yml
index fe65d2d..85430d8 100644
--- a/metadata/service/radosgw/single.yml
+++ b/metadata/service/radosgw/single.yml
@@ -14,3 +14,5 @@
       bind:
         address: ${_param:single_address}
         port: ${_param:ceph_radosgw_bind_port}
+      swift:
+        enforce_content_length: true
\ No newline at end of file
diff --git a/tests/run_tests.sh b/tests/run_tests.sh
index 9761585..461fd8b 100755
--- a/tests/run_tests.sh
+++ b/tests/run_tests.sh
@@ -1,5 +1,15 @@
 #!/usr/bin/env bash
 
+###
+# Script source: https://gerrit.mcp.mirantis.com/#/admin/projects/salt-formulas/cookiecutter-salt-formula
+# Script requirments:
+#apt-get install -y python-yaml virtualenv git
+
+__ScriptVersion="2018.11.21"
+__ScriptName="run_tests.sh"
+__ScriptFullName="$0"
+__ScriptArgs="$*"
+
 set -e
 [ -n "$DEBUG" ] && set -x
 
@@ -14,32 +24,40 @@
 VENV_DIR=${VENV_DIR:-${BUILDDIR}/virtualenv}
 MOCK_BIN_DIR=${MOCK_BIN_DIR:-${CURDIR}/mock_bin}
 DEPSDIR=${BUILDDIR}/deps
+SCHEMARDIR=${SCHEMARDIR:-"${CURDIR}/../${FORMULA_NAME}/schemas/"}
 
 SALT_FILE_DIR=${SALT_FILE_DIR:-${BUILDDIR}/file_root}
 SALT_PILLAR_DIR=${SALT_PILLAR_DIR:-${BUILDDIR}/pillar_root}
 SALT_CONFIG_DIR=${SALT_CONFIG_DIR:-${BUILDDIR}/salt}
 SALT_CACHE_DIR=${SALT_CACHE_DIR:-${SALT_CONFIG_DIR}/cache}
+SALT_CACHE_EXTMODS_DIR=${SALT_CACHE_EXTMODS_DIR:-${SALT_CONFIG_DIR}/cache_master_extmods}
 
 SALT_OPTS="${SALT_OPTS} --retcode-passthrough --local -c ${SALT_CONFIG_DIR} --log-file=/dev/null"
 
+IGNORE_MODELVALIDATE_MASK=${IGNORE_MODELVALIDATE_MASK:-"novalidate"}
+
 if [ "x${SALT_VERSION}" != "x" ]; then
     PIP_SALT_VERSION="==${SALT_VERSION}"
 fi
 
 ## Functions
 log_info() {
-    echo "[INFO] $*"
+    echo -e "[INFO] $*"
 }
 
 log_err() {
-    echo "[ERROR] $*" >&2
+    echo -e "[ERROR] $*" >&2
 }
 
 setup_virtualenv() {
     log_info "Setting up Python virtualenv"
+    dependency_check virtualenv
     virtualenv $VENV_DIR
     source ${VENV_DIR}/bin/activate
     python -m pip install salt${PIP_SALT_VERSION}
+    if [[ -f ${CURDIR}/test-requirements.txt ]]; then
+       python -m pip install -r ${CURDIR}/test-requirements.txt
+    fi
 }
 
 setup_mock_bin() {
@@ -65,6 +83,7 @@
     [ ! -d ${SALT_FILE_DIR} ] && mkdir -p ${SALT_FILE_DIR}
     [ ! -d ${SALT_CONFIG_DIR} ] && mkdir -p ${SALT_CONFIG_DIR}
     [ ! -d ${SALT_CACHE_DIR} ] && mkdir -p ${SALT_CACHE_DIR}
+    [ ! -d ${SALT_CACHE_EXTMODS_DIR} ] && mkdir -p ${SALT_CACHE_EXTMODS_DIR}
 
     echo "base:" > ${SALT_FILE_DIR}/top.sls
     for pillar in ${PILLARDIR}/*.sls; do
@@ -76,6 +95,7 @@
     cat << EOF > ${SALT_CONFIG_DIR}/minion
 file_client: local
 cachedir: ${SALT_CACHE_DIR}
+extension_modules:  ${SALT_CACHE_EXTMODS_DIR}
 verify_env: False
 minion_id_caching: False
 
@@ -83,7 +103,6 @@
   base:
   - ${SALT_FILE_DIR}
   - ${CURDIR}/..
-  - /usr/share/salt-formulas/env
 
 pillar_roots:
   base:
@@ -93,13 +112,14 @@
 }
 
 fetch_dependency() {
+    # example: fetch_dependency "linux:https://github.com/salt-formulas/salt-formula-linux"
     dep_name="$(echo $1|cut -d : -f 1)"
     dep_source="$(echo $1|cut -d : -f 2-)"
     dep_root="${DEPSDIR}/$(basename $dep_source .git)"
     dep_metadata="${dep_root}/metadata.yml"
 
-    [ -d /usr/share/salt-formulas/env/${dep_name} ] && log_info "Dependency $dep_name already present in system-wide salt env" && return 0
-    [ -d $dep_root ] && log_info "Dependency $dep_name already fetched" && return 0
+    dependency_check git
+    [ -d $dep_root ] && { log_info "Dependency $dep_name already fetched"; return 0; }
 
     log_info "Fetching dependency $dep_name"
     [ ! -d ${DEPSDIR} ] && mkdir -p ${DEPSDIR}
@@ -109,6 +129,19 @@
     METADATA="${dep_metadata}" install_dependencies
 }
 
+link_modules(){
+    # Link modules *.py files to temporary salt-root
+    local SALT_ROOT=${1:-$SALT_FILE_DIR}
+    local SALT_ENV=${2:-$DEPSDIR}
+
+    mkdir -p "${SALT_ROOT}/_modules/"
+    # from git, development versions
+    find ${SALT_ENV} -maxdepth 3 -mindepth 3 -path '*_modules*' -iname "*.py" -type f -print0 | while read -d $'\0' file; do
+      ln -fs $(readlink -e ${file}) "$SALT_ROOT"/_modules/$(basename ${file}) ;
+    done
+    salt_run saltutil.sync_all
+}
+
 install_dependencies() {
     grep -E "^dependencies:" ${METADATA} >/dev/null || return 0
     (python - | while read dep; do fetch_dependency "$dep"; done) << EOF
@@ -129,13 +162,30 @@
 }
 
 prepare() {
-    [ -d ${BUILDDIR} ] && mkdir -p ${BUILDDIR}
+    if [[ -f ${BUILDDIR}/.prepare_done ]]; then
+      log_info "${BUILDDIR}/.prepare_done exist, not rebuilding BUILDDIR"
+      return
+    fi
+    [[ -d ${BUILDDIR} ]] && mkdir -p ${BUILDDIR}
 
-    which salt-call || setup_virtualenv
+    [[ ! -f "${VENV_DIR}/bin/activate" ]] && setup_virtualenv
     setup_mock_bin
     setup_pillar
     setup_salt
     install_dependencies
+    link_modules
+    touch ${BUILDDIR}/.prepare_done
+}
+
+lint_releasenotes() {
+    [[ ! -f "${VENV_DIR}/bin/activate" ]] && setup_virtualenv
+    source ${VENV_DIR}/bin/activate
+    reno lint ${CURDIR}/../
+}
+
+lint() {
+#    lint_releasenotes
+    log_err "TODO: lint_releasenotes"
 }
 
 run() {
@@ -152,7 +202,7 @@
             meta_name=$(basename ${meta})
             echo "Checking meta ${meta_name} ..."
             salt_run --out=quiet --id=${state_name} cp.get_template ${meta} ${SALT_CACHE_DIR}/${meta_name} \
-              || (log_err "Failed to render meta ${meta} using pillar ${FORMULA_NAME}.${state_name}"; exit 1)
+              || { log_err "Failed to render meta ${meta} using pillar ${FORMULA_NAME}.${state_name}"; exit 1; }
             cat ${SALT_CACHE_DIR}/${meta_name}
         done
     done
@@ -161,10 +211,45 @@
 real_run() {
     for pillar in ${PILLARDIR}/*.sls; do
         state_name=$(basename ${pillar%.sls})
-        salt_run --id=${state_name} state.sls ${FORMULA_NAME} || (log_err "Execution of ${FORMULA_NAME}.${state_name} failed"; exit 1)
+        salt_run --id=${state_name} state.sls ${FORMULA_NAME} || { log_err "Execution of ${FORMULA_NAME}.${state_name} failed"; exit 1; }
     done
 }
 
+run_model_validate(){
+  # Run modelschema.model_validate validation.
+  # TEST iterateble, run for `each formula ROLE against each ROLE_PILLARNAME`
+  # Pillars should be named in conviend ROLE_XXX.sls or ROLE.sls
+  # Example:
+  # client.sls  client_auth.sls  server.sls  server_auth.sls
+  if [ -d ${SCHEMARDIR} ]; then
+    # model validator require py modules
+    fetch_dependency "salt:https://github.com/salt-formulas/salt-formula-salt"
+    link_modules
+    salt_run saltutil.clear_cache; salt_run saltutil.refresh_pillar; salt_run saltutil.sync_all;
+    for role in ${SCHEMARDIR}/*.yaml; do
+      role_name=$(basename "${role%*.yaml}")
+      for pillar in $(ls pillar/${role_name}*.sls | grep -v ${IGNORE_MODELVALIDATE_MASK} ); do
+        pillar_name=$(basename "${pillar%*.sls}")
+        local _message="FORMULA:${FORMULA_NAME} ROLE:${role_name} against PILLAR:${pillar_name}"
+        log_info "model_validate ${_message}"
+        # Rendered Example:
+        # python $(which salt-call) --local -c /test1/maas/tests/build/salt --id=maas_cluster modelschema.model_validate maas cluster
+        salt_run -m ${DEPSDIR}/salt-formula-salt --id=${pillar_name} modelschema.model_validate ${FORMULA_NAME} ${role_name} || { log_err "Execution of model_validate ${_message} failed"; exit 1 ; }
+      done
+    done
+  else
+    log_info "${SCHEMARDIR} not found!";
+  fi
+}
+
+dependency_check() {
+  local DEPENDENCY_COMMANDS=$*
+
+  for DEPENDENCY_COMMAND in $DEPENDENCY_COMMANDS; do
+    which $DEPENDENCY_COMMAND > /dev/null || ( log_err "Command \"$DEPENDENCY_COMMAND\" can not be found in default path."; exit 1; )
+  done
+}
+
 _atexit() {
     RETVAL=$?
     trap true INT TERM EXIT
@@ -178,6 +263,10 @@
 }
 
 ## Main
+
+log_info "Running version: ${__ScriptVersion}"
+log_info "Command line: '${__ScriptFullName} ${__ScriptArgs}'"
+
 trap _atexit INT TERM EXIT
 
 case $1 in
@@ -187,14 +276,23 @@
     prepare)
         prepare
         ;;
+    lint)
+        lint
+        ;;
     run)
         run
         ;;
     real-run)
         real_run
         ;;
+    model-validate)
+       prepare
+       run_model_validate
+        ;;
     *)
         prepare
+#        lint
         run
+        run_model_validate
         ;;
 esac