Merge pull request #11 from damjanek/master

Moved _modules/apiclient/ content to _modules/ per AKomarek request + change domainname
diff --git a/_modules/apiclient/__init__.py b/_modules/__init__.py
similarity index 100%
rename from _modules/apiclient/__init__.py
rename to _modules/__init__.py
diff --git a/_modules/apiclient/creds.py b/_modules/creds.py
similarity index 100%
rename from _modules/apiclient/creds.py
rename to _modules/creds.py
diff --git a/_modules/apiclient/encode_json.py b/_modules/encode_json.py
similarity index 100%
rename from _modules/apiclient/encode_json.py
rename to _modules/encode_json.py
diff --git a/_modules/maas.py b/_modules/maas.py
index 5ad0a41..c2ba659 100644
--- a/_modules/maas.py
+++ b/_modules/maas.py
@@ -27,7 +27,7 @@
 # Import third party libs
 HAS_MASS = False
 try:
-    from apiclient.maas_client import MAASClient, MAASDispatcher, MAASOAuth
+    from maas_client import MAASClient, MAASDispatcher, MAASOAuth
     HAS_MASS = True
 except ImportError:
     LOG.exception('why??')
@@ -434,6 +434,128 @@
         return new
 
 
+#class SSHPrefs(MaasObject):
+#    def __init__(self):
+#        super(SSHPrefs, self).__init__()
+#        self._all_elements_url = u'api/2.0/machines/'
+#        self._create_url = u'api/2.0/account/prefs/sshkeys/'
+#        self._config_path = 'region.sshprefs'
+#        self._element_key = 'hostname'
+#        self._update_key = 'system_id'
+#
+#    def fill_data(self, value):
+#        data = {
+#            'key': value,
+#        }
+#        return data
+#
+#    def process(self):
+#        config = __salt__['config.get']('maas')
+#        for part in self._config_path.split('.'):
+#            config = config.get(part, {})
+#        extra = {}
+#        for name, url_call in self._extra_data_urls.iteritems():
+#            key = 'id'
+#            if isinstance(url_call, tuple):
+#                url_call, key = url_call[:]
+#            extra[name] = {v['name']: v[key] for v in
+#                            json.loads(self._maas.get(url_call).read())}
+#        if self._all_elements_url:
+#            all_elements = {}
+#            elements = self._maas.get(self._all_elements_url).read()
+#            res_json = json.loads(elements)
+#            for element in res_json:
+#                if isinstance(element, (str, unicode)):
+#                    all_elements[element] = {}
+#                else:
+#                    all_elements[element[self._element_key]] = element
+#        else:
+#            all_elements = {}
+#        ret = {
+#            'success': [],
+#            'errors': {},
+#            'updated': [],
+#        }
+#        for config_data in config:
+#            try:
+#                data = self.fill_data(config_data, **extra)
+#                self.send(data)
+#                ret['success'].append(name)
+#            except urllib2.HTTPError as e:
+#                etxt = e.read()
+#                LOG.exception('Failed for object %s reason %s', name, etxt)
+#                ret['errors'][name] = str(etxt)
+#            except Exception as e:
+#                LOG.exception('Failed for object %s reason %s', name, e)
+#                ret['errors'][name] = str(e)
+#        if ret['errors']:
+#            raise Exception(ret)
+#        return ret
+
+class Domain(MaasObject):
+    def __init__(self):
+        super(Domain, self).__init__()
+        self._all_elements_url = u'/api/2.0/domains/'
+        self._create_url = u'/api/2.0/domains/'
+        self._config_path = 'region.domain'
+        self._update_url = u'/api/2.0/domains/{0}/'
+
+    def fill_data(self, value):
+        data = {
+            'name': value,
+        }
+        self._update = True
+        return data
+
+    def update(self, new, old):
+        new['id'] = str(old['id'])
+        new['authoritative'] = str(old['authoritative'])
+        return new
+
+    def process(self):
+        config = __salt__['config.get']('maas')
+        for part in self._config_path.split('.'):
+            config = config.get(part, {})
+        extra = {}
+        for name, url_call in self._extra_data_urls.iteritems():
+            key = 'id'
+            if isinstance(url_call, tuple):
+                url_call, key = url_call[:]
+            extra[name] = {v['name']: v[key] for v in
+                            json.loads(self._maas.get(url_call).read())}
+        if self._all_elements_url:
+            all_elements = {}
+            elements = self._maas.get(self._all_elements_url).read()
+            res_json = json.loads(elements)
+            for element in res_json:
+                if isinstance(element, (str, unicode)):
+                    all_elements[element] = {}
+                else:
+                    all_elements[element[self._element_key]] = element
+        else:
+            all_elements = {}
+        ret = {
+            'success': [],
+            'errors': {},
+            'updated': [],
+        }
+        try:
+            data = self.fill_data(config, **extra)
+            data = self.update(data, all_elements.values()[0])
+            self.send(data)
+            ret['success'].append('domain')
+        except urllib2.HTTPError as e:
+            etxt = e.read()
+            LOG.exception('Failed for object %s reason %s', 'domain', etxt)
+            ret['errors']['domain'] = str(etxt)
+        except Exception as e:
+            LOG.exception('Failed for object %s reason %s', 'domain', e)
+            ret['errors']['domain'] = str(e)
+        if ret['errors']:
+            raise Exception(ret)
+        return ret
+
+
 def process_fabrics():
     return Fabric().process()
 
@@ -460,3 +582,6 @@
 
 def process_commissioning_scripts():
     return CommissioningScripts().process()
+
+def process_domain():
+    return Domain().process()
diff --git a/_modules/apiclient/maas_client.py b/_modules/maas_client.py
similarity index 98%
rename from _modules/apiclient/maas_client.py
rename to _modules/maas_client.py
index 6704597..97aeb8b 100644
--- a/_modules/apiclient/maas_client.py
+++ b/_modules/maas_client.py
@@ -22,9 +22,9 @@
 from io import BytesIO
 import urllib2
 
-from apiclient.encode_json import encode_json_data
-from apiclient.multipart import encode_multipart_data
-from apiclient.utils import urlencode
+from encode_json import encode_json_data
+from multipart import encode_multipart_data
+from utils import urlencode
 import oauth.oauth as oauth
 
 
diff --git a/_modules/apiclient/multipart.py b/_modules/multipart.py
similarity index 100%
rename from _modules/apiclient/multipart.py
rename to _modules/multipart.py
diff --git a/_modules/apiclient/testing/__init__.py b/_modules/testing/__init__.py
similarity index 100%
rename from _modules/apiclient/testing/__init__.py
rename to _modules/testing/__init__.py
diff --git a/_modules/apiclient/testing/credentials.py b/_modules/testing/credentials.py
similarity index 100%
rename from _modules/apiclient/testing/credentials.py
rename to _modules/testing/credentials.py
diff --git a/_modules/apiclient/testing/django.py b/_modules/testing/django.py
similarity index 100%
rename from _modules/apiclient/testing/django.py
rename to _modules/testing/django.py
diff --git a/_modules/apiclient/testing/django_client_proxy.py b/_modules/testing/django_client_proxy.py
similarity index 100%
rename from _modules/apiclient/testing/django_client_proxy.py
rename to _modules/testing/django_client_proxy.py
diff --git a/_modules/apiclient/utils.py b/_modules/utils.py
similarity index 100%
rename from _modules/apiclient/utils.py
rename to _modules/utils.py
diff --git a/maas/region.sls b/maas/region.sls
index aa55a51..f2a9e4f 100644
--- a/maas/region.sls
+++ b/maas/region.sls
@@ -143,4 +143,10 @@
   - require:
     - module: maas_config
 
+maas_domain:
+  module.run:
+  - name: maas.process_domain
+  - require:
+    - module: maas_config
+
 {%- endif %}