Jelajahi Sumber

Merge branch 'trunk' into branch-alerts-dev

Jonathan Hurley 11 tahun lalu
induk
melakukan
6ba11a2a94
100 mengubah file dengan 1105 tambahan dan 1533 penghapusan
  1. 39 26
      ambari-admin/src/main/resources/ui/admin-web/app/scripts/controllers/users/UsersShowCtrl.js
  2. 1 2
      ambari-admin/src/main/resources/ui/admin-web/app/scripts/services/User.js
  3. 10 2
      ambari-admin/src/main/resources/ui/admin-web/app/styles/main.css
  4. 3 3
      ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/create.html
  5. 55 40
      ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/edit.html
  6. 0 81
      ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/list.html
  7. 1 1
      ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/listTable.html
  8. 42 33
      ambari-admin/src/main/resources/ui/admin-web/app/views/clusters/manageAccess.html
  9. 7 3
      ambari-admin/src/main/resources/ui/admin-web/app/views/groups/list.html
  10. 1 1
      ambari-admin/src/main/resources/ui/admin-web/app/views/users/show.html
  11. 1 0
      ambari-admin/src/main/resources/view.xml
  12. 1 1
      ambari-common/src/main/python/resource_management/libraries/providers/hdfs_directory.py
  13. 1 1
      ambari-server/src/main/java/org/apache/ambari/server/api/services/ConfigurationService.java
  14. 55 14
      ambari-server/src/main/java/org/apache/ambari/server/api/util/StackExtensionHelper.java
  15. 0 8
      ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java
  16. 151 0
      ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariHandlerList.java
  17. 8 5
      ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
  18. 2 0
      ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
  19. 38 2
      ambari-server/src/main/java/org/apache/ambari/server/controller/FailsafeHandlerList.java
  20. 1 1
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClientConfigResourceProvider.java
  21. 21 5
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ConfigGroupResourceProvider.java
  22. 5 1
      ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ViewInstanceResourceProvider.java
  23. 14 2
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrincipalDAO.java
  24. 0 69
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java
  25. 8 1
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ServiceConfigDAO.java
  26. 0 8
      ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java
  27. 11 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ConfigGroupEntity.java
  28. 5 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrincipalEntity.java
  29. 0 70
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/RoleEntity.java
  30. 0 11
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java
  31. 20 0
      ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewInstanceEntity.java
  32. 6 128
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java
  33. 1 7
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java
  34. 0 9
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/User.java
  35. 9 138
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/Users.java
  36. 23 7
      ambari-server/src/main/java/org/apache/ambari/server/security/authorization/internal/InternalAuthenticationToken.java
  37. 6 2
      ambari-server/src/main/java/org/apache/ambari/server/state/cluster/ClusterImpl.java
  38. 4 0
      ambari-server/src/main/java/org/apache/ambari/server/state/configgroup/ConfigGroup.java
  39. 21 0
      ambari-server/src/main/java/org/apache/ambari/server/state/configgroup/ConfigGroupImpl.java
  40. 41 15
      ambari-server/src/main/java/org/apache/ambari/server/upgrade/UpgradeCatalog170.java
  41. 43 0
      ambari-server/src/main/java/org/apache/ambari/server/view/ViewInstanceHandlerList.java
  42. 23 35
      ambari-server/src/main/java/org/apache/ambari/server/view/ViewRegistry.java
  43. 2 14
      ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
  44. 2 14
      ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
  45. 2 16
      ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
  46. 2 18
      ambari-server/src/main/resources/Ambari-DDL-Postgres-EMBEDDED-CREATE.sql
  47. 0 1
      ambari-server/src/main/resources/META-INF/persistence.xml
  48. 1 0
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HBASE/package/scripts/params.py
  49. 1 1
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HDFS/package/scripts/hdfs_namenode.py
  50. 1 0
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HDFS/package/scripts/params.py
  51. 19 8
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HIVE/package/scripts/hcat_service_check.py
  52. 1 0
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HIVE/package/scripts/params.py
  53. 0 20
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/MAPREDUCE/configuration/core-site.xml
  54. 1 0
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/MAPREDUCE/package/scripts/params.py
  55. 1 0
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/OOZIE/package/scripts/params.py
  56. 1 0
      ambari-server/src/main/resources/stacks/HDP/1.3.2/services/WEBHCAT/package/scripts/params.py
  57. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HBASE/package/scripts/params.py
  58. 1 1
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HDFS/package/scripts/hdfs_namenode.py
  59. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HDFS/package/scripts/params.py
  60. 19 8
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HIVE/package/scripts/hcat_service_check.py
  61. 1 1
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HIVE/package/scripts/install_jars.py
  62. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HIVE/package/scripts/params.py
  63. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/OOZIE/package/scripts/params.py
  64. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/PIG/package/scripts/params.py
  65. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/WEBHCAT/package/scripts/params.py
  66. 1 1
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/WEBHCAT/package/scripts/webhcat.py
  67. 0 20
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/YARN/configuration-mapred/core-site.xml
  68. 0 20
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/YARN/configuration/core-site.xml
  69. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.0.6/services/YARN/package/scripts/params.py
  70. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/FALCON/package/scripts/params.py
  71. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/scripts/params.py
  72. 1 0
      ambari-server/src/main/resources/stacks/HDP/2.1/services/FALCON/package/scripts/params.py
  73. 0 20
      ambari-server/src/main/resources/stacks/HDP/2.1/services/YARN/configuration/core-site.xml
  74. 97 138
      ambari-server/src/test/java/org/apache/ambari/server/api/util/StackExtensionHelperTest.java
  75. 107 0
      ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariHandlerListTest.java
  76. 0 11
      ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java
  77. 6 20
      ambari-server/src/test/java/org/apache/ambari/server/orm/OrmTestHelper.java
  78. 1 39
      ambari-server/src/test/java/org/apache/ambari/server/orm/dao/UserDAOTest.java
  79. 0 38
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java
  80. 0 39
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java
  81. 0 2
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapDataPopulatorTest.java
  82. 0 7
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsServiceTest.java
  83. 7 205
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestAmbariLdapAuthoritiesPopulator.java
  84. 0 87
      ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestUsers.java
  85. 6 2
      ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog170Test.java
  86. 0 8
      ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeTest.java
  87. 6 2
      ambari-server/src/test/java/org/apache/ambari/server/view/ViewRegistryTest.java
  88. 2 1
      ambari-server/src/test/python/stacks/1.3.2/HIVE/test_hive_service_check.py
  89. 0 0
      ambari-server/src/test/python/stacks/1.3.2/configs/secured.json
  90. 2 1
      ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_service_check.py
  91. 0 0
      ambari-server/src/test/python/stacks/2.0.6/configs/secured.json
  92. 0 0
      ambari-server/src/test/python/stacks/2.1/configs/secured.json
  93. 12 19
      ambari-web/app/app.js
  94. 0 1
      ambari-web/app/config.js
  95. 4 4
      ambari-web/app/controllers/global/cluster_controller.js
  96. 0 7
      ambari-web/app/controllers/installer.js
  97. 1 0
      ambari-web/app/controllers/main.js
  98. 6 2
      ambari-web/app/controllers/main/admin/repositories.js
  99. 79 1
      ambari-web/app/controllers/main/views_controller.js
  100. 25 4
      ambari-web/app/controllers/wizard/step5_controller.js

+ 39 - 26
ambari-admin/src/main/resources/ui/admin-web/app/scripts/controllers/users/UsersShowCtrl.js

@@ -108,10 +108,17 @@ angular.module('ambariAdminConsole')
   };
 
   $scope.toggleUserActive = function() {
-    User.setActive($scope.user.user_name, !$scope.user.active);
+    if(!$scope.isCurrentUser){
+      User.setActive($scope.user.user_name, !$scope.user.active);
+    }
   };    
   $scope.toggleUserAdmin = function() {
-    User.setAdmin($scope.user.user_name, !$scope.user.admin);
+    if(!$scope.isCurrentUser){
+      User.setAdmin($scope.user.user_name, !$scope.user.admin)
+      .then(function() {
+        loadPrivilegies();
+      });
+    }
   };    
 
   $scope.deleteUser = function() {
@@ -123,30 +130,36 @@ angular.module('ambariAdminConsole')
   };
 
   // Load privilegies
-  User.getPrivilegies($routeParams.id).then(function(data) {
-    var privilegies = {
-      clusters: {},
-      views: {}
-    };
-    angular.forEach(data.data.items, function(privilegie) {
-      privilegie = privilegie.PrivilegeInfo;
-      if(privilegie.type === 'CLUSTER'){
-        // This is cluster
-        privilegies.clusters[privilegie.cluster_name] = privilegies.clusters[privilegie.cluster_name] || '';
-        privilegies.clusters[privilegie.cluster_name] += privilegies.clusters[privilegie.cluster_name] ? ', ' + privilegie.permission_name : privilegie.permission_name;
-      } else if ( privilegie.type === 'VIEW'){
-        privilegies.views[privilegie.instance_name] = privilegies.views[privilegie.instance_name] || { privileges:''};
-        privilegies.views[privilegie.instance_name].version = privilegie.version;
-        privilegies.views[privilegie.instance_name].view_name = privilegie.view_name;
-        privilegies.views[privilegie.instance_name].privileges += privilegies.views[privilegie.instance_name].privileges ? ', ' + privilegie.permission_name : privilegie.permission_name;
-
-      }
-    });
+  function loadPrivilegies(){
+    User.getPrivilegies($routeParams.id).then(function(data) {
+      var privilegies = {
+        clusters: {},
+        views: {}
+      };
+      angular.forEach(data.data.items, function(privilegie) {
+        privilegie = privilegie.PrivilegeInfo;
+        if(privilegie.type === 'CLUSTER'){
+          // This is cluster
+          privilegies.clusters[privilegie.cluster_name] = privilegies.clusters[privilegie.cluster_name] || '';
+          privilegies.clusters[privilegie.cluster_name] += privilegies.clusters[privilegie.cluster_name] ? ', ' + privilegie.permission_name : privilegie.permission_name;
+        } else if ( privilegie.type === 'VIEW'){
+          privilegies.views[privilegie.instance_name] = privilegies.views[privilegie.instance_name] || { privileges:''};
+          privilegies.views[privilegie.instance_name].version = privilegie.version;
+          privilegies.views[privilegie.instance_name].view_name = privilegie.view_name;
+          privilegies.views[privilegie.instance_name].privileges += privilegies.views[privilegie.instance_name].privileges ? ', ' + privilegie.permission_name : privilegie.permission_name;
+
+        }
+      });
+
+      $scope.privileges = data.data.items.length ? privilegies : null;
+      $scope.dataLoaded = true;
 
-    $scope.privileges = data.data.items.length ? privilegies : null;
-    $scope.dataLoaded = true;
+    }).catch(function(data) {
+      uiAlert.danger(data.data.status, data.data.message);
+    });
+  }
 
-  }).catch(function(data) {
-    uiAlert.danger(data.data.status, data.data.message);
-  });
+  loadPrivilegies();
+  
+    
 }]);

+ 1 - 2
ambari-admin/src/main/resources/ui/admin-web/app/scripts/services/User.js

@@ -64,8 +64,7 @@ angular.module('ambariAdminConsole')
         url: Settings.baseUrl + '/users/' + user.user_name,
         data: {
           'Users/password': password,
-          'Users/old_password': currentUserPassword,
-          'Users/roles': user.roles[0] || 'user'
+          'Users/old_password': currentUserPassword
         }
       });
     },

+ 10 - 2
ambari-admin/src/main/resources/ui/admin-web/app/styles/main.css

@@ -133,7 +133,7 @@
   background-color: #e6e6e6;
   cursor: not-allowed;
 }
-.btn.deleteuser-btn.disabled, .btn.deleteuser-btn[disabled]{
+.btn.deleteuser-btn.disabled, .btn.deleteuser-btn[disabled], .btn.btn-delete-instance.disabled{
   pointer-events: auto;
   cursor: not-allowed;
   background-color: #e6e6e6;
@@ -251,8 +251,13 @@
   top: 30px;
 }
 .groups-pane .search-container .close{
-  top: 5px;
+  top: 30px;
 }
+.views-list-table .search-container .close{
+  top: 5px;
+  right: 50px;
+  z-index: 10;
+} 
 .views-list-pane .search-container .close{
   right: 50px;
   top: 5px;
@@ -337,6 +342,9 @@ table.no-border tr td{
 .top-margin-4{
   margin-top: 4px;
 }
+.table > thead > tr > th.vertical-top{
+  vertical-align: top;
+}
 
 .groups-pane table ul{
   list-style-type: none;

+ 3 - 3
ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/create.html

@@ -63,18 +63,18 @@
       ng-class="{'has-error' : ( (form.isntanceCreateForm.displayLabel.$error.required || form.isntanceCreateForm.displayLabel.$error.pattern) && form.isntanceCreateForm.submitted)}">
         <label for="" class="control-label col-sm-2">Display Label</label>
         <div class="col-sm-10">
-          <input type="text" class="form-control instancelabel-input" name="displayLabel" ng-model="instance.label" required ng-pattern="nameValidationPattern" autocomplete="off">
+          <input type="text" class="form-control instancelabel-input" name="displayLabel" ng-model="instance.label" required ng-pattern="/^([a-zA-Z0-9._\s]+)$/" autocomplete="off">
 
           <div class="alert alert-danger no-margin-bottom top-margin" ng-show='form.isntanceCreateForm.displayLabel.$error.required && form.isntanceCreateForm.submitted'>
             This field is required.
           </div>
           <div class="alert alert-danger no-margin-bottom top-margin" ng-show='form.isntanceCreateForm.displayLabel.$error.pattern && form.isntanceCreateForm.submitted'>
-            Must not contain any special characters or spaces.
+            Must not contain any special characters.
           </div>
         </div>
       </div>
       <div class="form-group" ng-class="{'has-error' : form.isntanceCreateForm.description.$error.required && form.isntanceCreateForm.submitted }">
-        <label for="" class="control-label col-sm-2">Instance Description</label>
+        <label for="" class="control-label col-sm-2">Description</label>
         <div class="col-sm-10">
           <input type="text" class="form-control" name="description" ng-model="instance.description" maxlength="140" required>
           <div class="alert alert-danger no-margin-bottom top-margin" ng-show='form.isntanceCreateForm.description.$error.required && form.isntanceCreateForm.submitted'>

+ 55 - 40
ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/edit.html

@@ -20,8 +20,9 @@
     <li><a href="#/views">Views</a></li>
     <li class="active">{{instance.ViewInstanceInfo.label}}</li>
   </ol>
-  <div class="pull-right top-margin-4">
-    <button class="btn btn-danger" ng-click="deleteInstance(instance)">Delete Instance</button>
+  <div class="pull-right top-margin-4" ng-switch="instance.ViewInstanceInfo.static">
+    <button ng-switch-when="true" class="btn disabled btn-default btn-delete-instance" tooltip="Cannot Delete Static Instances">Delete Instance</button>
+    <button ng-switch-when="false" class="btn btn-danger" ng-click="deleteInstance(instance)">Delete Instance</button>
   </div>
 </div>
 <hr>
@@ -30,7 +31,7 @@
     <h3 class="panel-title pull-left">Settings</h3>
     <div class="pull-right" ng-switch="instance.ViewInstanceInfo.static">
       <a href ng-switch-when="false" ng-click="toggleSettingsEdit()" ng-show="editSettingsDisabled" class="settings-edit-toggle"> <span class="glyphicon glyphicon-pencil" ></span> Edit</a>
-      <a href ng-switch-when="true" class="settings-edit-toggle disabled" tooltip="You can`t edit XML driven instances"> <span class="glyphicon glyphicon-pencil" ></span> Edit</a>
+      <a href ng-switch-when="true" class="settings-edit-toggle disabled" tooltip="Cannot Edit Static Instances"> <span class="glyphicon glyphicon-pencil" ></span> Edit</a>
     </div>
   </div>
   <div class="panel-body">
@@ -48,17 +49,20 @@
           <label for="" class="col-sm-2 control-label">Instance Name</label>
           <div class="col-sm-10"><input disabled="disabled" type="text" class="form-control instancename-input" placeholder="Display Name" value="{{instance.ViewInstanceInfo.instance_name}}"></div>
         </div>
-        <div class="form-group" ng-class="{'has-error' : settingsForm.displayName.$error.required && !editSettingsDisabled}">
+        <div class="form-group" ng-class="{'has-error' : (settingsForm.displayName.$error.required || settingsForm.displayName.$error.pattern) && !editSettingsDisabled}">
           <label for="" class="col-sm-2 control-label">Display Name</label>
           <div class="col-sm-10">
-            <input type="text" class="form-control instancename-input" placeholder="Display Name" name="displayName" required ng-model="settings.label">
+            <input type="text" class="form-control instancename-input" placeholder="Display Name" name="displayName" required ng-model="settings.label" ng-pattern="/^([a-zA-Z0-9._\s]+)$/">
             <div class="alert alert-danger no-margin-bottom top-margin" ng-show='settingsForm.displayName.$error.required  && !editSettingsDisabled'>
               This field is required.
             </div>
+            <div class="alert alert-danger no-margin-bottom top-margin" ng-show='settingsForm.displayName.$error.pattern && !editSettingsDisabled'>
+              Must not contain any special characters.
+            </div>
           </div>
         </div>
         <div class="form-group" ng-class="{'has-error' : settingsForm.description.$error.required  && !editSettingsDisabled}">
-          <label for="" class="control-label col-sm-2">Instance Description</label>
+          <label for="" class="control-label col-sm-2">Description</label>
           <div class="col-sm-10">
             <input type="text" class="form-control" ng-model="settings.description" name="description" placeholder="Instance Description" required>
             <div class="alert alert-danger no-margin-bottom top-margin" ng-show='settingsForm.description.$error.required  && !editSettingsDisabled'>
@@ -94,41 +98,52 @@
     </div>
   </div>
   <div class="panel-body">
-    <form class="form-horizontal" ng-show="!isPermissionsEmpty">
-      <div class="form-group">
-        <div class="col-sm-2"></div>
-        <label class="col-sm-5 control-label text-left">Users</label>
-        <label class="col-sm-5 control-label text-left">Groups</label>
-      </div>
-      <div class="form-group" ng-repeat="permission in permissions">
-        <label class="col-sm-2 control-label">{{permission.PermissionInfo.permission_name}}</label>
-        <div class="col-sm-5" ng-switch="editPermissionDisabled">
-          <textarea name="" id="" cols="30" rows="4" class="form-control permission-textarea-user" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].USER" ng-switch-when="false"></textarea>
-          <div class="well" ng-switch-when="true">
-            <span ng-repeat="user in permission.USER">
-              <link-to route="users.show" id="{{user}}">{{user}}</link-to>
-              {{$last ? '' :', '}}
-            </span>
-          </div>
-        </div>
-        <div class="col-sm-5" ng-switch="editPermissionDisabled">
-          <textarea name="" id="" cols="30" rows="4" class="form-control permission-textarea-group" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].GROUP" ng-switch-when="false"></textarea>
-          <div class="well" ng-switch-when="true">
-            <span ng-repeat="group in permission.GROUP">
-              <link-to route="groups.edit" id="{{group}}" >{{group}}</link-to>
-              {{$last ? '' :', '}}
-            </span>
-          </div>
-        </div>
-      </div>
-      
-      <div class="form-group" ng-hide="editPermissionDisabled">
-        <div class="col-sm-offset-2 col-sm-10">
-          <button class="btn btn-primary pull-right left-margin permissions-save" ng-click="savePermissions()">Save</button>
-          <button class="btn btn-default pull-right permissions-cancel" ng-click="cancelPermissions()">Cancel</button>
-        </div>
+    
+
+    <table class="table" ng-show="!isPermissionsEmpty">
+      <thead>
+        <tr>
+          <th class="col-sm-2"><label>Permission</label></th>
+          <th><label>Grant permission to these users</label></th>
+          <th><label>Grant permission to these groups</label></th>
+        </tr>
+      </thead>
+      <tbody>
+        <tr ng-repeat="permission in permissions">
+          <td>
+            <label class="">{{permission.PermissionInfo.permission_name}}</label>
+          </td>
+          <td>
+            <div class="" ng-switch="editPermissionDisabled">
+              <textarea name="" id="" cols="30" rows="4" class="form-control permission-textarea-user" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].USER" ng-switch-when="false"></textarea>
+              <div class="well" ng-switch-when="true">
+                <span ng-repeat="user in permission.USER">
+                  <link-to route="users.show" id="{{user}}">{{user}}</link-to>
+                  {{$last ? '' :', '}}
+                </span>
+              </div>
+            </div>
+          </td>
+          <td>
+            <div class="" ng-switch="editPermissionDisabled">
+              <textarea name="" id="" cols="30" rows="4" class="form-control permission-textarea-group" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].GROUP" ng-switch-when="false"></textarea>
+              <div class="well" ng-switch-when="true">
+                <span ng-repeat="group in permission.GROUP">
+                  <link-to route="groups.edit" id="{{group}}" >{{group}}</link-to>
+                  {{$last ? '' :', '}}
+                </span>
+              </div>
+            </div>
+          </td>
+        </tr>
+      </tbody>
+    </table>
+    <div class="form-group" ng-hide="editPermissionDisabled">
+      <div class="col-sm-offset-2 col-sm-10">
+        <button class="btn btn-primary pull-right left-margin permissions-save" ng-click="savePermissions()">Save</button>
+        <button class="btn btn-default pull-right permissions-cancel" ng-click="cancelPermissions()">Cancel</button>
       </div>
-    </form>
+    </div>
     <div ng-show="isPermissionsEmpty">
       <div class="alert alert-info">There are no permissions defined for this view.</div>
     </div>

+ 0 - 81
ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/list.html

@@ -1,81 +0,0 @@
-<!--
-* Licensed to the Apache Software Foundation (ASF) under one
-* or more contributor license agreements.  See the NOTICE file
-* distributed with this work for additional information
-* regarding copyright ownership.  The ASF licenses this file
-* to you 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.
--->
-    
-<div class="views-list-pane">
-  <div class="clearfix">
-    <ol class="breadcrumb pull-left">
-      <li class="active">Views</li>
-    </ol>
-    <div class="pull-right col-sm-4">
-      <div class="input-group search-container">
-        <input type="text" class="form-control search-input" placeholder="Search" ng-model="viewsFilter" ng-change="getFilteredViews()">
-        <button type="button" class="close clear-search" ng-show="viewsFilter" ng-click="viewsFilter=''; getFilteredViews()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
-        <span class="input-group-addon">
-          <span class="glyphicon glyphicon-search"></span>
-        </span>
-      </div>
-    </div>
-  </div>
-  <hr>
-  <div class="row">
-    <div class="col-sm-3 padding-left-30"><h4>View Name</h4></div>
-    <div class="col-sm-3"><h4>Versions</h4></div>
-    <div class="col-sm-3"><h4>Instances</h4></div>
-    <div class="col-sm-3"><h4>Description</h4></div>
-  </div>
-  <accordion>
-    <accordion-group ng-repeat="view in filteredViews" is-open="open">
-      <accordion-heading>
-        <div class="row">
-          <div class="col-sm-3">
-            <i class="glyphicon glyphicon-chevron-right" ng-class="{'opened': open}"></i>
-            {{view.view_name}}
-          </div>
-          <div class="col-sm-3">{{view.versions}}</div>
-          <div class="col-sm-3">{{view.instances.length ? view.instances.length : 'No'}} instances</div>
-          <div class="col-sm-3">This is a description</div>
-        </div>
-      </accordion-heading>
-      <table class="table">
-        <tbody>
-          <tr ng-repeat="instance in view.instances">
-            <td class="col-sm-3"></td>
-            <td class="col-sm-3">{{instance.ViewInstanceInfo.version}}</td>
-            <td class="col-sm-3">
-              <a href="#/views/{{view.view_name}}/versions/{{instance.ViewInstanceInfo.version}}/instances/{{instance.ViewInstanceInfo.instance_name}}/edit" class="instance-link">{{instance.ViewInstanceInfo.label}}</a>
-            </td>
-            <td class="col-sm-3">
-            </td>
-          </tr>
-        </tbody>
-        <tfoot>
-          <tr>
-            <td class="col-sm-3"></td>
-            <td class="col-sm-3"></td>
-            <td class="col-sm-3">
-              <a class="btn btn-default createisntance-btn" href="#/views/{{view.view_name}}/versions/{{view.versionsList[view.versionsList.length-1].ViewVersionInfo.version}}/new"><span class="glyphicon glyphicon-plus" ></span> Create Instance</a>
-            </td>
-            <td class="col-sm-3">
-            </td>
-          </tr>
-        </tfoot>
-      </table>
-    </accordion-group>
-
-  </accordion>
-</div>

+ 1 - 1
ambari-admin/src/main/resources/ui/admin-web/app/views/ambariViews/listTable.html

@@ -35,7 +35,7 @@
   <div class="row">
     <div class="col-sm-3 padding-left-30"><h4>View Name</h4></div>
     <div class="col-sm-3"><h4>Instances</h4></div>
-    <div class="col-sm-6"><h4>Description</h4></div>
+    <div class="col-sm-6"><h4></h4></div>
   </div>
   <accordion close-others="false">
     <accordion-group ng-repeat="view in filteredViews" is-open="view.isOpened">

+ 42 - 33
ambari-admin/src/main/resources/ui/admin-web/app/views/clusters/manageAccess.html

@@ -22,41 +22,50 @@
       <li class="active">{{clusterName}} Permissions</li>
     </ol>
     <div class="pull-right top-margin-4">
-      <a href class="btn btn-primary"  ng-click="toggleEditMode()"><span class="glyphicon glyphicon-pencil"></span> Edit</a>
+      <a href class="btn btn-primary"  ng-hide="isEditMode" ng-click="toggleEditMode()"><span class="glyphicon glyphicon-pencil"></span> Edit</a>
     </div>
   </div>
   <hr>
-  <form class="form-horizontal">
-    <div class="form-group">
-      <div class="col-sm-2"></div>
-      <label class="col-sm-5 control-label text-left">Users</label>
-      <label class="col-sm-5 control-label text-left">Groups</label>
-    </div>
-    <div class="form-group" ng-repeat="permission in permissions">
-      <label class="col-sm-2 control-label">{{permission.PermissionInfo.permission_name}}</label>
-      <div class="col-sm-5" ng-switch="isEditMode">
-        <textarea ng-switch-when="true" name="" id="" cols="30" rows="4" class="form-control permission-user-input" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].USER"></textarea>
-        <div class="well" ng-switch-default>
-          <span ng-repeat="user in permission.USER">
-            <link-to route="users.show" id="{{user}}" >{{user}}</link-to>
-            {{$last ? '' :', '}}
-          </span>
-        </div>
-      </div>
-      <div class="col-sm-5" ng-switch="isEditMode">
-        <textarea ng-switch-when="true" name="" id="" cols="30" rows="4" class="form-control permission-group-input" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].GROUP"></textarea>
-        <div class="well" ng-switch-default>
-          <span ng-repeat="group in permission.GROUP">
-            <link-to route="groups.edit" id="{{group}}">{{group}}</link-to>
-            {{$last ? '' :', '}}
-          </span>
-        </div>
-      </div>
-    </div>
-    <div class="form-group" ng-show="isEditMode">
-      <div class="col-sm-offset-2 col-sm-10">
-        <button class="btn btn-default pull-right left-margin permissions-cancel" ng-click="cancel()">Cancel</button>
-        <button class="btn btn-primary pull-right permission-save" ng-click="save()">Save</button>
-      </div>
+  <table class="table">
+    <thead>
+      <tr>
+        <th class="col-sm-2"><label>Permission</label></th>
+        <th><label>Grant permission to these users</label></th>
+        <th><label>Grant permission to these groups</label></th>
+      </tr>
+    </thead>
+    <tbody>
+      <tr ng-repeat="permission in permissions">
+        <td><label class="">{{permission.PermissionInfo.permission_name}}</label></td>
+        <td>
+          <div class="" ng-switch="isEditMode">
+            <textarea ng-switch-when="true" name="" id="" cols="30" rows="4" class="form-control permission-user-input" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].USER"></textarea>
+            <div class="well" ng-switch-default>
+              <span ng-repeat="user in permission.USER">
+                <link-to route="users.show" id="{{user}}" >{{user}}</link-to>
+                {{$last ? '' :', '}}
+              </span>
+            </div>
+          </div>
+        </td>
+        <td>
+          <div class="" ng-switch="isEditMode">
+            <textarea ng-switch-when="true" name="" id="" cols="30" rows="4" class="form-control permission-group-input" ng-model="permissionsEdit[permission.PermissionInfo.permission_name].GROUP"></textarea>
+            <div class="well" ng-switch-default>
+              <span ng-repeat="group in permission.GROUP">
+                <link-to route="groups.edit" id="{{group}}">{{group}}</link-to>
+                {{$last ? '' :', '}}
+              </span>
+            </div>
+          </div>
+        </td>
+      </tr>
+    </tbody>
+  </table>
+  <div class="form-group" ng-show="isEditMode">
+    <div class="col-sm-offset-2 col-sm-10">
+      <button class="btn btn-primary pull-right permission-save left-margin" ng-click="save()">Save</button>
+      <button class="btn btn-default pull-right permissions-cancel" ng-click="cancel()">Cancel</button>
     </div>
+  </div>
 </div>

+ 7 - 3
ambari-admin/src/main/resources/ui/admin-web/app/views/groups/list.html

@@ -27,7 +27,7 @@
   <hr>
   <table class="table table-striped table-hover col-sm-12">
     <thead>
-      <tr>
+      <!-- <tr>
         <th>
           <label for="">Group Name</label>
         </th>
@@ -35,22 +35,26 @@
           <label for="">Type</label>
         </th>
         <th><label for="">Members</label></th>
-      </tr>
+      </tr> -->
       <tr>
         <th class="col-sm-8">
           <div class="search-container">
+            <label for="">Group Name</label>
             <input type="text" class="form-control namefilter" ng-model="currentNameFilter" ng-change="resetPagination()">
             <button type="button" class="close" ng-show="currentNameFilter" ng-click="currentNameFilter=''; resetPagination()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
           </div>
         </th>
         <th class="col-sm-2">
+          <label for="">Type</label>
           <select class="form-control typefilter"
             ng-model="currentTypeFilter"
             ng-options="item.label for item in typeFilterOptions"
             ng-change="resetPagination();">
           </select>
         </th>
-        <th class="col-sm-2"></th>
+        <th class="col-sm-2 vertical-top">
+          <label for="">Members</label>
+        </th>
       </tr>
     </thead>
     <tbody>

+ 1 - 1
ambari-admin/src/main/resources/ui/admin-web/app/views/users/show.html

@@ -117,7 +117,7 @@
             </tr>
           </tbody>
         </table>
-        <div class="alert alert-info" ng-show="!privileges">This user does not have any privileges.</div>
+        <div class="alert alert-info" ng-show="!privileges && !user.admin">This user does not have any privileges.</div>
         <div class="alert alert-info" ng-show="user.admin">This user is an Ambari Admin and has all privileges.</div>
       </div>
     </div>

+ 1 - 0
ambari-admin/src/main/resources/view.xml

@@ -21,5 +21,6 @@ limitations under the License. Kerberos, LDAP, Custom. Binary/Htt
   <instance>
     <name>INSTANCE</name>
     <visible>false</visible>
+    <description>This view provides administration capabilities for Ambari</description>
   </instance>
 </view>

+ 1 - 1
ambari-common/src/main/python/resource_management/libraries/providers/hdfs_directory.py

@@ -90,7 +90,7 @@ class HdfsDirectoryProvider(Provider):
         chown_commands.append(format("hadoop fs -chown {recursive} {chown} {chown_dirs_str}"))
 
     if secured:
-        Execute(format("{kinit_path} -kt {keytab_file} {hdp_hdfs_user}"),
+        Execute(format("{kinit_path} -kt {keytab_file} {hdfs_principal_name}"),
                 user=hdp_hdfs_user)
     #create all directories in one 'mkdir' call
     dir_list_str = ' '.join(directories_list)

+ 1 - 1
ambari-server/src/main/java/org/apache/ambari/server/api/services/ConfigurationService.java

@@ -51,7 +51,7 @@ public class ConfigurationService extends BaseService {
     m_clusterName = clusterName;
   }
 
-  @Path("serviceconfigversions")
+  @Path("service_config_versions")
   public ServiceConfigVersionService getServiceConfigVersionService() {
     return new ServiceConfigVersionService(m_clusterName);
   }

+ 55 - 14
ambari-server/src/main/java/org/apache/ambari/server/api/util/StackExtensionHelper.java

@@ -24,6 +24,7 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.ListIterator;
@@ -143,12 +144,6 @@ public class StackExtensionHelper {
             parentService.getConfigDependencies() != null ?
                 parentService.getConfigDependencies() :
                 Collections.<String>emptyList());
-    mergedServiceInfo.setConfigTypes(
-        childService.getConfigTypes() != null ?
-            childService.getConfigTypes() :
-            parentService.getConfigTypes() != null ?
-                parentService.getConfigTypes() :
-                Collections.<String, Map<String, Map<String, String>>>emptyMap());
     mergedServiceInfo.setExcludedConfigTypes(
       childService.getExcludedConfigTypes() != null ?
         childService.getExcludedConfigTypes() :
@@ -179,7 +174,15 @@ public class StackExtensionHelper {
     } else {
       mergedServiceInfo.setOsSpecifics(parentService.getOsSpecifics());
     }
-
+    
+    mergedServiceInfo.setConfigTypes(new HashMap<String, Map<String, Map<String, String>>>());
+    if(childService.getConfigTypes() != null) {
+      mergedServiceInfo.getConfigTypes().putAll(childService.getConfigTypes());
+    }
+    if(parentService.getConfigTypes() != null) {
+      mergedServiceInfo.getConfigTypes().putAll(parentService.getConfigTypes());
+    }
+    
     CommandScriptDefinition commandScript = childService.getCommandScript();
     if (commandScript != null) {
        mergedServiceInfo.setCommandScript(childService.getCommandScript());
@@ -421,8 +424,21 @@ public class StackExtensionHelper {
           serviceInfoMap.put(service.getName(), newServiceInfo);
         }
         
-        // add action for service check
+        // remove 'excluded-config-types' from configTypes
         ServiceInfo serviceInfo = serviceInfoMap.get(service.getName());
+        if(serviceInfo.getExcludedConfigTypes() != null) { 
+          Iterator<Map.Entry<String,Map<String,Map<String,String>>>> configTypesItetator = serviceInfo.getConfigTypes().entrySet().iterator();
+          
+          while(configTypesItetator.hasNext()) {
+            Map.Entry<String,Map<String,Map<String,String>>> configTypeMap = configTypesItetator.next();
+            
+            if(serviceInfo.getExcludedConfigTypes().contains(configTypeMap.getKey())) {
+              configTypesItetator.remove();
+            }
+          }
+        }
+        
+        // add action for service check
         if(serviceInfo.getCommandScript() != null) {
           actionMetadata.addServiceCheckAction(serviceInfo.getName());
         }
@@ -503,7 +519,6 @@ public class StackExtensionHelper {
           List<ServiceInfo> serviceInfos = smiv2x.getServices();
           for (ServiceInfo serviceInfo : serviceInfos) {
             serviceInfo.setSchemaVersion(AmbariMetaInfo.SCHEMA_VERSION_2);
-            populateConfigTypesFromDependencies(serviceInfo);
 
             // Find service package folder
             String servicePackageDir = resolveServicePackageFolder(
@@ -706,6 +721,12 @@ public class StackExtensionHelper {
     serviceInfo.getProperties().addAll(getProperties(configuration, fileName));
     int extIndex = fileName.indexOf(AmbariMetaInfo.SERVICE_CONFIG_FILE_NAME_POSTFIX);
     String configType = fileName.substring(0, extIndex);
+   
+    addConfigType(serviceInfo, configType);
+    setConfigTypeAttributes(serviceInfo, configuration, configType);
+  }
+  
+  void setConfigTypeAttributes(ServiceInfo serviceInfo, ConfigurationXml configuration, String configType) {
     for (Map.Entry<QName, String> attribute : configuration.getAttributes().entrySet()) {
       for (Supports supportsProperty : Supports.values()) {
         String attributeName = attribute.getKey().getLocalPart();
@@ -717,23 +738,43 @@ public class StackExtensionHelper {
       }
     }
   }
+  
+  void addConfigType(ServiceInfo serviceInfo, String configType) {
+    if(serviceInfo.getConfigTypes() == null) {
+      serviceInfo.setConfigTypes(new HashMap<String, Map<String, Map<String, String>>>());
+    }
+    
+    Map<String, Map<String, Map<String, String>>> configTypes = serviceInfo.getConfigTypes();
+    configTypes.put(configType, new HashMap<String, Map<String, String>>());
+    
+    
+    Map<String, Map<String, String>> properties = configTypes.get(configType);
+    Map<String, String> supportsProperties = new HashMap<String, String>();
+    for (Supports supportsProperty : Supports.values()) {
+      supportsProperties.put(supportsProperty.getPropertyName(), supportsProperty.getDefaultValue());
+    }
+    properties.put(Supports.KEYWORD, supportsProperties); 
+  }
 
   /**
    * Populate ServiceInfo#configTypes with default entries based on ServiceInfo#configDependencies property
    */
   void populateConfigTypesFromDependencies(ServiceInfo serviceInfo) {
-    List<String> configDependencies = serviceInfo.getConfigDependenciesWithComponents();
-    if (configDependencies != null) {
+    List<PropertyInfo> configurations = serviceInfo.getProperties();
+    if (configurations != null) {
       Map<String, Map<String, Map<String, String>>> configTypes = new HashMap<String, Map<String, Map<String, String>>>();
-      for (String configDependency : configDependencies) {
-        if (!configTypes.containsKey(configDependency)) {
+      for (PropertyInfo configuration : configurations) {
+        int extIndex = configuration.getFilename().indexOf(AmbariMetaInfo.SERVICE_CONFIG_FILE_NAME_POSTFIX);
+        String configType = configuration.getFilename().substring(0, extIndex);
+        
+        if (!configTypes.containsKey(configType)) {
           Map<String, Map<String, String>> properties = new HashMap<String, Map<String, String>>();
           Map<String, String> supportsProperties = new HashMap<String, String>();
           for (Supports supportsProperty : Supports.values()) {
             supportsProperties.put(supportsProperty.getPropertyName(), supportsProperty.getDefaultValue());
           }
           properties.put(Supports.KEYWORD, supportsProperties);
-          configTypes.put(configDependency, properties);
+          configTypes.put(configType, properties);
         }
       }
       serviceInfo.setConfigTypes(configTypes);

+ 0 - 8
ambari-server/src/main/java/org/apache/ambari/server/configuration/Configuration.java

@@ -149,10 +149,6 @@ public class Configuration {
       "authorization.ldap.adminGroupMappingRules";
   public static final String LDAP_GROUP_SEARCH_FILTER_KEY =
       "authorization.ldap.groupSearchFilter";
-  public static final String USER_ROLE_NAME_KEY =
-      "authorization.userRoleName";
-  public static final String ADMIN_ROLE_NAME_KEY =
-      "authorization.adminRoleName";
   public static final String SERVER_EC_CACHE_SIZE = "server.ecCacheSize";
   public static final String SERVER_STALE_CONFIG_CACHE_ENABLED_KEY =
     "server.cache.isStale.enabled";
@@ -349,10 +345,6 @@ public class Configuration {
         PASSPHRASE_ENV_KEY, PASSPHRASE_ENV_DEFAULT));
     configsMap.put(PASSPHRASE_KEY, System.getenv(configsMap.get(
         PASSPHRASE_ENV_KEY)));
-    configsMap.put(USER_ROLE_NAME_KEY, properties.getProperty(
-        USER_ROLE_NAME_KEY, USER_ROLE_NAME_DEFAULT));
-    configsMap.put(ADMIN_ROLE_NAME_KEY, properties.getProperty(
-        ADMIN_ROLE_NAME_KEY, ADMIN_ROLE_NAME_DEFAULT));
     configsMap.put(RESOURCES_DIR_KEY, properties.getProperty(
         RESOURCES_DIR_KEY, RESOURCES_DIR_DEFAULT));
     configsMap.put(SRVR_CRT_PASS_LEN_KEY, properties.getProperty(

+ 151 - 0
ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariHandlerList.java

@@ -0,0 +1,151 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.ambari.server.controller;
+
+import org.apache.ambari.server.orm.entities.ViewEntity;
+import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
+import org.apache.ambari.server.view.ViewContextImpl;
+import org.apache.ambari.server.view.ViewInstanceHandlerList;
+import org.apache.ambari.server.view.ViewRegistry;
+import org.apache.ambari.view.SystemException;
+import org.apache.ambari.view.ViewContext;
+import org.eclipse.jetty.server.Handler;
+import org.eclipse.jetty.webapp.WebAppContext;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * An Ambari specific extension of the FailsafeHandlerList that allows for the addition
+ * of view instances as handlers.
+ */
+@Singleton
+public class AmbariHandlerList extends FailsafeHandlerList implements ViewInstanceHandlerList {
+
+  /**
+   * The view registry.
+   */
+  @Inject
+  ViewRegistry viewRegistry;
+
+  /**
+   * The Handler factory.
+   */
+  private final HandlerFactory handlerFactory;
+
+  /**
+   * Mapping of view instance entities to handlers.
+   */
+  private final Map<ViewInstanceEntity, Handler> handlerMap = new HashMap<ViewInstanceEntity, Handler>();
+
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct an AmbariHandlerList.
+   */
+  public AmbariHandlerList() {
+    super(true);
+    this.handlerFactory = new HandlerFactory() {
+      @Override
+      public Handler create(ViewInstanceEntity viewInstanceDefinition, String webApp, String contextPath) {
+
+        WebAppContext context = new WebAppContext(webApp, contextPath);
+
+        context.setClassLoader(viewInstanceDefinition.getViewEntity().getClassLoader());
+        context.setAttribute(ViewContext.CONTEXT_ATTRIBUTE, new ViewContextImpl(viewInstanceDefinition, viewRegistry));
+
+        return context;
+      }
+    };
+  }
+
+  /**
+   * Construct an AmbariHandlerList with the given handler factory.
+   *
+   * @param handlerFactory  the handler factory.
+   */
+  protected AmbariHandlerList(HandlerFactory handlerFactory) {
+    super(true);
+    this.handlerFactory = handlerFactory;
+  }
+
+
+  // ----- ViewInstanceHandler -----------------------------------------------
+
+  @Override
+  public void addViewInstance(ViewInstanceEntity viewInstanceDefinition) throws SystemException {
+    Handler handler = getHandler(viewInstanceDefinition);
+    handlerMap.put(viewInstanceDefinition, handler);
+    addFailsafeHandler(handler);
+    // if this is running then start the handler being added...
+    if(!isStopped() && !isStopping()) {
+      try {
+        handler.start();
+      } catch (Exception e) {
+        throw new SystemException("Caught exception adding a view instance.", e);
+      }
+    }
+  }
+
+  @Override
+  public void removeViewInstance(ViewInstanceEntity viewInstanceDefinition) {
+    Handler handler = handlerMap.get(viewInstanceDefinition);
+    if (handler != null) {
+      removeHandler(handler);
+    }
+  }
+
+
+  // ----- helper methods ----------------------------------------------------
+
+  /**
+   * Get a Handler for the given view instance.
+   *
+   * @param viewInstanceDefinition  the view instance definition
+   *
+   * @return a handler
+   *
+   * @throws org.apache.ambari.view.SystemException if an handler can not be obtained for the given view instance
+   */
+  private Handler getHandler(ViewInstanceEntity viewInstanceDefinition)
+      throws SystemException {
+    ViewEntity viewDefinition = viewInstanceDefinition.getViewEntity();
+    return handlerFactory.create(viewInstanceDefinition, viewDefinition.getArchive(), viewInstanceDefinition.getContextPath());
+  }
+
+
+  // ----- inner interface : HandlerFactory ----------------------------------
+
+  /**
+   * Factory for creating Handler instances.
+   */
+  protected interface HandlerFactory {
+    /**
+     * Create a Handler.
+     *
+     * @param webApp       the web app archive
+     * @param contextPath  the context path
+     *
+     * @return a new Handler instance
+     */
+    public Handler create(ViewInstanceEntity viewInstanceDefinition, String webApp, String contextPath);
+  }
+}

+ 8 - 5
ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java

@@ -149,6 +149,12 @@ public class AmbariServer {
   @Inject
   ViewRegistry viewRegistry;
 
+  /**
+   * The handler list for deployed web apps.
+   */
+  @Inject
+  AmbariHandlerList handlerList;
+
   public String getServerOsType() {
     return configs.getServerOsType();
   }
@@ -300,11 +306,9 @@ public class AmbariServer {
       root.addServlet(sh, "/api/v1/*");
       sh.setInitOrder(2);
 
-      FailsafeHandlerList handlerList = new FailsafeHandlerList();
-
       try {
         for (ViewInstanceEntity entity : viewRegistry.readViewArchives(configs)){
-          handlerList.addFailsafeHandler(viewRegistry.getWebAppContext(entity));
+          handlerList.addViewInstance(entity);
         }
       } catch (SystemException e) {
         LOG.error("Caught exception deploying views.", e);
@@ -459,7 +463,7 @@ public class AmbariServer {
   }
 
   /**
-   * Creates default users and roles if in-memory database is used
+   * Creates default users if in-memory database is used
    */
   @Transactional
   protected void initDB() {
@@ -467,7 +471,6 @@ public class AmbariServer {
       LOG.info("Database init needed - creating default data");
       Users users = injector.getInstance(Users.class);
 
-      users.createDefaultRoles();
       users.createUser("admin", "admin", true, true);
       users.createUser("user", "user", true, false);
 

+ 2 - 0
ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java

@@ -76,6 +76,7 @@ import org.apache.ambari.server.state.scheduler.RequestExecution;
 import org.apache.ambari.server.state.scheduler.RequestExecutionFactory;
 import org.apache.ambari.server.state.scheduler.RequestExecutionImpl;
 import org.apache.ambari.server.state.svccomphost.ServiceComponentHostImpl;
+import org.apache.ambari.server.view.ViewInstanceHandlerList;
 import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.security.crypto.password.StandardPasswordEncoder;
 
@@ -201,6 +202,7 @@ public class ControllerModule extends AbstractModule {
     bind(ServerActionManager.class).to(ServerActionManagerImpl.class);
     bind(ExecutionScheduler.class).to(ExecutionSchedulerImpl.class);
     bind(DBAccessor.class).to(DBAccessorImpl.class);
+    bind(ViewInstanceHandlerList.class).to(AmbariHandlerList.class);
 
     requestStaticInjection(ExecutionCommandWrapper.class);
   }

+ 38 - 2
ambari-server/src/main/java/org/apache/ambari/server/controller/FailsafeHandlerList.java

@@ -50,16 +50,40 @@ public class FailsafeHandlerList extends HandlerCollection {
    */
   private final List<Handler> failsafeHandlers = new ArrayList<Handler>();
 
+
+  // ----- Constructors ------------------------------------------------------
+
+  /**
+   * Construct a FailsafeHandlerList.
+   */
+  public FailsafeHandlerList() {
+  }
+
+  /**
+   * Construct a FailsafeHandlerList.
+   *
+   * @param mutableWhenRunning allow for changes while running
+   */
+  public FailsafeHandlerList(boolean mutableWhenRunning) {
+    super(mutableWhenRunning);
+  }
+
+
+  // ----- FailsafeHandlerList -----------------------------------------------
+
   /**
    * Adds handler to collection and marks it as fail-safe.
    *
-   * @param handler failsafe handler
+   * @param handler fail-safe handler
    */
   public void addFailsafeHandler(Handler handler) {
     addHandler(handler);
     failsafeHandlers.add(handler);
   }
 
+
+  // ----- HandlerCollection -------------------------------------------------
+
   @Override
   public void removeHandler(Handler handler) {
     super.removeHandler(handler);
@@ -74,11 +98,16 @@ public class FailsafeHandlerList extends HandlerCollection {
   public void handle(String target, Request baseRequest,
       HttpServletRequest request, HttpServletResponse response)
       throws IOException, ServletException {
+
     final Handler[] handlers = getHandlers();
 
     if (handlers != null && isStarted()) {
+
+      List<Handler> nonFailsafeHandlers = new ArrayList<Handler>();
+
       for (int i = 0; i < handlers.length; i++) {
         final Handler handler = handlers[i];
+        // Do all of the fail-safe handlers first...
         if (failsafeHandlers.contains(handler)) {
           try {
             final FailsafeServletResponse responseWrapper = new FailsafeServletResponse(response);
@@ -92,12 +121,19 @@ public class FailsafeHandlerList extends HandlerCollection {
             continue;
           }
         } else {
-          handler.handle(target, baseRequest, request, response);
+          nonFailsafeHandlers.add(handler);
         }
         if (baseRequest.isHandled()) {
           return;
         }
       }
+
+      for (Handler handler : nonFailsafeHandlers) {
+        handler.handle(target, baseRequest, request, response);
+        if (baseRequest.isHandled()) {
+          return;
+        }
+      }
     }
   }
 }

+ 1 - 1
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClientConfigResourceProvider.java

@@ -291,7 +291,7 @@ public class ClientConfigResourceProvider extends AbstractControllerResourceProv
         throw new SystemException("Failed to write configurations to json file ", e);
       }
 
-      String cmd = "python " + commandScriptAbsolute + " generate_configs " + jsonFileName.getAbsolutePath() + " " +
+      String cmd = "ambari-python-wrap " + commandScriptAbsolute + " generate_configs " + jsonFileName.getAbsolutePath() + " " +
               packageFolderAbsolute + " " + TMP_PATH + File.separator + "structured-out.json" + " INFO " + TMP_PATH;
 
       try {

+ 21 - 5
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ConfigGroupResourceProvider.java

@@ -17,6 +17,8 @@
  */
 package org.apache.ambari.server.controller.internal;
 
+import com.google.common.collect.MapDifference;
+import com.google.common.collect.Maps;
 import org.apache.ambari.server.AmbariException;
 import org.apache.ambari.server.ClusterNotFoundException;
 import org.apache.ambari.server.ConfigGroupNotFoundException;
@@ -44,6 +46,7 @@ import org.apache.ambari.server.state.ConfigImpl;
 import org.apache.ambari.server.state.Host;
 import org.apache.ambari.server.state.configgroup.ConfigGroup;
 import org.apache.ambari.server.state.configgroup.ConfigGroupFactory;
+import org.apache.commons.lang.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -457,9 +460,10 @@ public class ConfigGroupResourceProvider extends
         request.getConfigs(), hosts);
 
       String serviceName = null;
-      if (configGroup.getConfigurations() != null) {
-        serviceName = cluster.getServiceForConfigTypes(configGroup.getConfigurations().keySet());
+      if (request.getConfigs() != null && !request.getConfigs().isEmpty()) {
+        serviceName = cluster.getServiceForConfigTypes(request.getConfigs().keySet());
       }
+      configGroup.setServiceName(serviceName);
 
       // Persist before add, since id is auto-generated
       configLogger.info("Persisting new Config group"
@@ -472,6 +476,9 @@ public class ConfigGroupResourceProvider extends
       cluster.addConfigGroup(configGroup);
       if (serviceName != null) {
         cluster.createServiceConfigVersion(serviceName, getManagementController().getAuthName(), null, configGroup);
+      } else {
+        LOG.warn("Could not determine service name for config group {}, service config version not created",
+            configGroup.getId());
       }
 
       ConfigGroupResponse response = new ConfigGroupResponse(configGroup
@@ -517,9 +524,15 @@ public class ConfigGroupResourceProvider extends
                                  + ", clusterName = " + request.getClusterName()
                                  + ", groupId = " + request.getId());
       }
-      String serviceName = null;
-      if (configGroup.getConfigurations() != null) {
-        serviceName = cluster.getServiceForConfigTypes(configGroup.getConfigurations().keySet());
+      String serviceName = configGroup.getServiceName();
+      String requestServiceName = cluster.getServiceForConfigTypes(request.getConfigs().keySet());
+      if (serviceName != null && requestServiceName !=null && !StringUtils.equals(serviceName, requestServiceName)) {
+        throw new IllegalArgumentException("Config group " + configGroup.getId() +
+            " is mapped to service " + serviceName + ", " +
+            "but request contain configs from service " + requestServiceName);
+      } else if (serviceName == null && requestServiceName != null) {
+        configGroup.setServiceName(requestServiceName);
+        serviceName = requestServiceName;
       }
 
       // Update hosts
@@ -555,6 +568,9 @@ public class ConfigGroupResourceProvider extends
       configGroup.persist();
       if (serviceName != null) {
         cluster.createServiceConfigVersion(serviceName, getManagementController().getAuthName(), null, configGroup);
+      } else {
+        LOG.warn("Could not determine service name for config group {}, service config version not created",
+            configGroup.getId());
       }
     }
 

+ 5 - 1
ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ViewInstanceResourceProvider.java

@@ -331,7 +331,11 @@ public class ViewInstanceResourceProvider extends AbstractResourceProvider {
     return new Command<Void>() {
       @Override
       public Void invoke() throws AmbariException {
-        ViewRegistry.getInstance().installViewInstance(toEntity(properties));
+        try {
+          ViewRegistry.getInstance().installViewInstance(toEntity(properties));
+        } catch (org.apache.ambari.view.SystemException e) {
+          throw new AmbariException("Caught exception trying to create view instance.", e);
+        }
         return null;
       }
     };

+ 14 - 2
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/PrincipalDAO.java

@@ -22,10 +22,11 @@ import com.google.inject.Inject;
 import com.google.inject.Provider;
 import com.google.inject.Singleton;
 import com.google.inject.persist.Transactional;
-import org.apache.ambari.server.orm.entities.PrincipalEntity;
 
+import org.apache.ambari.server.orm.entities.PrincipalEntity;
 import javax.persistence.EntityManager;
 import javax.persistence.TypedQuery;
+
 import java.util.List;
 
 /**
@@ -44,7 +45,6 @@ public class PrincipalDAO {
   /**
    * Find a principal with the given id.
    *
-   *
    * @param id  type id
    *
    * @return  a matching principal type  or null
@@ -63,6 +63,18 @@ public class PrincipalDAO {
     return daoUtils.selectList(query);
   }
 
+  /**
+   * Find principals having specified permission.
+   *
+   * @param id permission id
+   * @return all principals having specified permission
+   */
+  public List<PrincipalEntity> findByPermissionId(Integer id) {
+    TypedQuery<PrincipalEntity> query = entityManagerProvider.get().createNamedQuery("principalByPrivilegeId", PrincipalEntity.class);
+    query.setParameter("permission_id", id);
+    return daoUtils.selectList(query);
+  }
+
   /**
    * Make an instance managed and persistent.
    *

+ 0 - 69
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/RoleDAO.java

@@ -1,69 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 org.apache.ambari.server.orm.dao;
-
-import com.google.inject.Inject;
-import com.google.inject.Provider;
-import com.google.inject.Singleton;
-import com.google.inject.persist.Transactional;
-import org.apache.ambari.server.orm.RequiresSession;
-import org.apache.ambari.server.orm.entities.RoleEntity;
-
-import javax.persistence.EntityManager;
-import java.util.List;
-
-@Singleton
-public class RoleDAO {
-
-  @Inject
-  Provider<EntityManager> entityManagerProvider;
-  @Inject
-  DaoUtils daoUtils;
-
-  @RequiresSession
-  public RoleEntity findByName(String roleName) {
-    return entityManagerProvider.get().find(RoleEntity.class, roleName.toLowerCase());
-  }
-
-  @RequiresSession
-  public List<RoleEntity> findAll() {
-    return daoUtils.selectAll(entityManagerProvider.get(), RoleEntity.class);
-  }
-
-  @Transactional
-  public void create(RoleEntity role) {
-    role.setRoleName(role.getRoleName().toLowerCase());
-    entityManagerProvider.get().persist(role);
-  }
-
-  @Transactional
-  public RoleEntity merge(RoleEntity role) {
-    return entityManagerProvider.get().merge(role);
-  }
-
-  @Transactional
-  public void remove(RoleEntity role) {
-    entityManagerProvider.get().remove(merge(role));
-  }
-
-  @Transactional
-  public void removeByName(String roleName) {
-    remove(findByName(roleName));
-  }
-
-}

+ 8 - 1
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/ServiceConfigDAO.java

@@ -32,7 +32,6 @@ import java.util.List;
 import java.util.Map;
 
 @Singleton
-@RequiresSession
 public class ServiceConfigDAO {
   @Inject
   Provider<EntityManager> entityManagerProvider;
@@ -40,10 +39,12 @@ public class ServiceConfigDAO {
   DaoUtils daoUtils;
 
 
+  @RequiresSession
   public ServiceConfigEntity find(Long serviceConfigId) {
     return entityManagerProvider.get().find(ServiceConfigEntity.class, serviceConfigId);
   }
 
+  @RequiresSession
   public ServiceConfigEntity findByServiceAndVersion(String serviceName, Long version) {
     TypedQuery<ServiceConfigEntity> query = entityManagerProvider.get().
         createQuery("SELECT scv FROM ServiceConfigEntity scv " +
@@ -51,6 +52,7 @@ public class ServiceConfigDAO {
     return daoUtils.selectOne(query, serviceName, version);
   }
 
+  @RequiresSession
   public Map<String, Long> findMaxVersions(Long clusterId) {
     Map<String, Long> maxVersions = new HashMap<String, Long>();
 
@@ -64,6 +66,7 @@ public class ServiceConfigDAO {
     return maxVersions;
   }
 
+  @RequiresSession
   public List<Long> getServiceConfigVersionsByConfig(Long clusterId, String configType, Long configVersion) {
     TypedQuery<Long> query = entityManagerProvider.get().createQuery("SELECT scv.version " +
         "FROM ServiceConfigEntity scv JOIN scv.clusterConfigEntities cc " +
@@ -71,6 +74,7 @@ public class ServiceConfigDAO {
     return daoUtils.selectList(query, clusterId, configType, configVersion);
   }
 
+  @RequiresSession
   public List<ServiceConfigEntity> getLastServiceConfigs(Long clusterId) {
     TypedQuery<ServiceConfigEntity> query = entityManagerProvider.get().
       createQuery("SELECT scv FROM ServiceConfigEntity scv " +
@@ -82,6 +86,7 @@ public class ServiceConfigDAO {
     return daoUtils.selectList(query, clusterId);
   }
 
+  @RequiresSession
   public ServiceConfigEntity getLastServiceConfig(Long clusterId, String serviceName) {
     TypedQuery<ServiceConfigEntity> query = entityManagerProvider.get().
         createQuery("SELECT scv FROM ServiceConfigEntity scv " +
@@ -92,6 +97,7 @@ public class ServiceConfigDAO {
     return daoUtils.selectOne(query, clusterId, serviceName);
   }
 
+  @RequiresSession
   public ServiceConfigEntity findMaxVersion(Long clusterId, String serviceName) {
     TypedQuery<ServiceConfigEntity> query = entityManagerProvider.get().createQuery("SELECT scv FROM ServiceConfigEntity scv " +
       "WHERE scv.clusterId=?1 AND scv.serviceName=?2 AND scv.version = (" +
@@ -101,6 +107,7 @@ public class ServiceConfigDAO {
     return daoUtils.selectSingle(query, clusterId, serviceName);
   }
 
+  @RequiresSession
   public List<ServiceConfigEntity> getServiceConfigs(Long clusterId) {
     TypedQuery<ServiceConfigEntity> query = entityManagerProvider.get()
       .createQuery("SELECT scv FROM ServiceConfigEntity scv " +

+ 0 - 8
ambari-server/src/main/java/org/apache/ambari/server/orm/dao/UserDAO.java

@@ -30,7 +30,6 @@ import javax.persistence.NoResultException;
 import javax.persistence.TypedQuery;
 import java.util.Collections;
 import java.util.List;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 
 @Singleton
 public class UserDAO {
@@ -51,13 +50,6 @@ public class UserDAO {
     return daoUtils.selectList(query);
   }
 
-  @RequiresSession
-  public List<UserEntity> findAllLocalUsersByRole(RoleEntity roleEntity) {
-    TypedQuery<UserEntity> query = entityManagerProvider.get().createQuery("SELECT role.userEntities FROM RoleEntity role WHERE role = :roleEntity", UserEntity.class);
-    query.setParameter("roleEntity", roleEntity);
-    return query.getResultList();
-  }
-
   @RequiresSession
   public UserEntity findLocalUserByName(String userName) {
     TypedQuery<UserEntity> query = entityManagerProvider.get().createNamedQuery("localUserByName", UserEntity.class);

+ 11 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ConfigGroupEntity.java

@@ -73,6 +73,9 @@ public class ConfigGroupEntity {
   @Column(name = "create_timestamp", nullable=false, insertable=true, updatable=false)
   private long timestamp;
 
+  @Column(name = "service_name")
+  private String serviceName;
+
   @ManyToOne
   @JoinColumn(name = "cluster_id", referencedColumnName = "cluster_id", nullable = false)
   private ClusterEntity clusterEntity;
@@ -178,4 +181,12 @@ public class ConfigGroupEntity {
     result = 31 * result + tag.hashCode();
     return result;
   }
+
+  public String getServiceName() {
+    return serviceName;
+  }
+
+  public void setServiceName(String serviceName) {
+    this.serviceName = serviceName;
+  }
 }

+ 5 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/PrincipalEntity.java

@@ -29,6 +29,8 @@ import javax.persistence.Id;
 import javax.persistence.JoinColumn;
 import javax.persistence.JoinColumns;
 import javax.persistence.ManyToOne;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
 import javax.persistence.OneToMany;
 import javax.persistence.Table;
 import javax.persistence.TableGenerator;
@@ -44,6 +46,9 @@ import javax.persistence.TableGenerator;
     , initialValue = 2
     , allocationSize = 1
 )
+@NamedQueries({
+  @NamedQuery(name = "principalByPrivilegeId", query = "SELECT principal FROM PrincipalEntity principal JOIN principal.privileges privilege WHERE privilege.permission.id=:permission_id")
+})
 public class PrincipalEntity {
 
   /**

+ 0 - 70
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/RoleEntity.java

@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 org.apache.ambari.server.orm.entities;
-
-import javax.persistence.*;
-import java.util.Set;
-
-@javax.persistence.Table(name = "roles")
-@Entity
-public class RoleEntity {
-
-  @Column(name = "role_name")
-  @Id
-  private String roleName;
-
-  @JoinTable(name = "user_roles",
-      joinColumns = {@JoinColumn(name = "role_name", referencedColumnName = "role_name")},
-      inverseJoinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "user_id")})
-  @ManyToMany(cascade = CascadeType.ALL)
-  private Set<UserEntity> userEntities;
-
-  public String getRoleName() {
-    return roleName;
-  }
-
-  public void setRoleName(String roleName) {
-    this.roleName = roleName;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (o == null || getClass() != o.getClass()) return false;
-
-    RoleEntity that = (RoleEntity) o;
-
-    if (roleName != null ? !roleName.equals(that.roleName) : that.roleName != null) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    return roleName != null ? roleName.hashCode() : 0;
-  }
-
-  public Set<org.apache.ambari.server.orm.entities.UserEntity> getUserEntities() {
-    return userEntities;
-  }
-
-  public void setUserEntities(Set<org.apache.ambari.server.orm.entities.UserEntity> userEntities) {
-    this.userEntities = userEntities;
-  }
-}

+ 0 - 11
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/UserEntity.java

@@ -59,9 +59,6 @@ public class UserEntity {
   @Column(name = "active")
   private Integer active = 1;
 
-  @ManyToMany(mappedBy = "userEntities")
-  private Set<RoleEntity> roleEntities;
-
   @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
   private Set<MemberEntity> memberEntities;
 
@@ -118,14 +115,6 @@ public class UserEntity {
     this.createTime = createTime;
   }
 
-  public Set<RoleEntity> getRoleEntities() {
-    return roleEntities;
-  }
-
-  public void setRoleEntities(Set<RoleEntity> roleEntities) {
-    this.roleEntities = roleEntities;
-  }
-
   public Set<MemberEntity> getMemberEntities() {
     return memberEntities;
   }

+ 20 - 0
ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ViewInstanceEntity.java

@@ -748,4 +748,24 @@ public class ViewInstanceEntity implements ViewInstanceDefinition {
   protected void setSecurityHelper(SecurityHelper securityHelper) {
     this.securityHelper = securityHelper;
   }
+
+
+  // ----- Object overrides --------------------------------------------------
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    ViewInstanceEntity that = (ViewInstanceEntity) o;
+
+    return name.equals(that.name) && viewName.equals(that.viewName);
+  }
+
+  @Override
+  public int hashCode() {
+    int result = viewName.hashCode();
+    result = 31 * result + name.hashCode();
+    return result;
+  }
 }

+ 6 - 128
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthoritiesPopulator.java

@@ -18,19 +18,12 @@
 package org.apache.ambari.server.security.authorization;
 
 import com.google.inject.Inject;
-import com.google.inject.persist.Transactional;
-import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.dao.MemberDAO;
-import org.apache.ambari.server.orm.dao.PrincipalDAO;
-import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.PrivilegeDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.MemberEntity;
 import org.apache.ambari.server.orm.entities.PrincipalEntity;
-import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -39,6 +32,7 @@ import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
 
 import java.util.Collection;
+import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
 
@@ -48,61 +42,31 @@ import java.util.List;
 public class AmbariLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
   private static final Logger log = LoggerFactory.getLogger(AmbariLdapAuthoritiesPopulator.class);
 
-  Configuration configuration;
   private AuthorizationHelper authorizationHelper;
   UserDAO userDAO;
-  RoleDAO roleDAO;
-  PrincipalDAO principalDAO;
-  PrincipalTypeDAO principalTypeDAO;
   MemberDAO memberDAO;
   PrivilegeDAO privilegeDAO;
 
-  private static final String AMBARI_ADMIN_LDAP_ATTRIBUTE_KEY = "ambari_admin";
-
   @Inject
-  public AmbariLdapAuthoritiesPopulator(Configuration configuration, AuthorizationHelper authorizationHelper,
-                                        UserDAO userDAO, RoleDAO roleDAO,
-                                        PrincipalDAO principalDAO, PrincipalTypeDAO principalTypeDAO,
-                                        MemberDAO memberDAO, PrivilegeDAO privilegeDAO) {
-    this.configuration = configuration;
+  public AmbariLdapAuthoritiesPopulator(AuthorizationHelper authorizationHelper,
+                                        UserDAO userDAO, MemberDAO memberDAO, PrivilegeDAO privilegeDAO) {
     this.authorizationHelper = authorizationHelper;
     this.userDAO = userDAO;
-    this.roleDAO = roleDAO;
-    this.principalDAO = principalDAO;
-    this.principalTypeDAO = principalTypeDAO;
     this.memberDAO = memberDAO;
     this.privilegeDAO = privilegeDAO;
   }
 
   @Override
   public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
-    log.info("Get roles for user " + username + " from local DB");
+    log.info("Get authorities for user " + username + " from local DB");
 
     UserEntity user;
 
     user = userDAO.findLdapUserByName(username);
 
     if (user == null) {
-      log.info("User " + username + " not present in local DB - creating");
-
-      createLdapUser(username);
-      user = userDAO.findLdapUserByName(username);
-    }
-
-    //don't remove admin role from user if group mapping was not configured
-    if (configuration.getLdapServerProperties().isGroupMappingEnabled()) {
-      //Adding an "admin" user role if user is a member of ambari administrators
-      // LDAP group
-      Boolean isAdmin =
-          (Boolean) userData.getObjectAttribute(AMBARI_ADMIN_LDAP_ATTRIBUTE_KEY);
-      if ((isAdmin != null) && isAdmin) {
-        log.info("Adding admin role to LDAP user " + username);
-        addRole(user, configuration.getConfigsMap().
-            get(Configuration.ADMIN_ROLE_NAME_KEY));
-      } else {
-        removeRole(user, configuration.getConfigsMap().
-            get(Configuration.ADMIN_ROLE_NAME_KEY));
-      }
+      log.error("Can't get authorities for user " + username + ", he is not present in local DB");
+      return Collections.emptyList();
     }
 
     // get all of the privileges for the user
@@ -120,90 +84,4 @@ public class AmbariLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator
 
     return authorizationHelper.convertPrivilegesToAuthorities(privilegeEntities);
   }
-
-  /**
-   * Creates record in local DB for LDAP user
-   * @param username - name of user to create
-   */
-  @Transactional
-  void createLdapUser(String username) {
-    // create an admin principal to represent this user
-    PrincipalTypeEntity principalTypeEntity = principalTypeDAO.findById(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
-    if (principalTypeEntity == null) {
-      principalTypeEntity = new PrincipalTypeEntity();
-      principalTypeEntity.setId(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
-      principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
-      principalTypeDAO.create(principalTypeEntity);
-    }
-    PrincipalEntity principalEntity = new PrincipalEntity();
-    principalEntity.setPrincipalType(principalTypeEntity);
-    principalDAO.create(principalEntity);
-
-    UserEntity newUser = new UserEntity();
-    newUser.setLdapUser(true);
-    newUser.setUserName(username);
-    newUser.setPrincipal(principalEntity);
-
-    userDAO.create(newUser);
-
-    //Adding a default "user" role
-    addRole(newUser, configuration.getConfigsMap().
-        get(Configuration.USER_ROLE_NAME_KEY));
-  }
-
-  /**
-   * Adds role to user's role entities
-   * Adds user to roleName's user entities
-   *
-   * @param user - the user entity to be modified
-   * @param roleName - the role to add to user's roleEntities
-   */
-  @Transactional
-  void addRole(UserEntity user, String roleName) {
-    log.info("Using default role name " + roleName);
-
-    RoleEntity roleEntity = roleDAO.findByName(roleName);
-
-    if (roleEntity == null) {
-      log.info("Role " + roleName + " not present in local DB - creating");
-      roleEntity = new RoleEntity();
-      roleEntity.setRoleName(roleName);
-      roleDAO.create(roleEntity);
-      roleEntity = roleDAO.findByName(roleEntity.getRoleName());
-    }
-
-    UserEntity userEntity = userDAO.findLdapUserByName(user.getUserName());
-    if (userEntity == null) {
-      userDAO.create(user);
-      userEntity = userDAO.findLdapUserByName(user.getUserName());
-    }
-
-    if (!userEntity.getRoleEntities().contains(roleEntity)) {
-      userEntity.getRoleEntities().add(roleEntity);
-      roleEntity.getUserEntities().add(userEntity);
-      roleDAO.merge(roleEntity);
-      userDAO.merge(userEntity);
-    }
-  }
-
-  /**
-   * Remove role "roleName" from user "user"
-   *
-   * @param user      the user entity
-   * @param roleName  the role name
-   */
-  @Transactional
-  void removeRole(UserEntity user, String roleName) {
-    UserEntity userEntity = userDAO.findByPK(user.getUserId());
-    RoleEntity roleEntity = roleDAO.findByName(roleName);
-
-    if (userEntity.getRoleEntities().contains(roleEntity)) {
-      log.info("Removing admin role from LDAP user " + user.getUserName());
-      userEntity.getRoleEntities().remove(roleEntity);
-      roleEntity.getUserEntities().remove(userEntity);
-      userDAO.merge(userEntity);
-      roleDAO.merge(roleEntity);
-    }
-
-  }
 }

+ 1 - 7
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsService.java

@@ -22,7 +22,6 @@ import com.google.inject.Injector;
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.dao.MemberDAO;
 import org.apache.ambari.server.orm.dao.PrivilegeDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.MemberEntity;
 import org.apache.ambari.server.orm.entities.PrincipalEntity;
@@ -46,19 +45,17 @@ public class AmbariLocalUserDetailsService implements UserDetailsService {
   Configuration configuration;
   private AuthorizationHelper authorizationHelper;
   UserDAO userDAO;
-  RoleDAO roleDAO;
   MemberDAO memberDAO;
   PrivilegeDAO privilegeDAO;
 
   @Inject
   public AmbariLocalUserDetailsService(Injector injector, Configuration configuration,
                                        AuthorizationHelper authorizationHelper, UserDAO userDAO,
-                                       RoleDAO roleDAO, MemberDAO memberDAO, PrivilegeDAO privilegeDAO) {
+                                       MemberDAO memberDAO, PrivilegeDAO privilegeDAO) {
     this.injector = injector;
     this.configuration = configuration;
     this.authorizationHelper = authorizationHelper;
     this.userDAO = userDAO;
-    this.roleDAO = roleDAO;
     this.memberDAO = memberDAO;
     this.privilegeDAO = privilegeDAO;
   }
@@ -79,9 +76,6 @@ public class AmbariLocalUserDetailsService implements UserDetailsService {
     if (user == null) {
       log.info("user not found ");
       throw new UsernameNotFoundException("Username " + username + " not found");
-    }else if (user.getRoleEntities().isEmpty()) {
-      log.info("No authorities for user");
-      throw new UsernameNotFoundException("Username " + username + " has no roles");
     }
 
     // get all of the privileges for the user

+ 0 - 9
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/User.java

@@ -24,7 +24,6 @@ import java.util.Date;
 import org.apache.ambari.server.orm.entities.MemberEntity;
 import org.apache.ambari.server.orm.entities.PermissionEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 
 /**
@@ -36,7 +35,6 @@ public class User {
   final boolean ldapUser;
   final Date createTime;
   final boolean active;
-  final Collection<String> roles = new ArrayList<String>();
   final Collection<String> groups = new ArrayList<String>();
   boolean admin = false;
 
@@ -46,9 +44,6 @@ public class User {
     createTime = userEntity.getCreateTime();
     ldapUser = userEntity.getLdapUser();
     active = userEntity.getActive();
-    for (RoleEntity roleEntity : userEntity.getRoleEntities()) {
-      roles.add(roleEntity.getRoleName());
-    }
     for (MemberEntity memberEntity : userEntity.getMemberEntities()) {
       groups.add(memberEntity.getGroup().getGroupName());
     }
@@ -84,10 +79,6 @@ public class User {
     return admin;
   }
 
-  public Collection<String> getRoles() {
-    return roles;
-  }
-
   public Collection<String> getGroups() {
     return groups;
   }

+ 9 - 138
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/Users.java

@@ -32,7 +32,6 @@ import org.apache.ambari.server.orm.dao.PrincipalDAO;
 import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.PrivilegeDAO;
 import org.apache.ambari.server.orm.dao.ResourceDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.GroupEntity;
 import org.apache.ambari.server.orm.entities.MemberEntity;
@@ -40,7 +39,6 @@ import org.apache.ambari.server.orm.entities.PermissionEntity;
 import org.apache.ambari.server.orm.entities.PrincipalEntity;
 import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -65,8 +63,6 @@ public class Users {
   @Inject
   protected UserDAO userDAO;
   @Inject
-  protected RoleDAO roleDAO;
-  @Inject
   protected GroupDAO groupDAO;
   @Inject
   protected MemberDAO memberDAO;
@@ -260,27 +256,16 @@ public class Users {
     UserEntity userEntity = new UserEntity();
     userEntity.setUserName(userName);
     userEntity.setUserPassword(passwordEncoder.encode(password));
-    userEntity.setRoleEntities(new HashSet<RoleEntity>());
     userEntity.setPrincipal(principalEntity);
     if (active != null) {
       userEntity.setActive(active);
     }
 
-    RoleEntity roleEntity = roleDAO.findByName(getUserRole());
-    if (roleEntity == null) {
-      createRole(getUserRole());
-    }
-    roleEntity = roleDAO.findByName(getUserRole());
-
-    userEntity.getRoleEntities().add(roleEntity);
     userDAO.create(userEntity);
 
     if (admin != null && admin) {
       grantAdminPrivilege(userEntity.getUserId());
     }
-
-    roleEntity.getUserEntities().add(userEntity);
-    roleDAO.merge(roleEntity);
   }
 
   @Transactional
@@ -289,7 +274,7 @@ public class Users {
     if (userEntity != null) {
       if (!isUserCanBeRemoved(userEntity)){
         throw new AmbariException("Could not remove user " + userEntity.getUserName() +
-              ". System should have at least one user with administrator role.");
+              ". System should have at least one administrator.");
       }
       userDAO.remove(userEntity);
     } else {
@@ -430,58 +415,6 @@ public class Users {
     }
   }
 
-  /**
-   * Grants ADMIN role to provided user
-   * @throws AmbariException
-   */
-  public synchronized void promoteToAdmin(User user) throws AmbariException{
-    addRoleToUser(user, getAdminRole());
-  }
-
-  /**
-   * Removes ADMIN role form provided user
-   * @throws AmbariException
-   */
-  public synchronized void demoteAdmin(User user) throws AmbariException {
-    removeRoleFromUser(user, getAdminRole());
-  }
-
-  @Transactional
-  public synchronized void addRoleToUser(User user, String role)
-      throws AmbariException {
-
-    if (configuration.getLdapServerProperties().isGroupMappingEnabled() &&
-        userDAO.findLdapUserByName(user.getUserName()) != null) {
-      LOG.warn("Trying to add a role to the LDAP user"
-          + ", user=" + user.getUserName());
-      throw new AmbariException("Ldap group mapping is enabled, " +
-          "roles for LDAP users should be managed on LDAP server");
-    }
-
-    UserEntity userEntity = userDAO.findByPK(user.getUserId());
-    if (userEntity == null) {
-      throw new AmbariException("User " + user + " doesn't exist");
-    }
-
-    RoleEntity roleEntity = roleDAO.findByName(role);
-    if (roleEntity == null) {
-      LOG.warn("Trying to add user to non-existent role"
-          + ", user=" + user.getUserName()
-          + ", role=" + role);
-      throw new AmbariException("Role " + role + " doesn't exist");
-    }
-
-    if (!userEntity.getRoleEntities().contains(roleEntity)) {
-      userEntity.getRoleEntities().add(roleEntity);
-      roleEntity.getUserEntities().add(userEntity);
-      userDAO.merge(userEntity);
-      roleDAO.merge(roleEntity);
-    } else {
-      throw new AmbariException("User " + user + " already owns role " + role);
-    }
-
-  }
-
   @Transactional
   public synchronized void addMemberToGroup(String groupName, String userName)
       throws AmbariException {
@@ -513,45 +446,6 @@ public class Users {
     }
   }
 
-  @Transactional
-  public synchronized void removeRoleFromUser(User user, String role)
-      throws AmbariException {
-
-    if (configuration.getLdapServerProperties().isGroupMappingEnabled() &&
-        userDAO.findLdapUserByName(user.getUserName()) != null) {
-      LOG.warn("Trying to add a role to the LDAP user"
-          + ", user=" + user.getUserName());
-      throw new AmbariException("Ldap group mapping is enabled, " +
-          "roles for LDAP users should be managed on LDAP server");
-    }
-
-    UserEntity userEntity = userDAO.findByPK(user.getUserId());
-    if (userEntity == null) {
-      throw new AmbariException("User " + user + " doesn't exist");
-    }
-
-    RoleEntity roleEntity = roleDAO.findByName(role);
-    if (roleEntity == null) {
-      throw new AmbariException("Role " + role + " doesn't exist");
-    }
-    if (role.equals(getAdminRole())){
-      if (!isUserCanBeRemoved(userEntity)){
-        throw new AmbariException("Could not remove admin role from user " + userEntity.getUserName() +
-        ". System should have at least one user with administrator role.");
-      }
-    }
-
-    if (userEntity.getRoleEntities().contains(roleEntity)) {
-      userEntity.getRoleEntities().remove(roleEntity);
-      roleEntity.getUserEntities().remove(userEntity);
-      userDAO.merge(userEntity);
-      roleDAO.merge(roleEntity);
-    } else {
-      throw new AmbariException("User " + user + " doesn't own role " + role);
-    }
-
-  }
-
   @Transactional
   public synchronized void removeMemberFromGroup(String groupName, String userName)
       throws AmbariException {
@@ -588,10 +482,15 @@ public class Users {
 
   }
 
+  /**
+   * Performs a check if the user can be removed. Do not allow removing all admins from database.
+   *
+   * @param userEntity user to be checked
+   * @return true if user can be removed
+   */
   public synchronized boolean isUserCanBeRemoved(UserEntity userEntity){
-    RoleEntity roleEntity = new RoleEntity();
-    roleEntity.setRoleName(getAdminRole());
-    Set<UserEntity> userEntitysSet = new HashSet<UserEntity>(userDAO.findAllLocalUsersByRole(roleEntity));
+    List<PrincipalEntity> adminPrincipals = principalDAO.findByPermissionId(PermissionEntity.AMBARI_ADMIN_PERMISSION);
+    Set<UserEntity> userEntitysSet = new HashSet<UserEntity>(userDAO.findUsersByPrincipal(adminPrincipals));
     return (userEntitysSet.contains(userEntity) && userEntitysSet.size() < 2) ? false : true;
   }
 
@@ -611,32 +510,4 @@ public class Users {
     return false;
   }
 
-  public String getUserRole() {
-    return configuration.getConfigsMap().get(Configuration.USER_ROLE_NAME_KEY);
-  }
-
-  public String getAdminRole() {
-    return configuration.getConfigsMap().get(Configuration.ADMIN_ROLE_NAME_KEY);
-  }
-
-  /**
-   * Creates new role
-   */
-  public void createRole(String role) {
-    RoleEntity roleEntity = new RoleEntity();
-    roleEntity.setRoleName(role);
-    roleDAO.create(roleEntity);
-  }
-
-  /**
-   * Creates ADMIN adn USER roles if not present
-   */
-  public synchronized void createDefaultRoles() {
-    if (roleDAO.findByName(getUserRole()) == null) {
-      createRole(getUserRole());
-    }
-    if (roleDAO.findByName(getAdminRole()) == null) {
-      createRole(getAdminRole());
-    }
-  }
 }

+ 23 - 7
ambari-server/src/main/java/org/apache/ambari/server/security/authorization/internal/InternalAuthenticationToken.java

@@ -18,19 +18,26 @@
 
 package org.apache.ambari.server.security.authorization.internal;
 
+import java.util.Collection;
+import java.util.Collections;
+
 import org.apache.ambari.server.orm.entities.PermissionEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
+import org.apache.ambari.server.orm.entities.ResourceEntity;
+import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
 import org.apache.ambari.server.security.authorization.AmbariGrantedAuthority;
 import org.springframework.security.core.Authentication;
 import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.userdetails.User;
-import java.util.Collection;
-import java.util.Collections;
 
 public class InternalAuthenticationToken implements Authentication {
-
+  private static final long serialVersionUID = 1L;
+  
   private static final String INTERNAL_NAME = "internal";
   private static final PrivilegeEntity ADMIN_PRIV_ENTITY = new PrivilegeEntity();
+  static{
+    createAdminPrivilegeEntity(ADMIN_PRIV_ENTITY);
+  }
 
   // used in ClustersImpl, checkPermissions
   private static final Collection<? extends GrantedAuthority> AUTHORITIES =
@@ -40,12 +47,22 @@ public class InternalAuthenticationToken implements Authentication {
   private String token;
   private boolean authenticated = false;
 
-  static{
+
+  private static void createAdminPrivilegeEntity(PrivilegeEntity entity) {
     PermissionEntity pe = new PermissionEntity();
     pe.setId(PermissionEntity.AMBARI_ADMIN_PERMISSION);
     pe.setPermissionName(PermissionEntity.AMBARI_ADMIN_PERMISSION_NAME);
-
-    ADMIN_PRIV_ENTITY.setPermission(pe);
+    
+    entity.setPermission(pe);
+    
+    ResourceEntity resource = new ResourceEntity();
+    resource.setId(1L);
+    
+    ResourceTypeEntity rte = new ResourceTypeEntity();
+    rte.setId(ResourceTypeEntity.CLUSTER_RESOURCE_TYPE);
+    rte.setName(ResourceTypeEntity.CLUSTER_RESOURCE_TYPE_NAME);
+    resource.setResourceType(rte);
+    entity.setResource(resource);
   }
 
   public InternalAuthenticationToken(String tokenString) {
@@ -81,7 +98,6 @@ public class InternalAuthenticationToken implements Authentication {
   public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
     this.authenticated = isAuthenticated;
   }
-
   @Override
   public String getName() {
     return INTERNAL_NAME;

+ 6 - 2
ambari-server/src/main/java/org/apache/ambari/server/state/cluster/ClusterImpl.java

@@ -233,7 +233,7 @@ public class ClusterImpl implements Cluster {
   }
 
 
-  public void loadServiceConfigTypes() throws AmbariException {
+  private void loadServiceConfigTypes() throws AmbariException {
     try {
       serviceConfigTypes = collectServiceConfigTypesMapping();
     } catch (AmbariException e) {
@@ -1458,10 +1458,11 @@ public class ClusterImpl implements Cluster {
     serviceConfigEntity.setNote(note);
 
     if (configGroup != null) {
+      serviceConfigEntity.setGroupId(configGroup.getId());
       Collection<Config> configs = configGroup.getConfigurations().values();
       List<ClusterConfigEntity> configEntities = new ArrayList<ClusterConfigEntity>(configs.size());
       for (Config config : configs) {
-        configEntities.add(clusterDAO.findConfig(getClusterId(), config.getType(), config.getVersion()));
+        configEntities.add(clusterDAO.findConfig(getClusterId(), config.getType(), config.getTag()));
       }
       serviceConfigEntity.setClusterConfigEntities(configEntities);
 
@@ -1491,6 +1492,8 @@ public class ClusterImpl implements Cluster {
 
   @Override
   public String getServiceForConfigTypes(Collection<String> configTypes) {
+    //debug
+    LOG.info("Looking for service for config types {}", configTypes);
     String serviceName = null;
     for (String configType : configTypes) {
       for (Entry<String, String> entry : serviceConfigTypes.entries()) {
@@ -1506,6 +1509,7 @@ public class ClusterImpl implements Cluster {
         }
       }
     }
+    LOG.info("Service {} returning", serviceName);
     return serviceName;
   }
 

+ 4 - 0
ambari-server/src/main/java/org/apache/ambari/server/state/configgroup/ConfigGroup.java

@@ -149,4 +149,8 @@ public interface ConfigGroup {
    * Remove host mapping
    */
   public void removeHost(String hostname) throws AmbariException;
+
+  String getServiceName();
+
+  void setServiceName(String serviceName);
 }

+ 21 - 0
ambari-server/src/main/java/org/apache/ambari/server/state/configgroup/ConfigGroupImpl.java

@@ -531,4 +531,25 @@ public class ConfigGroupImpl implements ConfigGroup {
   }
 
 
+  @Override
+  public String getServiceName() {
+    readWriteLock.readLock().lock();
+    try {
+      return this.configGroupEntity.getServiceName();
+    } finally {
+      readWriteLock.readLock().unlock();
+    }
+
+  }
+
+  @Override
+  public void setServiceName(String serviceName) {
+    readWriteLock.writeLock().lock();
+    try {
+      this.configGroupEntity.setServiceName(serviceName);
+    } finally {
+      readWriteLock.writeLock().unlock();
+    }
+
+  }
 }

+ 41 - 15
ambari-server/src/main/java/org/apache/ambari/server/upgrade/UpgradeCatalog170.java

@@ -66,7 +66,6 @@ import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
 import org.apache.ambari.server.orm.entities.ResourceEntity;
 import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.apache.ambari.server.orm.entities.ViewEntity;
 import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
@@ -339,8 +338,14 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
     columns.add(new DBColumnInfo("create_timestamp", Long.class, null, null, false));
     columns.add(new DBColumnInfo("user_name", String.class, null, "_db", false));
     columns.add(new DBColumnInfo("note", char[].class, null, null, true));
+    columns.add(new DBColumnInfo("group_id", Long.class, null, null, true));
     dbAccessor.createTable("serviceconfig", columns, "service_config_id");
 
+    columns.clear();
+    columns.add(new DBColumnInfo("service_config_id", Long.class, null, null, false));
+    columns.add(new DBColumnInfo("hostname", String.class, 255, null, false));
+    dbAccessor.createTable("serviceconfighosts", columns, "service_config_id", "hostname");
+
     dbAccessor.executeQuery("ALTER TABLE serviceconfig ADD CONSTRAINT UQ_scv_service_version UNIQUE (cluster_id, service_name, version)", true);
 
     columns.clear();
@@ -352,6 +357,11 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
       new String[]{"cluster_id", "config_type", "version_tag"}, "clusterconfig",
       new String[]{"cluster_id", "type_name", "version_tag"}, true);
 
+    dbAccessor.addFKConstraint("serviceconfighosts", "FK_scvhosts_scv",
+      new String[]{"service_config_id"}, "serviceconfig",
+      new String[]{"service_config_id"}, true);
+
+    dbAccessor.addColumn("configgroup", new DBColumnInfo("service_name", String.class, 255));
 
     dbAccessor.executeQuery("INSERT INTO ambari_sequences(sequence_name, sequence_value) VALUES('alert_definition_id_seq', 0)", false);
 
@@ -504,8 +514,6 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
 
   @Override
   protected void executeDMLUpdates() throws AmbariException, SQLException {
-    String dbType = getDbType();
-
     // Update historic records with the log paths, but only enough so as to not prolong the upgrade process
     executeInTransaction(new Runnable() {
       @Override
@@ -898,7 +906,7 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
     return result;
   }
 
-  private void upgradePermissionModel() {
+  private void upgradePermissionModel() throws SQLException {
     final UserDAO userDAO = injector.getInstance(UserDAO.class);
     final PrincipalDAO principalDAO = injector.getInstance(PrincipalDAO.class);
     final PrincipalTypeDAO principalTypeDAO = injector.getInstance(PrincipalTypeDAO.class);
@@ -950,17 +958,32 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
     final PermissionEntity clusterOperatePermission = permissionDAO.findClusterOperatePermission();
     final PermissionEntity clusterReadPermission = permissionDAO.findClusterReadPermission();
     final ResourceEntity ambariResource = resourceDAO.findAmbariResource();
-    for (UserEntity user: userDAO.findAll()) {
-      boolean hasAdminRole = false;
-      boolean hasUserRole = false;
-      for (RoleEntity role: user.getRoleEntities()) {
-        if (role.getRoleName().equals("admin")) {
-          hasAdminRole = true;
-        }
-        if (role.getRoleName().equals("user")) {
-          hasUserRole = true;
+
+    final Map<UserEntity, List<String>> roles = new HashMap<UserEntity, List<String>>();
+    ResultSet resultSet = null;
+    try {
+      resultSet = dbAccessor.executeSelect("SELECT role_name, user_id FROM user_roles");
+      while (resultSet.next()) {
+        final String roleName = resultSet.getString(1);
+        final int userId = resultSet.getInt(2);
+
+        final UserEntity user = userDAO.findByPK(userId);
+        List<String> userRoles = roles.get(user);
+        if (userRoles == null) {
+          userRoles = new ArrayList<String>();
+          roles.put(user, userRoles);
         }
-        if (hasAdminRole) {
+        userRoles.add(roleName);
+      }
+    } finally {
+      if (resultSet != null) {
+        resultSet.close();
+      }
+    }
+
+    for (UserEntity user: userDAO.findAll()) {
+      for (String role: roles.get(user)) {
+        if (role.equals("admin")) {
           final PrivilegeEntity privilege = new PrivilegeEntity();
           privilege.setPermission(adminPermission);
           privilege.setPrincipal(user.getPrincipal());
@@ -976,7 +999,7 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
             user.getPrincipal().getPrivileges().add(clusterPrivilege);
           }
           userDAO.merge(user);
-        } else if (hasUserRole) {
+        } else if (role.equals("user")) {
           for (ClusterEntity cluster: clusterDAO.findAll()) {
             final PrivilegeEntity privilege = new PrivilegeEntity();
             privilege.setPermission(clusterReadPermission);
@@ -989,6 +1012,9 @@ public class UpgradeCatalog170 extends AbstractUpgradeCatalog {
         }
       }
     }
+
+    dbAccessor.dropTable("user_roles");
+    dbAccessor.dropTable("roles");
   }
 
   protected void addJobsViewPermissions() {

+ 43 - 0
ambari-server/src/main/java/org/apache/ambari/server/view/ViewInstanceHandlerList.java

@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.ambari.server.view;
+
+import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
+import org.apache.ambari.view.SystemException;
+
+/**
+ * List of handlers for deployed view instances.
+ */
+public interface ViewInstanceHandlerList {
+
+  /**
+   * Add a handler for the given view instance.
+   *
+   * @param viewInstanceDefinition  the view instance
+   *
+   * @throws SystemException if a handler the view instance can not be added
+   */
+  public void addViewInstance(ViewInstanceEntity viewInstanceDefinition) throws SystemException;
+
+  /**
+   * Remove the handler for the given view instance.
+   *
+   * @param viewInstanceDefinition  the view instance
+   */
+  public void removeViewInstance(ViewInstanceEntity viewInstanceDefinition);
+}

+ 23 - 35
ambari-server/src/main/java/org/apache/ambari/server/view/ViewRegistry.java

@@ -93,7 +93,6 @@ import org.apache.ambari.view.ViewResourceHandler;
 import org.apache.ambari.view.events.Event;
 import org.apache.ambari.view.events.Listener;
 import org.apache.commons.lang.StringUtils;
-import org.eclipse.jetty.webapp.WebAppContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.security.core.GrantedAuthority;
@@ -208,6 +207,12 @@ public class ViewRegistry {
   @Inject
   Configuration configuration;
 
+  /**
+   * The handler list.
+   */
+  @Inject
+  ViewInstanceHandlerList handlerList;
+
 
   // ----- ViewRegistry ------------------------------------------------------
 
@@ -468,9 +473,10 @@ public class ViewRegistry {
    * @throws IllegalStateException     if the given instance is not in a valid state
    * @throws IllegalArgumentException  if the view associated with the given instance
    *                                   does not exist
+   * @throws SystemException           if the instance can not be installed
    */
   public void installViewInstance(ViewInstanceEntity instanceEntity)
-      throws IllegalStateException, IllegalArgumentException {
+      throws IllegalStateException, IllegalArgumentException, SystemException {
     ViewEntity viewEntity = getDefinition(instanceEntity.getViewName());
 
     if (viewEntity != null) {
@@ -511,6 +517,9 @@ public class ViewRegistry {
         }
         // update the registry
         addInstanceDefinition(viewEntity, instanceEntity);
+
+        // add the web app context
+        handlerList.addViewInstance(instanceEntity);
       }
     } else {
       String message = "Attempt to install an instance for an unknown view " +
@@ -538,21 +547,6 @@ public class ViewRegistry {
     }
   }
 
-  /**
-   * Remove the data entry keyed by the given key from the given instance entity.
-   *
-   * @param instanceEntity  the instance entity
-   * @param key             the data key
-   */
-  public void removeInstanceData(ViewInstanceEntity instanceEntity, String key) {
-    ViewInstanceDataEntity dataEntity = instanceEntity.getInstanceData(key);
-    if (dataEntity != null) {
-      instanceDAO.removeData(dataEntity);
-    }
-    instanceEntity.removeInstanceData(key);
-    instanceDAO.merge(instanceEntity);
-  }
-
   /**
    * Uninstall a view instance for the view with the given view name.
    *
@@ -578,32 +572,26 @@ public class ViewRegistry {
         instanceDAO.remove(instanceEntity);
         viewEntity.removeInstanceDefinition(instanceName);
         removeInstanceDefinition(viewEntity, instanceName);
+
+        // remove the web app context
+        handlerList.removeViewInstance(instanceEntity);
       }
     }
   }
 
   /**
-   * Get a WebAppContext for the given view instance.
-   *
-   * @param viewInstanceDefinition  the view instance definition
-   *
-   * @return a web app context
+   * Remove the data entry keyed by the given key from the given instance entity.
    *
-   * @throws SystemException if an application context can not be obtained for the given view instance
+   * @param instanceEntity  the instance entity
+   * @param key             the data key
    */
-  public WebAppContext getWebAppContext(ViewInstanceEntity viewInstanceDefinition)
-      throws SystemException{
-    try {
-      ViewEntity viewDefinition = viewInstanceDefinition.getViewEntity();
-
-      WebAppContext context = new WebAppContext(viewDefinition.getArchive(), viewInstanceDefinition.getContextPath());
-      context.setClassLoader(viewDefinition.getClassLoader());
-      context.setAttribute(ViewContext.CONTEXT_ATTRIBUTE, new ViewContextImpl(viewInstanceDefinition, this));
-      return context;
-    } catch (Exception e) {
-      throw new SystemException("Can't get application context for view " +
-          viewInstanceDefinition.getViewEntity().getCommonName() + ".", e);
+  public void removeInstanceData(ViewInstanceEntity instanceEntity, String key) {
+    ViewInstanceDataEntity dataEntity = instanceEntity.getInstanceData(key);
+    if (dataEntity != null) {
+      instanceDAO.removeData(dataEntity);
     }
+    instanceEntity.removeInstanceData(key);
+    instanceDAO.merge(instanceEntity);
   }
 
   /**

+ 2 - 14
ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql

@@ -29,7 +29,7 @@ delimiter ;
 CREATE TABLE clusters (cluster_id BIGINT NOT NULL, resource_id BIGINT NOT NULL, cluster_info VARCHAR(255) NOT NULL, cluster_name VARCHAR(100) NOT NULL UNIQUE, provisioning_state VARCHAR(255) NOT NULL DEFAULT 'INIT', desired_cluster_state VARCHAR(255) NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, PRIMARY KEY (cluster_id));
 CREATE TABLE clusterconfig (config_id BIGINT NOT NULL, version_tag VARCHAR(255) NOT NULL, version BIGINT NOT NULL, type_name VARCHAR(255) NOT NULL, cluster_id BIGINT NOT NULL, config_data LONGTEXT NOT NULL, config_attributes LONGTEXT, create_timestamp BIGINT NOT NULL, PRIMARY KEY (config_id));
 CREATE TABLE serviceconfig (service_config_id BIGINT NOT NULL, cluster_id BIGINT NOT NULL, service_name VARCHAR(255) NOT NULL, version BIGINT NOT NULL, create_timestamp BIGINT NOT NULL, user_name VARCHAR(255) NOT NULL DEFAULT '_db', group_id BIGINT, note LONGTEXT, PRIMARY KEY (service_config_id));
-CREATE TABLE serviceconfighosts (service_config_id BIGINT NOT NULL, hostname VARCHAR(255), PRIMARY KEY(service_config_id, hostname));
+CREATE TABLE serviceconfighosts (service_config_id BIGINT NOT NULL, hostname VARCHAR(255) NOT NULL, PRIMARY KEY(service_config_id, hostname));
 CREATE TABLE serviceconfigmapping (service_config_id BIGINT NOT NULL, config_id BIGINT NOT NULL, PRIMARY KEY(service_config_id, config_id));
 CREATE TABLE clusterservices (service_name VARCHAR(255) NOT NULL, cluster_id BIGINT NOT NULL, service_enabled INTEGER NOT NULL, PRIMARY KEY (service_name, cluster_id));
 CREATE TABLE clusterstate (cluster_id BIGINT NOT NULL, current_cluster_state VARCHAR(255) NOT NULL, current_stack_version VARCHAR(255) NOT NULL, PRIMARY KEY (cluster_id));
@@ -39,7 +39,6 @@ CREATE TABLE hosts (host_name VARCHAR(255) NOT NULL, cpu_count INTEGER NOT NULL,
 CREATE TABLE hoststate (agent_version VARCHAR(255) NOT NULL, available_mem BIGINT NOT NULL, current_state VARCHAR(255) NOT NULL, health_status VARCHAR(255), host_name VARCHAR(255) NOT NULL, time_in_state BIGINT NOT NULL, maintenance_state VARCHAR(512), PRIMARY KEY (host_name));
 CREATE TABLE servicecomponentdesiredstate (component_name VARCHAR(255) NOT NULL, cluster_id BIGINT NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, desired_state VARCHAR(255) NOT NULL, service_name VARCHAR(255) NOT NULL, PRIMARY KEY (component_name, cluster_id, service_name));
 CREATE TABLE servicedesiredstate (cluster_id BIGINT NOT NULL, desired_host_role_mapping INTEGER NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, desired_state VARCHAR(255) NOT NULL, service_name VARCHAR(255) NOT NULL, maintenance_state VARCHAR(32) NOT NULL DEFAULT 'ACTIVE', PRIMARY KEY (cluster_id, service_name));
-CREATE TABLE roles (role_name VARCHAR(255) NOT NULL, PRIMARY KEY (role_name));
 CREATE TABLE users (user_id INTEGER, principal_id BIGINT NOT NULL, create_time TIMESTAMP DEFAULT NOW(), ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, user_password VARCHAR(255), active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id));
 CREATE TABLE groups (group_id INTEGER, principal_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id));
 CREATE TABLE members (member_id INTEGER, group_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (member_id));
@@ -55,10 +54,9 @@ CREATE TABLE clusterconfigmapping (type_name VARCHAR(255) NOT NULL, create_times
 CREATE TABLE hostconfigmapping (create_timestamp BIGINT NOT NULL, host_name VARCHAR(255) NOT NULL, cluster_id BIGINT NOT NULL, type_name VARCHAR(255) NOT NULL, selected INTEGER NOT NULL DEFAULT 0, service_name VARCHAR(255), version_tag VARCHAR(255) NOT NULL, user_name VARCHAR(255) NOT NULL DEFAULT '_db', PRIMARY KEY (create_timestamp, host_name, cluster_id, type_name));
 CREATE TABLE metainfo (`metainfo_key` VARCHAR(255), `metainfo_value` LONGTEXT, PRIMARY KEY (`metainfo_key`));
 CREATE TABLE ClusterHostMapping (cluster_id BIGINT NOT NULL, host_name VARCHAR(255) NOT NULL, PRIMARY KEY (cluster_id, host_name));
-CREATE TABLE user_roles (role_name VARCHAR(255) NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (role_name, user_id));
 CREATE TABLE ambari_sequences (sequence_name VARCHAR(255), sequence_value DECIMAL(38) NOT NULL, PRIMARY KEY (sequence_name));
 CREATE TABLE confgroupclusterconfigmapping (config_group_id BIGINT NOT NULL, cluster_id BIGINT NOT NULL, config_type VARCHAR(255) NOT NULL, version_tag VARCHAR(255) NOT NULL, user_name VARCHAR(255) DEFAULT '_db', create_timestamp BIGINT NOT NULL, PRIMARY KEY(config_group_id, cluster_id, config_type));
-CREATE TABLE configgroup (group_id BIGINT, cluster_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, tag VARCHAR(1024) NOT NULL, description VARCHAR(1024), create_timestamp BIGINT NOT NULL, PRIMARY KEY(group_id));
+CREATE TABLE configgroup (group_id BIGINT, cluster_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, tag VARCHAR(1024) NOT NULL, description VARCHAR(1024), create_timestamp BIGINT NOT NULL, service_name VARCHAR(255), PRIMARY KEY(group_id));
 CREATE TABLE configgrouphostmapping (config_group_id BIGINT NOT NULL, host_name VARCHAR(255) NOT NULL, PRIMARY KEY(config_group_id, host_name));
 CREATE TABLE requestschedule (schedule_id bigint, cluster_id BIGINT NOT NULL, description varchar(255), status varchar(255), batch_separation_seconds smallint, batch_toleration_limit smallint, create_user varchar(255), create_timestamp bigint, update_user varchar(255), update_timestamp bigint, minutes varchar(10), hours varchar(10), days_of_month varchar(10), month varchar(10), day_of_week varchar(10), yearToSchedule varchar(10), startTime varchar(50), endTime varchar(50), last_execution_status varchar(255), PRIMARY KEY(schedule_id));
 CREATE TABLE requestschedulebatchrequest (schedule_id bigint, batch_id bigint, request_id bigint, request_type varchar(255), request_uri varchar(1024), request_body LONGBLOB, request_status varchar(255), return_code smallint, return_message varchar(2000), PRIMARY KEY(schedule_id, batch_id));
@@ -114,8 +112,6 @@ ALTER TABLE stage ADD CONSTRAINT FK_stage_request_id FOREIGN KEY (request_id) RE
 ALTER TABLE request ADD CONSTRAINT FK_request_schedule_id FOREIGN KEY (request_schedule_id) REFERENCES requestschedule (schedule_id);
 ALTER TABLE ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_cluster_id FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
 ALTER TABLE ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_host_name FOREIGN KEY (host_name) REFERENCES hosts (host_name);
-ALTER TABLE user_roles ADD CONSTRAINT FK_user_roles_user_id FOREIGN KEY (user_id) REFERENCES users (user_id);
-ALTER TABLE user_roles ADD CONSTRAINT FK_user_roles_role_name FOREIGN KEY (role_name) REFERENCES roles (role_name);
 ALTER TABLE hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_cluster_id FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
 ALTER TABLE hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_host_name FOREIGN KEY (host_name) REFERENCES hosts (host_name);
 ALTER TABLE serviceconfigmapping ADD CONSTRAINT FK_scvm_scv FOREIGN KEY (service_config_id) REFERENCES serviceconfig(service_config_id);
@@ -287,11 +283,6 @@ insert into adminresourcetype (resource_type_id, resource_type_name)
 insert into adminresource (resource_id, resource_type_id)
   select 1, 1;
 
-insert into roles(role_name)
-  select 'admin'
-  union all
-  select 'user';
-
 insert into adminprincipaltype (principal_type_id, principal_type_name)
   select 1, 'USER'
   union all
@@ -303,9 +294,6 @@ insert into adminprincipal (principal_id, principal_type_id)
 insert into users(user_id, principal_id, user_name, user_password)
   select 1, 1, 'admin','538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
 
-insert into user_roles(role_name, user_id)
-  select 'admin',1;
-
 insert into adminpermission(permission_id, permission_name, resource_type_id)
   select 1, 'AMBARI.ADMIN', 1
   union all

+ 2 - 14
ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql

@@ -20,7 +20,7 @@
 CREATE TABLE clusters (cluster_id NUMBER(19) NOT NULL, resource_id NUMBER(19) NOT NULL, cluster_info VARCHAR2(255) NULL, cluster_name VARCHAR2(100) NOT NULL UNIQUE, provisioning_state VARCHAR2(255) DEFAULT 'INIT' NOT NULL, desired_cluster_state VARCHAR2(255) NULL, desired_stack_version VARCHAR2(255) NULL, PRIMARY KEY (cluster_id));
 CREATE TABLE clusterconfig (config_id NUMBER(19) NOT NULL, version_tag VARCHAR2(255) NOT NULL, version NUMBER(19) NOT NULL, type_name VARCHAR2(255) NOT NULL, cluster_id NUMBER(19) NOT NULL, config_data CLOB NOT NULL, config_attributes CLOB, create_timestamp NUMBER(19) NOT NULL, PRIMARY KEY (config_id));
 CREATE TABLE serviceconfig (service_config_id NUMBER(19) NOT NULL, cluster_id NUMBER(19) NOT NULL, service_name VARCHAR(255) NOT NULL, version NUMBER(19) NOT NULL, create_timestamp NUMBER(19) NOT NULL, user_name VARCHAR(255) DEFAULT '_db' NOT NULL, group_id NUMBER(19), note CLOB, PRIMARY KEY (service_config_id));
-CREATE TABLE serviceconfighosts (service_config_id NUMBER(19) NOT NULL, hostname VARCHAR(255), PRIMARY KEY(service_config_id, hostname));
+CREATE TABLE serviceconfighosts (service_config_id NUMBER(19) NOT NULL, hostname VARCHAR(255) NOT NULL, PRIMARY KEY(service_config_id, hostname));
 CREATE TABLE serviceconfigmapping (service_config_id NUMBER(19) NOT NULL, config_id NUMBER(19) NOT NULL, PRIMARY KEY(service_config_id, config_id));
 CREATE TABLE clusterservices (service_name VARCHAR2(255) NOT NULL, cluster_id NUMBER(19) NOT NULL, service_enabled NUMBER(10) NOT NULL, PRIMARY KEY (service_name, cluster_id));
 CREATE TABLE clusterstate (cluster_id NUMBER(19) NOT NULL, current_cluster_state VARCHAR2(255) NULL, current_stack_version VARCHAR2(255) NULL, PRIMARY KEY (cluster_id));
@@ -30,7 +30,6 @@ CREATE TABLE hosts (host_name VARCHAR2(255) NOT NULL, cpu_count INTEGER NOT NULL
 CREATE TABLE hoststate (agent_version VARCHAR2(255) NULL, available_mem NUMBER(19) NOT NULL, current_state VARCHAR2(255) NOT NULL, health_status VARCHAR2(255) NULL, host_name VARCHAR2(255) NOT NULL, time_in_state NUMBER(19) NOT NULL, maintenance_state VARCHAR2(512), PRIMARY KEY (host_name));
 CREATE TABLE servicecomponentdesiredstate (component_name VARCHAR2(255) NOT NULL, cluster_id NUMBER(19) NOT NULL, desired_stack_version VARCHAR2(255) NULL, desired_state VARCHAR2(255) NOT NULL, service_name VARCHAR2(255) NOT NULL, PRIMARY KEY (component_name, cluster_id, service_name));
 CREATE TABLE servicedesiredstate (cluster_id NUMBER(19) NOT NULL, desired_host_role_mapping NUMBER(10) NOT NULL, desired_stack_version VARCHAR2(255) NULL, desired_state VARCHAR2(255) NOT NULL, service_name VARCHAR2(255) NOT NULL, maintenance_state VARCHAR2(32) NOT NULL, PRIMARY KEY (cluster_id, service_name));
-CREATE TABLE roles (role_name VARCHAR2(255) NOT NULL, PRIMARY KEY (role_name));
 CREATE TABLE users (user_id NUMBER(10) NOT NULL, principal_id NUMBER(19) NOT NULL, create_time TIMESTAMP NULL, ldap_user NUMBER(10) DEFAULT 0, user_name VARCHAR2(255) NULL, user_password VARCHAR2(255) NULL, active INTEGER DEFAULT 1 NOT NULL, PRIMARY KEY (user_id));
 CREATE TABLE groups (group_id NUMBER(10) NOT NULL, principal_id NUMBER(19) NOT NULL, group_name VARCHAR2(255) NOT NULL, ldap_group NUMBER(10) DEFAULT 0, PRIMARY KEY (group_id));
 CREATE TABLE members (member_id NUMBER(10), group_id NUMBER(10) NOT NULL, user_id NUMBER(10) NOT NULL, PRIMARY KEY (member_id));
@@ -46,9 +45,8 @@ CREATE TABLE clusterconfigmapping (type_name VARCHAR2(255) NOT NULL, create_time
 CREATE TABLE hostconfigmapping (create_timestamp NUMBER(19) NOT NULL, host_name VARCHAR2(255) NOT NULL, cluster_id NUMBER(19) NOT NULL, type_name VARCHAR2(255) NOT NULL, selected NUMBER(10) NOT NULL, service_name VARCHAR2(255) NULL, version_tag VARCHAR2(255) NOT NULL, user_name VARCHAR(255) DEFAULT '_db', PRIMARY KEY (create_timestamp, host_name, cluster_id, type_name));
 CREATE TABLE metainfo ("metainfo_key" VARCHAR2(255) NOT NULL, "metainfo_value" CLOB NULL, PRIMARY KEY ("metainfo_key"));
 CREATE TABLE ClusterHostMapping (cluster_id NUMBER(19) NOT NULL, host_name VARCHAR2(255) NOT NULL, PRIMARY KEY (cluster_id, host_name));
-CREATE TABLE user_roles (role_name VARCHAR2(255) NOT NULL, user_id NUMBER(10) NOT NULL, PRIMARY KEY (role_name, user_id));
 CREATE TABLE ambari_sequences (sequence_name VARCHAR2(50) NOT NULL, sequence_value NUMBER(38) NULL, PRIMARY KEY (sequence_name));
-CREATE TABLE configgroup (group_id NUMBER(19), cluster_id NUMBER(19) NOT NULL, group_name VARCHAR2(255) NOT NULL, tag VARCHAR2(1024) NOT NULL, description VARCHAR2(1024), create_timestamp NUMBER(19) NOT NULL, PRIMARY KEY(group_id));
+CREATE TABLE configgroup (group_id NUMBER(19), cluster_id NUMBER(19) NOT NULL, group_name VARCHAR2(255) NOT NULL, tag VARCHAR2(1024) NOT NULL, description VARCHAR2(1024), create_timestamp NUMBER(19) NOT NULL, service_name VARCHAR(255), PRIMARY KEY(group_id));
 CREATE TABLE confgroupclusterconfigmapping (config_group_id NUMBER(19) NOT NULL, cluster_id NUMBER(19) NOT NULL, config_type VARCHAR2(255) NOT NULL, version_tag VARCHAR2(255) NOT NULL, user_name VARCHAR2(255) DEFAULT '_db', create_timestamp NUMBER(19) NOT NULL, PRIMARY KEY(config_group_id, cluster_id, config_type));
 CREATE TABLE configgrouphostmapping (config_group_id NUMBER(19) NOT NULL, host_name VARCHAR2(255) NOT NULL, PRIMARY KEY(config_group_id, host_name));
 CREATE TABLE requestschedule (schedule_id NUMBER(19), cluster_id NUMBER(19) NOT NULL, description VARCHAR2(255), status VARCHAR2(255), batch_separation_seconds smallint, batch_toleration_limit smallint, create_user VARCHAR2(255), create_timestamp NUMBER(19), update_user VARCHAR2(255), update_timestamp NUMBER(19), minutes VARCHAR2(10), hours VARCHAR2(10), days_of_month VARCHAR2(10), month VARCHAR2(10), day_of_week VARCHAR2(10), yearToSchedule VARCHAR2(10), startTime VARCHAR2(50), endTime VARCHAR2(50), last_execution_status VARCHAR2(255), PRIMARY KEY(schedule_id));
@@ -106,8 +104,6 @@ ALTER TABLE stage ADD CONSTRAINT FK_stage_request_id FOREIGN KEY (request_id) RE
 ALTER TABLE request ADD CONSTRAINT FK_request_schedule_id FOREIGN KEY (request_schedule_id) REFERENCES requestschedule (schedule_id);
 ALTER TABLE ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_cluster_id FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
 ALTER TABLE ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_host_name FOREIGN KEY (host_name) REFERENCES hosts (host_name);
-ALTER TABLE user_roles ADD CONSTRAINT FK_user_roles_user_id FOREIGN KEY (user_id) REFERENCES users (user_id);
-ALTER TABLE user_roles ADD CONSTRAINT FK_user_roles_role_name FOREIGN KEY (role_name) REFERENCES roles (role_name);
 ALTER TABLE hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_cluster_id FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
 ALTER TABLE hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_host_name FOREIGN KEY (host_name) REFERENCES hosts (host_name);
 ALTER TABLE serviceconfigmapping ADD CONSTRAINT FK_scvm_scv FOREIGN KEY (service_config_id) REFERENCES serviceconfig(service_config_id);
@@ -281,11 +277,6 @@ insert into adminresourcetype (resource_type_id, resource_type_name)
 insert into adminresource (resource_id, resource_type_id)
   select 1, 1 from dual;
 
-insert into Roles(role_name)
-select 'admin' from dual
-union all
-select 'user' from dual;
-
 insert into adminprincipaltype (principal_type_id, principal_type_name)
   select 1, 'USER' from dual
   union all
@@ -297,9 +288,6 @@ insert into adminprincipal (principal_id, principal_type_id)
 insert into users(user_id, principal_id, user_name, user_password)
 select 1,1,'admin','538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00' from dual;
 
-insert into user_roles(role_name, user_id)
-select 'admin',1 from dual;
-
 insert into adminpermission(permission_id, permission_name, resource_type_id)
   select 1, 'AMBARI.ADMIN', 1 from dual
   union all

+ 2 - 16
ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql

@@ -25,7 +25,7 @@ CREATE TABLE clusterconfigmapping (cluster_id BIGINT NOT NULL, type_name VARCHAR
 
 CREATE TABLE serviceconfig (service_config_id BIGINT NOT NULL, cluster_id BIGINT NOT NULL, service_name VARCHAR(255) NOT NULL, version BIGINT NOT NULL, create_timestamp BIGINT NOT NULL, user_name VARCHAR(255) NOT NULL DEFAULT '_db', group_id BIGINT, note TEXT, PRIMARY KEY (service_config_id));
 
-CREATE TABLE serviceconfighosts (service_config_id BIGINT NOT NULL, hostname VARCHAR(255), PRIMARY KEY(service_config_id, hostname));
+CREATE TABLE serviceconfighosts (service_config_id BIGINT NOT NULL, hostname VARCHAR(255) NOT NULL, PRIMARY KEY(service_config_id, hostname));
 
 CREATE TABLE serviceconfigmapping (service_config_id BIGINT NOT NULL, config_id BIGINT NOT NULL, PRIMARY KEY(service_config_id, config_id));
 
@@ -45,8 +45,6 @@ CREATE TABLE servicecomponentdesiredstate (component_name VARCHAR(255) NOT NULL,
 
 CREATE TABLE servicedesiredstate (cluster_id BIGINT NOT NULL, desired_host_role_mapping INTEGER NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, desired_state VARCHAR(255) NOT NULL, service_name VARCHAR(255) NOT NULL, maintenance_state VARCHAR(32) NOT NULL, PRIMARY KEY (cluster_id, service_name));
 
-CREATE TABLE roles (role_name VARCHAR(255) NOT NULL, PRIMARY KEY (role_name));
-
 CREATE TABLE users (user_id INTEGER, principal_id BIGINT NOT NULL, ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, create_time TIMESTAMP DEFAULT NOW(), user_password VARCHAR(255), PRIMARY KEY (user_id), active INTEGER NOT NULL DEFAULT 1, UNIQUE (ldap_user, user_name));
 
 CREATE TABLE groups (group_id INTEGER, principal_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, ldap_group INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (group_id), UNIQUE (ldap_group, group_name));
@@ -69,8 +67,6 @@ CREATE TABLE requestoperationlevel (operation_level_id BIGINT NOT NULL, request_
 
 CREATE TABLE ClusterHostMapping (cluster_id BIGINT NOT NULL, host_name VARCHAR(255) NOT NULL, PRIMARY KEY (cluster_id, host_name));
 
-CREATE TABLE user_roles (role_name VARCHAR(255) NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (role_name, user_id));
-
 CREATE TABLE key_value_store ("key" VARCHAR(255), "value" VARCHAR, PRIMARY KEY ("key"));
 
 CREATE TABLE hostconfigmapping (cluster_id BIGINT NOT NULL, host_name VARCHAR(255) NOT NULL, type_name VARCHAR(255) NOT NULL, version_tag VARCHAR(255) NOT NULL, service_name VARCHAR(255), create_timestamp BIGINT NOT NULL, selected INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL DEFAULT '_db', PRIMARY KEY (cluster_id, host_name, type_name, create_timestamp));
@@ -79,7 +75,7 @@ CREATE TABLE metainfo ("metainfo_key" VARCHAR(255), "metainfo_value" VARCHAR, PR
 
 CREATE TABLE ambari_sequences (sequence_name VARCHAR(255) PRIMARY KEY, sequence_value BIGINT NOT NULL);
 
-CREATE TABLE configgroup (group_id BIGINT, cluster_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, tag VARCHAR(1024) NOT NULL, description VARCHAR(1024), create_timestamp BIGINT NOT NULL, PRIMARY KEY(group_id));
+CREATE TABLE configgroup (group_id BIGINT, cluster_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, tag VARCHAR(1024) NOT NULL, description VARCHAR(1024), create_timestamp BIGINT NOT NULL, service_name VARCHAR(255), PRIMARY KEY(group_id));
 
 CREATE TABLE confgroupclusterconfigmapping (config_group_id BIGINT NOT NULL, cluster_id BIGINT NOT NULL, config_type VARCHAR(255) NOT NULL, version_tag VARCHAR(255) NOT NULL, user_name VARCHAR(255) DEFAULT '_db', create_timestamp BIGINT NOT NULL, PRIMARY KEY(config_group_id, cluster_id, config_type));
 
@@ -139,8 +135,6 @@ ALTER TABLE role_success_criteria ADD CONSTRAINT role_success_criteria_stage_id
 ALTER TABLE stage ADD CONSTRAINT FK_stage_request_id FOREIGN KEY (request_id) REFERENCES request (request_id);
 ALTER TABLE request ADD CONSTRAINT FK_request_schedule_id FOREIGN KEY (request_schedule_id) REFERENCES requestschedule (schedule_id);
 ALTER TABLE ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_host_name FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
-ALTER TABLE user_roles ADD CONSTRAINT FK_user_roles_user_id FOREIGN KEY (user_id) REFERENCES users (user_id);
-ALTER TABLE user_roles ADD CONSTRAINT FK_user_roles_role_name FOREIGN KEY (role_name) REFERENCES roles (role_name);
 ALTER TABLE hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_cluster_id FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
 ALTER TABLE hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_host_name FOREIGN KEY (host_name) REFERENCES hosts (host_name);
 ALTER TABLE configgroup ADD CONSTRAINT FK_configgroup_cluster_id FOREIGN KEY (cluster_id) REFERENCES clusters (cluster_id);
@@ -339,11 +333,6 @@ BEGIN;
   INSERT INTO adminresource (resource_id, resource_type_id)
   SELECT 1, 1;
 
-  INSERT INTO Roles (role_name)
-  SELECT 'admin'
-  UNION ALL
-  SELECT 'user';
-
   INSERT INTO adminprincipaltype (principal_type_id, principal_type_name)
   SELECT 1, 'USER'
   UNION ALL
@@ -355,9 +344,6 @@ BEGIN;
   INSERT INTO Users (user_id, principal_id, user_name, user_password)
   SELECT 1, 1, 'admin', '538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
 
-  INSERT INTO user_roles (role_name, user_id)
-  SELECT 'admin', 1;
-
   INSERT INTO adminpermission(permission_id, permission_name, resource_type_id)
   SELECT 1, 'AMBARI.ADMIN', 1
   UNION ALL

+ 2 - 18
ambari-server/src/main/resources/Ambari-DDL-Postgres-EMBEDDED-CREATE.sql

@@ -40,7 +40,7 @@ GRANT ALL PRIVILEGES ON TABLE ambari.clusterconfigmapping TO :username;
 CREATE TABLE ambari.serviceconfig (service_config_id BIGINT NOT NULL, cluster_id BIGINT NOT NULL, service_name VARCHAR(255) NOT NULL, version BIGINT NOT NULL, create_timestamp BIGINT NOT NULL, user_name VARCHAR(255) NOT NULL DEFAULT '_db', group_id BIGINT, note TEXT, PRIMARY KEY (service_config_id));
 GRANT ALL PRIVILEGES ON TABLE ambari.serviceconfig TO :username;
 
-CREATE TABLE ambari.serviceconfighosts (service_config_id BIGINT NOT NULL, hostname VARCHAR(255), PRIMARY KEY(service_config_id, hostname));
+CREATE TABLE ambari.serviceconfighosts (service_config_id BIGINT NOT NULL, hostname VARCHAR(255) NOT NULL, PRIMARY KEY(service_config_id, hostname));
 GRANT ALL PRIVILEGES ON TABLE ambari.serviceconfighosts TO :username;
 
 CREATE TABLE ambari.serviceconfigmapping (service_config_id BIGINT NOT NULL, config_id BIGINT NOT NULL, PRIMARY KEY(service_config_id, config_id));
@@ -70,9 +70,6 @@ GRANT ALL PRIVILEGES ON TABLE ambari.servicecomponentdesiredstate TO :username;
 CREATE TABLE ambari.servicedesiredstate (cluster_id BIGINT NOT NULL, desired_host_role_mapping INTEGER NOT NULL, desired_stack_version VARCHAR(255) NOT NULL, desired_state VARCHAR(255) NOT NULL, service_name VARCHAR(255) NOT NULL, maintenance_state VARCHAR(32) NOT NULL, PRIMARY KEY (cluster_id, service_name));
 GRANT ALL PRIVILEGES ON TABLE ambari.servicedesiredstate TO :username;
 
-CREATE TABLE ambari.roles (role_name VARCHAR(255) NOT NULL, PRIMARY KEY (role_name));
-GRANT ALL PRIVILEGES ON TABLE ambari.roles TO :username;
-
 CREATE TABLE ambari.users (user_id INTEGER, principal_id BIGINT NOT NULL, ldap_user INTEGER NOT NULL DEFAULT 0, user_name VARCHAR(255) NOT NULL, create_time TIMESTAMP DEFAULT NOW(), user_password VARCHAR(255), active INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (user_id), UNIQUE (ldap_user, user_name));
 GRANT ALL PRIVILEGES ON TABLE ambari.users TO :username;
 
@@ -106,9 +103,6 @@ GRANT ALL PRIVILEGES ON TABLE ambari.requestoperationlevel TO :username;
 CREATE TABLE ambari.ClusterHostMapping (cluster_id BIGINT NOT NULL, host_name VARCHAR(255) NOT NULL, PRIMARY KEY (cluster_id, host_name));
 GRANT ALL PRIVILEGES ON TABLE ambari.ClusterHostMapping TO :username;
 
-CREATE TABLE ambari.user_roles (role_name VARCHAR(255) NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (role_name, user_id));
-GRANT ALL PRIVILEGES ON TABLE ambari.user_roles TO :username;
-
 CREATE TABLE ambari.key_value_store ("key" VARCHAR(255), "value" VARCHAR, PRIMARY KEY ("key"));
 GRANT ALL PRIVILEGES ON TABLE ambari.key_value_store TO :username;
 
@@ -121,7 +115,7 @@ GRANT ALL PRIVILEGES ON TABLE ambari.metainfo TO :username;
 CREATE TABLE ambari.ambari_sequences (sequence_name VARCHAR(255) PRIMARY KEY, sequence_value BIGINT NOT NULL);
 GRANT ALL PRIVILEGES ON TABLE ambari.ambari_sequences TO :username;
 
-CREATE TABLE ambari.configgroup (group_id BIGINT, cluster_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, tag VARCHAR(1024) NOT NULL, description VARCHAR(1024), create_timestamp BIGINT NOT NULL, PRIMARY KEY(group_id));
+CREATE TABLE ambari.configgroup (group_id BIGINT, cluster_id BIGINT NOT NULL, group_name VARCHAR(255) NOT NULL, tag VARCHAR(1024) NOT NULL, description VARCHAR(1024), create_timestamp BIGINT NOT NULL, service_name VARCHAR(255), PRIMARY KEY(group_id));
 GRANT ALL PRIVILEGES ON TABLE ambari.configgroup TO :username;
 
 CREATE TABLE ambari.confgroupclusterconfigmapping (config_group_id BIGINT NOT NULL, cluster_id BIGINT NOT NULL, config_type VARCHAR(255) NOT NULL, version_tag VARCHAR(255) NOT NULL, user_name VARCHAR(255) DEFAULT '_db', create_timestamp BIGINT NOT NULL, PRIMARY KEY(config_group_id, cluster_id, config_type));
@@ -205,8 +199,6 @@ ALTER TABLE ambari.stage ADD CONSTRAINT FK_stage_request_id FOREIGN KEY (request
 ALTER TABLE ambari.request ADD CONSTRAINT FK_request_schedule_id FOREIGN KEY (request_schedule_id) REFERENCES ambari.requestschedule (schedule_id);
 ALTER TABLE ambari.ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_cluster_id FOREIGN KEY (host_name) REFERENCES ambari.hosts (host_name);
 ALTER TABLE ambari.ClusterHostMapping ADD CONSTRAINT ClusterHostMapping_host_name FOREIGN KEY (cluster_id) REFERENCES ambari.clusters (cluster_id);
-ALTER TABLE ambari.user_roles ADD CONSTRAINT FK_user_roles_user_id FOREIGN KEY (user_id) REFERENCES ambari.users (user_id);
-ALTER TABLE ambari.user_roles ADD CONSTRAINT FK_user_roles_role_name FOREIGN KEY (role_name) REFERENCES ambari.roles (role_name);
 ALTER TABLE ambari.hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_cluster_id FOREIGN KEY (cluster_id) REFERENCES ambari.clusters (cluster_id);
 ALTER TABLE ambari.hostconfigmapping ADD CONSTRAINT FK_hostconfmapping_host_name FOREIGN KEY (host_name) REFERENCES ambari.hosts (host_name);
 ALTER TABLE ambari.configgroup ADD CONSTRAINT FK_configgroup_cluster_id FOREIGN KEY (cluster_id) REFERENCES ambari.clusters (cluster_id);
@@ -414,11 +406,6 @@ INSERT INTO ambari.adminresourcetype (resource_type_id, resource_type_name)
 INSERT INTO ambari.adminresource (resource_id, resource_type_id)
   SELECT 1, 1;
 
-INSERT INTO ambari.Roles (role_name)
-  SELECT 'admin'
-  UNION ALL
-  SELECT 'user';
-
 INSERT INTO ambari.adminprincipaltype (principal_type_id, principal_type_name)
   SELECT 1, 'USER'
   UNION ALL
@@ -430,9 +417,6 @@ INSERT INTO ambari.adminprincipal (principal_id, principal_type_id)
 INSERT INTO ambari.Users (user_id, principal_id, user_name, user_password)
   SELECT 1, 1, 'admin', '538916f8943ec225d97a9a86a2c6ec0818c1cd400e09e03b660fdaaec4af29ddbb6f2b1033b81b00';
 
-INSERT INTO ambari.user_roles (role_name, user_id)
-  SELECT 'admin', 1;
-
 INSERT INTO ambari.adminpermission(permission_id, permission_name, resource_type_id)
   SELECT 1, 'AMBARI.ADMIN', 1
   UNION ALL

+ 0 - 1
ambari-server/src/main/resources/META-INF/persistence.xml

@@ -24,7 +24,6 @@
     <class>org.apache.ambari.server.orm.entities.HostStateEntity</class>
     <class>org.apache.ambari.server.orm.entities.ServiceComponentDesiredStateEntity</class>
     <class>org.apache.ambari.server.orm.entities.ServiceDesiredStateEntity</class>
-    <class>org.apache.ambari.server.orm.entities.RoleEntity</class>
     <class>org.apache.ambari.server.orm.entities.UserEntity</class>
     <class>org.apache.ambari.server.orm.entities.GroupEntity</class>
     <class>org.apache.ambari.server.orm.entities.MemberEntity</class>

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HBASE/package/scripts/params.py

@@ -100,6 +100,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 1
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HDFS/package/scripts/hdfs_namenode.py

@@ -39,7 +39,7 @@ def namenode(action=None, do_format=True):
 
     namenode_safe_mode_off = format("su - {hdfs_user} -c 'hadoop dfsadmin -safemode get' | grep 'Safe mode is OFF'")
     if params.security_enabled:
-      Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_user}"),
+      Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"),
               user = params.hdfs_user)
     Execute(namenode_safe_mode_off,
             tries=40,

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HDFS/package/scripts/params.py

@@ -128,6 +128,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 19 - 8
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HIVE/package/scripts/hcat_service_check.py

@@ -48,14 +48,25 @@ def hcat_service_check():
             path=['/usr/sbin', '/usr/local/nin', '/bin', '/usr/bin'],
             logoutput=True)
 
-    ExecuteHadoop(test_cmd,
-                  user=params.hdfs_user,
-                  logoutput=True,
-                  conf_dir=params.hadoop_conf_dir,
-                  security_enabled=params.security_enabled,
-                  kinit_path_local=params.kinit_path_local,
-                  keytab=params.hdfs_user_keytab
-    )
+    if params.security_enabled:
+      ExecuteHadoop(test_cmd,
+                    user=params.hdfs_user,
+                    logoutput=True,
+                    conf_dir=params.hadoop_conf_dir,
+                    security_enabled=params.security_enabled,
+                    kinit_path_local=params.kinit_path_local,
+                    keytab=params.hdfs_user_keytab,
+                    principal=params.hdfs_principal_name
+      )
+    else:
+      ExecuteHadoop(test_cmd,
+                    user=params.hdfs_user,
+                    logoutput=True,
+                    conf_dir=params.hadoop_conf_dir,
+                    security_enabled=params.security_enabled,
+                    kinit_path_local=params.kinit_path_local,
+                    keytab=params.hdfs_user_keytab
+      )
 
     cleanup_cmd = format("{kinit_cmd}sh {tmp_dir}/hcatSmoke.sh hcatsmoke{unique} cleanup")
 

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/HIVE/package/scripts/params.py

@@ -155,6 +155,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 0 - 20
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/MAPREDUCE/configuration/core-site.xml

@@ -1,20 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
-<!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You 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.
--->
-<configuration supports_final="true">
-</configuration>

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/MAPREDUCE/package/scripts/params.py

@@ -63,6 +63,7 @@ hadoop_conf_dir = "/etc/hadoop/conf"
 hadoop_pid_dir_prefix = config['configurations']['hadoop-env']['hadoop_pid_dir_prefix']
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 import functools
 #create partial functions with common arguments for every HdfsDirectory call
 #to create hdfs directory we need to call params.HdfsDirectory in code

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/OOZIE/package/scripts/params.py

@@ -105,6 +105,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/1.3.2/services/WEBHCAT/package/scripts/params.py

@@ -64,6 +64,7 @@ security_param = "true" if security_enabled else "false"
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HBASE/package/scripts/params.py

@@ -107,6 +107,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 1
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HDFS/package/scripts/hdfs_namenode.py

@@ -52,7 +52,7 @@ def namenode(action=None, do_format=True):
     namenode_safe_mode_off = format("su - {hdfs_user} -c 'hadoop dfsadmin -safemode get' | grep 'Safe mode is OFF'")
 
     if params.security_enabled:
-      Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_user}"),
+      Execute(format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name}"),
               user = params.hdfs_user)
     Execute(namenode_safe_mode_off,
             tries=40,

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HDFS/package/scripts/params.py

@@ -94,6 +94,7 @@ hive_user = config['configurations']['hive-env']['hive_user']
 smoke_user =  config['configurations']['hadoop-env']['smokeuser']
 mapred_user = config['configurations']['mapred-env']['mapred_user']
 hdfs_user = status_params.hdfs_user
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 
 user_group = config['configurations']['hadoop-env']['user_group']
 proxyuser_group =  config['configurations']['hadoop-env']['proxyuser_group']

+ 19 - 8
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HIVE/package/scripts/hcat_service_check.py

@@ -47,14 +47,25 @@ def hcat_service_check():
             path=['/usr/sbin', '/usr/local/nin', '/bin', '/usr/bin'],
             logoutput=True)
 
-    ExecuteHadoop(test_cmd,
-                  user=params.hdfs_user,
-                  logoutput=True,
-                  conf_dir=params.hadoop_conf_dir,
-                  security_enabled=params.security_enabled,
-                  kinit_path_local=params.kinit_path_local,
-                  keytab=params.hdfs_user_keytab
-    )
+    if params.security_enabled:
+      ExecuteHadoop(test_cmd,
+                    user=params.hdfs_user,
+                    logoutput=True,
+                    conf_dir=params.hadoop_conf_dir,
+                    security_enabled=params.security_enabled,
+                    kinit_path_local=params.kinit_path_local,
+                    keytab=params.hdfs_user_keytab,
+                    principal=params.hdfs_principal_name
+      )
+    else:
+      ExecuteHadoop(test_cmd,
+                    user=params.hdfs_user,
+                    logoutput=True,
+                    conf_dir=params.hadoop_conf_dir,
+                    security_enabled=params.security_enabled,
+                    kinit_path_local=params.kinit_path_local,
+                    keytab=params.hdfs_user_keytab
+      )
 
     cleanup_cmd = format("{kinit_cmd} {tmp_dir}/hcatSmoke.sh hcatsmoke{unique} cleanup")
 

+ 1 - 1
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HIVE/package/scripts/install_jars.py

@@ -39,7 +39,7 @@ def install_tez_jars():
     params.HdfsDirectory(None, action="create")
 
     if params.security_enabled:
-      kinit_if_needed = format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_user};")
+      kinit_if_needed = format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name};")
     else:
       kinit_if_needed = ""
 

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/HIVE/package/scripts/params.py

@@ -168,6 +168,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 
 # Tez libraries

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/OOZIE/package/scripts/params.py

@@ -97,6 +97,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/PIG/package/scripts/params.py

@@ -28,6 +28,7 @@ tmp_dir = Script.get_tmp_dir()
 pig_conf_dir = "/etc/pig/conf"
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 smokeuser = config['configurations']['hadoop-env']['smokeuser']
 user_group = config['configurations']['hadoop-env']['user_group']
 _authentication = config['configurations']['core-site']['hadoop.security.authentication']

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/WEBHCAT/package/scripts/params.py

@@ -69,6 +69,7 @@ hadoop_conf_dir = "/etc/hadoop/conf"
 security_param = "true" if security_enabled else "false"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 1
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/WEBHCAT/package/scripts/webhcat.py

@@ -74,7 +74,7 @@ def webhcat():
   )
 
   if params.security_enabled:
-    kinit_if_needed = format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_user};")
+    kinit_if_needed = format("{kinit_path_local} -kt {hdfs_user_keytab} {hdfs_principal_name};")
   else:
     kinit_if_needed = ""
 

+ 0 - 20
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/YARN/configuration-mapred/core-site.xml

@@ -1,20 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
-<!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You 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.
--->
-<configuration supports_final="true">
-</configuration>

+ 0 - 20
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/YARN/configuration/core-site.xml

@@ -1,20 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
-<!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You 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.
--->
-<configuration supports_final="true">
-</configuration>

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.0.6/services/YARN/package/scripts/params.py

@@ -123,6 +123,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/FALCON/package/scripts/params.py

@@ -56,6 +56,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['global']['hdfs_user_keytab']
 hdfs_user = config['configurations']['global']['hdfs_user']
+hdfs_principal_name = config['configurations']['global']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path([default("kinit_path_local",None), "/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.1.GlusterFS/services/YARN/package/scripts/params.py

@@ -117,6 +117,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['global']['hdfs_user_keytab']
 hdfs_user = config['configurations']['global']['hdfs_user']
+hdfs_principal_name = config['configurations']['global']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path([default("kinit_path_local",None), "/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 1 - 0
ambari-server/src/main/resources/stacks/HDP/2.1/services/FALCON/package/scripts/params.py

@@ -57,6 +57,7 @@ hostname = config["hostname"]
 hadoop_conf_dir = "/etc/hadoop/conf"
 hdfs_user_keytab = config['configurations']['hadoop-env']['hdfs_user_keytab']
 hdfs_user = config['configurations']['hadoop-env']['hdfs_user']
+hdfs_principal_name = config['configurations']['hadoop-env']['hdfs_principal_name']
 kinit_path_local = functions.get_kinit_path(["/usr/bin", "/usr/kerberos/bin", "/usr/sbin"])
 import functools
 #create partial functions with common arguments for every HdfsDirectory call

+ 0 - 20
ambari-server/src/main/resources/stacks/HDP/2.1/services/YARN/configuration/core-site.xml

@@ -1,20 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
-<!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You 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.
--->
-<configuration supports_final="true">
-</configuration>

+ 97 - 138
ambari-server/src/test/java/org/apache/ambari/server/api/util/StackExtensionHelperTest.java

@@ -23,6 +23,7 @@ import org.apache.ambari.server.metadata.ActionMetadata;
 import org.apache.ambari.server.state.*;
 
 import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -36,12 +37,16 @@ import static org.junit.Assert.*;
 
 import org.apache.ambari.server.state.stack.ConfigurationXml;
 import org.junit.Test;
+import org.xml.sax.SAXException;
 
 import com.google.inject.AbstractModule;
 import com.google.inject.Guice;
 import com.google.inject.Injector;
 
+import javax.xml.bind.JAXBException;
 import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.xpath.XPathExpressionException;
 
 public class StackExtensionHelperTest {
 
@@ -244,7 +249,7 @@ public class StackExtensionHelperTest {
     for (ServiceInfo serviceInfo : allServices) {
       if (serviceInfo.getName().equals("HDFS")) {
         assertEquals(5, serviceInfo.getConfigDependencies().size());
-        assertEquals(5, serviceInfo.getConfigTypes().size());
+        assertEquals(4, serviceInfo.getConfigTypes().size());
         assertTrue(serviceInfo.getConfigDependencies().contains("core-site"));
         assertTrue(serviceInfo.getConfigDependencies().contains("global"));
         assertTrue(serviceInfo.getConfigDependencies().contains("hdfs-site"));
@@ -280,31 +285,6 @@ public class StackExtensionHelperTest {
       }
     }
   }
-  
-  @Test
-  public void testrequiredServicesPropertyInheritance() throws Exception{
-    File stackRoot = new File(stackRootStr);
-    StackInfo stackInfo = new StackInfo();
-    stackInfo.setName("HDP");
-    stackInfo.setVersion("2.0.7");
-    StackExtensionHelper helper = new StackExtensionHelper(injector, stackRoot);
-    helper.populateServicesForStack(stackInfo);
-    helper.fillInfo();
-    List<ServiceInfo> allServices = helper.getAllApplicableServices(stackInfo);
-    assertEquals(13, allServices.size());
-    
-    List<String> expectedRequiredServices = new ArrayList<String>();
-    expectedRequiredServices.add("HDFS");
-    expectedRequiredServices.add("TEZ");
-    
-    for (ServiceInfo serviceInfo : allServices) {
-      if (serviceInfo.getName().equals("HBASE")) {
-        assertTrue(serviceInfo.getRequiredServices().equals(expectedRequiredServices));
-      } else {
-        assertTrue((serviceInfo.getRequiredServices() == null || serviceInfo.getRequiredServices().isEmpty()));
-      }
-    }
-  }
 
   @Test
   public void getSchemaVersion() throws Exception {
@@ -320,60 +300,54 @@ public class StackExtensionHelperTest {
     version = helper.getSchemaVersion(v2MetaInfoFile);
     assertEquals("2.0", version);
   }
-
-  @Test
-  public void testPopulateConfigTypes() {
-    File stackRoot = new File(stackRootStr);
-    StackExtensionHelper helper = new StackExtensionHelper(injector, stackRoot);
-    List<String> configDependencies = Arrays.asList("dep1", "dep2");
-    ServiceInfo serviceInfo = new ServiceInfo();
-    serviceInfo.setConfigDependencies(configDependencies);
-    helper.populateConfigTypesFromDependencies(serviceInfo);
-
-    Map<String, Map<String, Map<String, String>>> configTypes = serviceInfo.getConfigTypes();
-    assertEquals(2, configTypes.size());
-    assertTrue(configTypes.containsKey("dep1"));
-    assertTrue(configTypes.containsKey("dep2"));
-    Map<String, Map<String, String>> properties;
-    properties= configTypes.get("dep1");
-    assertEquals(1, properties.size());
-    assertTrue(properties.containsKey("supports"));
-    assertEquals(1, properties.get("supports").size());
-    assertTrue(properties.get("supports").containsKey("final"));
-    assertEquals("false", properties.get("supports").get("final"));
-    properties= configTypes.get("dep2");
-    assertEquals(1, properties.size());
-    assertTrue(properties.containsKey("supports"));
-    assertEquals(1, properties.get("supports").size());
-    assertTrue(properties.get("supports").containsKey("final"));
-    assertEquals("false", properties.get("supports").get("final"));
+  
+  public StackExtensionHelper getStackExtensionHelper() {
+    File stackRoot = new File(stackRootStr);    
+    return new StackExtensionHelper(injector, stackRoot);
   }
-
-  @Test
-  public void testPopulateConfigTypes_emptyList() {
-    File stackRoot = new File(stackRootStr);
-    StackExtensionHelper helper = new StackExtensionHelper(injector, stackRoot);
-    List<String> configDependencies = Collections.emptyList();
-    ServiceInfo serviceInfo = new ServiceInfo();
-    serviceInfo.setConfigDependencies(configDependencies);
-    helper.populateConfigTypesFromDependencies(serviceInfo);
-
-    Map<String, Map<String, Map<String, String>>> configTypes = serviceInfo.getConfigTypes();
-    assertNotNull(configTypes);
-    assertEquals(0, configTypes.size());
+  
+  public ServiceInfo getServiceFromStack(StackExtensionHelper helper, String stackName, String stackVersion, String serviceName) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, JAXBException {
+    StackInfo stackInfo = new StackInfo();
+    stackInfo.setName(stackName);
+    stackInfo.setVersion(stackVersion);
+    
+    helper.populateServicesForStack(stackInfo);
+    
+    for(ServiceInfo service:stackInfo.getServices()) {
+      if(service.getName().equals(serviceName)) {
+        return service;
+      }
+    }
+    return null;
   }
 
+  private void addToPropertyMap(Map<String, Map<String, Map<String, String>>> configTypes,String configType,
+      String keyword, String attributeName, String value) {
+    configTypes.put(configType, new HashMap<String, Map<String, String>>()); 
+    Map<String, Map<String, String>> config = configTypes.get(configType); 
+    config.put(keyword, new HashMap<String, String>());
+    Map<String, String> supports = config.get(keyword);
+    supports.put(attributeName, value);    
+  }
   @Test
-  public void testPopulateConfigTypes_null() {
-    File stackRoot = new File(stackRootStr);
-    StackExtensionHelper helper = new StackExtensionHelper(injector, stackRoot);
-    List<String> configDependencies = null;
-    ServiceInfo serviceInfo = new ServiceInfo();
-    serviceInfo.setConfigDependencies(configDependencies);
-    helper.populateConfigTypesFromDependencies(serviceInfo);
-
+  public void testPopulateConfigTypes() throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, JAXBException {
+    StackExtensionHelper helper = getStackExtensionHelper();
+    ServiceInfo serviceInfo = getServiceFromStack(helper, "HDP", "2.0.7", "HDFS");
+    
+    
+    Map<String, Map<String, Map<String, String>>> expectedConfigTypes = new HashMap<String, Map<String, Map<String, String>>>();
+    addToPropertyMap(expectedConfigTypes, "global", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "true");
+    addToPropertyMap(expectedConfigTypes, "hdfs-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    addToPropertyMap(expectedConfigTypes, "hadoop-policy", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    addToPropertyMap(expectedConfigTypes, "core-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    
     Map<String, Map<String, Map<String, String>>> configTypes = serviceInfo.getConfigTypes();
-    assertNull(configTypes);
+    assertEquals(4, configTypes.size());
+    assertEquals(expectedConfigTypes, configTypes);
   }
 
   @Test
@@ -472,81 +446,64 @@ public class StackExtensionHelperTest {
 
   @Test
   public void testPopulateServiceProperties_noSupportsFinalFlag() throws Exception {
-    // init
-    File stackRoot = new File(stackRootStr);
-    StackExtensionHelper helper = createMockBuilder(StackExtensionHelper.class).addMockedMethod("addConfigTypeProperty")
-        .withConstructor(injector, stackRoot).createMock();
-    File config = new File(stackRootStr
+    StackExtensionHelper helper = getStackExtensionHelper();
+    ServiceInfo serviceInfo = getServiceFromStack(helper, "HDP", "2.0.7", "YARN");
+    
+    File configFile = new File(stackRootStr
         + "HDP/2.0.7/services/YARN/configuration/yarn-site.xml".replaceAll("/", File.separator));
-    ServiceInfo serviceInfo = createNiceMock(ServiceInfo.class);
-    List<PropertyInfo> properties = createNiceMock(List.class);
-
-    // expectations
-    expect(serviceInfo.getProperties()).andReturn(properties).times(1);
-    expect(properties.addAll((Collection) anyObject())).andReturn(true).times(1);
-    replay(properties);
-    replay(serviceInfo);
-    replay(helper);
-
-    // eval
-    helper.populateServiceProperties(config, serviceInfo);
-
-    // verification
-    verify(properties, serviceInfo, helper);
+    
+    helper.populateServiceProperties(configFile, serviceInfo);
+    
+    Map<String, Map<String, Map<String, String>>> expectedConfigTypes = new HashMap<String, Map<String, Map<String, String>>>();
+    addToPropertyMap(expectedConfigTypes, "yarn-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    
+    assertEquals(expectedConfigTypes, serviceInfo.getConfigTypes());
   }
 
   @Test
   public void testPopulateServiceProperties_supportsFinalTrue() throws Exception {
-    // init
-    File stackRoot = new File(stackRootStr);
-    StackExtensionHelper helper = createMockBuilder(StackExtensionHelper.class).addMockedMethod("addConfigTypeProperty")
-        .withConstructor(injector, stackRoot).createMock();
-    File config = new File(stackRootStr
+    StackExtensionHelper helper = getStackExtensionHelper();
+    ServiceInfo serviceInfo = getServiceFromStack(helper, "HDP", "2.0.7", "HDFS");
+    
+    File configFile = new File(stackRootStr
         + "HDP/2.0.7/services/HDFS/configuration/global.xml".replaceAll("/", File.separator));
-    ServiceInfo serviceInfo = createNiceMock(ServiceInfo.class);
-    List<PropertyInfo> properties = createNiceMock(List.class);
-
-    // expectations
-    expect(serviceInfo.getProperties()).andReturn(properties).times(1);
-    expect(properties.addAll((Collection) anyObject())).andReturn(true).times(1);
-    helper.addConfigTypeProperty(serviceInfo, "global", StackExtensionHelper.Supports.KEYWORD,
+    helper.populateServiceProperties(configFile, serviceInfo);
+    
+    Map<String, Map<String, Map<String, String>>> expectedConfigTypes = new HashMap<String, Map<String, Map<String, String>>>();
+    addToPropertyMap(expectedConfigTypes, "global", StackExtensionHelper.Supports.KEYWORD, 
         StackExtensionHelper.Supports.FINAL.getPropertyName(), "true");
-    replay(properties);
-    replay(serviceInfo);
-    replay(helper);
-
-    // eval
-    helper.populateServiceProperties(config, serviceInfo);
-
-    // verification
-    verify(properties, serviceInfo, helper);
+    addToPropertyMap(expectedConfigTypes, "hdfs-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    addToPropertyMap(expectedConfigTypes, "hadoop-policy", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    addToPropertyMap(expectedConfigTypes, "core-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    
+    assertEquals(expectedConfigTypes, serviceInfo.getConfigTypes());
   }
 
   @Test
   public void testPopulateServiceProperties_supportsFinalFalse() throws Exception {
-    // init
-    File stackRoot = new File(stackRootStr);
-    StackExtensionHelper helper = createMockBuilder(StackExtensionHelper.class).addMockedMethod("addConfigTypeProperty")
-        .withConstructor(injector, stackRoot).createMock();
-    File config = new File(stackRootStr
-        + "HDP/2.0.7/services/HDFS/configuration/core-site.xml".replaceAll("/", File.separator));
-    ServiceInfo serviceInfo = createNiceMock(ServiceInfo.class);
-    List<PropertyInfo> properties = createNiceMock(List.class);
-
-    // expectations
-    expect(serviceInfo.getProperties()).andReturn(properties).times(1);
-    expect(properties.addAll((Collection) anyObject())).andReturn(true).times(1);
-    helper.addConfigTypeProperty(serviceInfo, "core-site", StackExtensionHelper.Supports.KEYWORD,
+    StackExtensionHelper helper = getStackExtensionHelper();
+    ServiceInfo serviceInfo = getServiceFromStack(helper, "HDP", "2.0.7", "HDFS");
+    File configFile = new File(stackRootStr
+        + "HDP/2.0.7/services/YARN/configuration/yarn-site.xml".replaceAll("/", File.separator));
+    helper.populateServiceProperties(configFile, serviceInfo);
+    
+    Map<String, Map<String, Map<String, String>>> expectedConfigTypes = new HashMap<String, Map<String, Map<String, String>>>();
+    addToPropertyMap(expectedConfigTypes, "global", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "true");
+    addToPropertyMap(expectedConfigTypes, "hdfs-site", StackExtensionHelper.Supports.KEYWORD, 
         StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
-    replay(properties);
-    replay(serviceInfo);
-    replay(helper);
-
-    // eval
-    helper.populateServiceProperties(config, serviceInfo);
-
-    // verification
-    verify(properties, serviceInfo, helper);
+    addToPropertyMap(expectedConfigTypes, "yarn-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    addToPropertyMap(expectedConfigTypes, "hadoop-policy", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    addToPropertyMap(expectedConfigTypes, "core-site", StackExtensionHelper.Supports.KEYWORD, 
+        StackExtensionHelper.Supports.FINAL.getPropertyName(), "false");
+    
+    assertEquals(expectedConfigTypes, serviceInfo.getConfigTypes());
   }
 
   @Test
@@ -561,6 +518,7 @@ public class StackExtensionHelperTest {
     List<PropertyInfo> properties = createNiceMock(List.class);
 
     // expectations
+    expect(serviceInfo.getConfigTypes()).andReturn(new HashMap<String, Map<String, Map<String, String>>>()).times(2);
     expect(serviceInfo.getProperties()).andReturn(properties).times(1);
     expect(properties.addAll((Collection) anyObject())).andReturn(true).times(1);
     helper.addConfigTypeProperty(serviceInfo, "yarn-site", StackExtensionHelper.Supports.KEYWORD,
@@ -587,6 +545,7 @@ public class StackExtensionHelperTest {
     List<PropertyInfo> properties = createNiceMock(List.class);
 
     // expectations
+    expect(serviceInfo.getConfigTypes()).andReturn(new HashMap<String, Map<String, Map<String, String>>>()).times(2);
     expect(serviceInfo.getProperties()).andReturn(properties).times(1);
     expect(properties.addAll((Collection) anyObject())).andReturn(true).times(1);
     expect(serviceInfo.getConfigTypes()).andReturn(null).times(1);

+ 107 - 0
ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariHandlerListTest.java

@@ -0,0 +1,107 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 org.apache.ambari.server.controller;
+
+import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
+import org.apache.ambari.server.orm.entities.ViewInstanceEntityTest;
+import org.eclipse.jetty.server.Handler;
+import org.eclipse.jetty.server.Server;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+
+/**
+ * AmbariHandlerList tests.
+ */
+public class AmbariHandlerListTest {
+  @Test
+  public void testAddViewInstance() throws Exception {
+
+    ViewInstanceEntity viewInstanceEntity = ViewInstanceEntityTest.getViewInstanceEntity();
+
+    final Handler handler = createNiceMock(Handler.class);
+    Server server = createNiceMock(Server.class);
+
+    expect(handler.getServer()).andReturn(server);
+    handler.setServer(null);
+
+    replay(handler, server);
+
+    AmbariHandlerList.HandlerFactory handlerFactory = new AmbariHandlerList.HandlerFactory() {
+      @Override
+      public Handler create(ViewInstanceEntity viewInstanceDefinition, String webApp, String contextPath) {
+        return handler;
+      }
+    };
+
+    AmbariHandlerList handlerList = new AmbariHandlerList(handlerFactory);
+
+    handlerList.addViewInstance(viewInstanceEntity);
+
+    ArrayList<Handler> handlers = new ArrayList<Handler>(Arrays.asList(handlerList.getHandlers()));
+
+    Assert.assertTrue(handlers.contains(handler));
+
+    verify(handler, server);
+  }
+
+  @Test
+  public void testRemoveViewInstance() throws Exception {
+    ViewInstanceEntity viewInstanceEntity = ViewInstanceEntityTest.getViewInstanceEntity();
+
+    final Handler handler = createNiceMock(Handler.class);
+    Server server = createNiceMock(Server.class);
+
+    expect(handler.getServer()).andReturn(server);
+    handler.setServer(null);
+
+    replay(handler, server);
+
+    AmbariHandlerList.HandlerFactory handlerFactory = new AmbariHandlerList.HandlerFactory() {
+      @Override
+      public Handler create(ViewInstanceEntity viewInstanceDefinition, String webApp, String contextPath) {
+        return handler;
+      }
+    };
+
+    AmbariHandlerList handlerList = new AmbariHandlerList(handlerFactory);
+
+    handlerList.addViewInstance(viewInstanceEntity);
+
+    ArrayList<Handler> handlers = new ArrayList<Handler>(Arrays.asList(handlerList.getHandlers()));
+
+    Assert.assertTrue(handlers.contains(handler));
+
+    handlerList.removeViewInstance(viewInstanceEntity);
+
+    handlers = new ArrayList<Handler>(Arrays.asList(handlerList.getHandlers()));
+
+    Assert.assertFalse(handlers.contains(handler));
+
+    verify(handler, server);
+
+  }
+}

+ 0 - 11
ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java

@@ -89,9 +89,7 @@ import org.apache.ambari.server.orm.GuiceJpaInitializer;
 import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
 import org.apache.ambari.server.orm.dao.ExecutionCommandDAO;
 import org.apache.ambari.server.orm.dao.HostDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.entities.ExecutionCommandEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.security.authorization.Users;
 import org.apache.ambari.server.serveraction.ServerAction;
 import org.apache.ambari.server.serveraction.ServerActionManager;
@@ -4596,7 +4594,6 @@ public class AmbariManagementControllerTest {
   @Test
   public void testUpdateUsers() throws Exception {
     createUser("user1");
-    users.createDefaultRoles();
 
     UserRequest request = new UserRequest("user1");
 
@@ -4609,8 +4606,6 @@ public class AmbariManagementControllerTest {
   public void testDeleteUsers() throws Exception {
     createUser("user1");
 
-    users.createDefaultRoles();
-
     UserRequest request = new UserRequest("user1");
     controller.updateUsers(Collections.singleton(request));
 
@@ -4621,12 +4616,6 @@ public class AmbariManagementControllerTest {
         Collections.singleton(new UserRequest(null)));
 
     Assert.assertEquals(0, responses.size());
-
-    RoleDAO roleDao = injector.getInstance(RoleDAO.class);
-    RoleEntity re1 = roleDao.findByName("user");
-    RoleEntity re2 = roleDao.findByName("admin");
-    Assert.assertNotNull(re1);
-    Assert.assertNotNull(re2);
   }
 
   @Test

+ 6 - 20
ambari-server/src/test/java/org/apache/ambari/server/orm/OrmTestHelper.java

@@ -39,7 +39,6 @@ import org.apache.ambari.server.orm.dao.HostDAO;
 import org.apache.ambari.server.orm.dao.HostRoleCommandDAO;
 import org.apache.ambari.server.orm.dao.RequestDAO;
 import org.apache.ambari.server.orm.dao.ResourceTypeDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.StageDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.AlertDefinitionEntity;
@@ -55,7 +54,6 @@ import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.RequestEntity;
 import org.apache.ambari.server.orm.entities.ResourceEntity;
 import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.StageEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.apache.ambari.server.state.HostState;
@@ -81,9 +79,6 @@ public class OrmTestHelper {
   @Inject
   public UserDAO userDAO;
 
-  @Inject
-  public RoleDAO roleDAO;
-
   @Inject
   public AlertDefinitionDAO alertDefinitionDAO;
 
@@ -175,25 +170,16 @@ public class OrmTestHelper {
 
     PasswordEncoder encoder = injector.getInstance(PasswordEncoder.class);
 
-    RoleEntity adminRole = new RoleEntity();
-    adminRole.setRoleName("admin");
-
     UserEntity admin = new UserEntity();
     admin.setUserName("administrator");
     admin.setUserPassword(encoder.encode("admin"));
     admin.setPrincipal(principalEntity);
 
-    Set<RoleEntity> roles = new HashSet<RoleEntity>();
     Set<UserEntity> users = new HashSet<UserEntity>();
 
-    roles.add(adminRole);
     users.add(admin);
 
-    admin.setRoleEntities(roles);
-    adminRole.setUserEntities(users);
-
     userDAO.create(admin);
-    roleDAO.create(adminRole);
 
     principalEntity = new PrincipalEntity();
     principalEntity.setPrincipalType(principalTypeEntity);
@@ -274,7 +260,7 @@ public class OrmTestHelper {
 
   /**
    * Creates an empty cluster with an ID.
-   * 
+   *
    * @return the cluster ID.
    */
   @Transactional
@@ -306,7 +292,7 @@ public class OrmTestHelper {
 
   /**
    * Creates an alert target.
-   * 
+   *
    * @return
    */
   @Transactional
@@ -320,10 +306,10 @@ public class OrmTestHelper {
     alertDispatchDAO.create(target);
     return alertDispatchDAO.findTargetById(target.getTargetId());
   }
-  
+
   /**
    * Creates an alert definition.
-   * 
+   *
    * @param clusterId
    * @return
    * @throws Exception
@@ -342,14 +328,14 @@ public class OrmTestHelper {
     definition.setScope(Scope.SERVICE);
     definition.setSource("Source " + System.currentTimeMillis());
     definition.setSourceType("SCRIPT");
-    
+
     alertDefinitionDAO.create(definition);
     return alertDefinitionDAO.findById(definition.getDefinitionId());
   }
 
   /**
    * Creates an alert group.
-   * 
+   *
    * @param clusterId
    * @param targets
    * @return

+ 1 - 39
ambari-server/src/test/java/org/apache/ambari/server/orm/dao/UserDAOTest.java

@@ -21,25 +21,14 @@ package org.apache.ambari.server.orm.dao;
 import com.google.inject.Inject;
 import com.google.inject.Provider;
 import org.junit.Before;
-import org.junit.Test;
 import static org.easymock.EasyMock.createStrictMock;
-import static org.easymock.EasyMock.eq;
 import static org.easymock.EasyMock.expect;
 import static org.easymock.EasyMock.replay;
 import static org.easymock.EasyMock.reset;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-
 import javax.persistence.EntityManager;
-import javax.persistence.TypedQuery;
-import java.util.Collections;
-import java.util.List;
-import org.apache.ambari.server.orm.entities.RoleEntity;
-import org.apache.ambari.server.orm.entities.UserEntity;
 
 /**
- * BlueprintDAO unit tests.
+ * UserDAO unit tests.
  */
 public class UserDAOTest {
 
@@ -56,31 +45,4 @@ public class UserDAOTest {
     replay(entityManagerProvider);
   }
 
-
-  @Test
-  public void testfindAllLocalUsersByRole() {
-    UserEntity entity = new UserEntity();
-    RoleEntity roleEntity = new RoleEntity();
-    TypedQuery<UserEntity> query = createStrictMock(TypedQuery.class);
-
-    // set expectations
-    expect(entityManager.createQuery(eq("SELECT role.userEntities FROM RoleEntity role WHERE role = :roleEntity"), eq(UserEntity.class))).andReturn(query);
-    roleEntity.setRoleName("admin");
-    expect(query.setParameter("roleEntity", roleEntity)).andReturn(query);
-    expect(query.getResultList()).andReturn(Collections.singletonList(entity));
-    
-    replay(entityManager, query);
-
-    UserDAO dao = new UserDAO();
-    dao.entityManagerProvider = entityManagerProvider;
-    roleEntity.setRoleName("admin");
-    
-    List<UserEntity> results = dao.findAllLocalUsersByRole(roleEntity);
-
-    assertEquals(1, results.size());
-    assertSame(entity, results.get(0));
-
-    verify(entityManagerProvider, entityManager, query);
-  }
-
 }

+ 0 - 38
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java

@@ -23,9 +23,7 @@ import com.google.inject.Injector;
 import com.google.inject.persist.PersistService;
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.GuiceJpaInitializer;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.apache.ambari.server.security.ClientSecurityType;
 import org.junit.*;
@@ -45,8 +43,6 @@ public class AmbariLdapAuthenticationProviderForDNWithSpaceTest {
   @Inject
   private UserDAO userDAO;
   @Inject
-  private RoleDAO roleDAO;
-  @Inject
   Configuration configuration;
 
   @BeforeClass
@@ -81,7 +77,6 @@ public class AmbariLdapAuthenticationProviderForDNWithSpaceTest {
     Authentication authentication = new UsernamePasswordAuthenticationToken("the allowedUser", "password");
     Authentication result = authenticationProvider.authenticate(authentication);
     assertTrue(result.isAuthenticated());
-    assertNotNull("User was not created", userDAO.findLdapUserByName("the allowedUser"));
     result = authenticationProvider.authenticate(authentication);
     assertTrue(result.isAuthenticated());
   }
@@ -94,39 +89,6 @@ public class AmbariLdapAuthenticationProviderForDNWithSpaceTest {
     assertTrue(auth == null);
   }
 
-  @Test
-  public void testLdapAdminGroupToRolesMapping() throws Exception {
-
-    Authentication authentication;
-
-    authentication =
-        new UsernamePasswordAuthenticationToken("allowedAdmin", "password");
-    Authentication result = authenticationProvider.authenticate(authentication);
-    assertTrue(result.isAuthenticated());
-
-    UserEntity allowedAdminEntity = userDAO.findLdapUserByName("allowedAdmin");
-
-    authentication =
-        new UsernamePasswordAuthenticationToken("the allowedUser", "password");
-    authenticationProvider.authenticate(authentication);
-    UserEntity allowedUserEntity = userDAO.findLdapUserByName("the allowedUser");
-
-
-    RoleEntity adminRole = roleDAO.findByName(
-        configuration.getConfigsMap().get(Configuration.ADMIN_ROLE_NAME_KEY));
-    RoleEntity userRole = roleDAO.findByName(
-        configuration.getConfigsMap().get(Configuration.USER_ROLE_NAME_KEY));
-
-
-    assertTrue(allowedAdminEntity.getRoleEntities().contains(userRole));
-    assertTrue(allowedAdminEntity.getRoleEntities().contains(adminRole));
-
-    assertTrue(allowedUserEntity.getRoleEntities().contains(userRole));
-    assertFalse(allowedUserEntity.getRoleEntities().contains(adminRole));
-
-
-  }
-
   @AfterClass
   public static void afterClass() {
     apacheDSContainer.stop();

+ 0 - 39
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java

@@ -25,10 +25,7 @@ import com.google.inject.Inject;
 import com.google.inject.Injector;
 import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.GuiceJpaInitializer;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
-import org.apache.ambari.server.orm.entities.RoleEntity;
-import org.apache.ambari.server.orm.entities.UserEntity;
 import org.apache.ambari.server.security.ClientSecurityType;
 import org.easymock.EasyMockSupport;
 import org.easymock.IAnswer;
@@ -56,8 +53,6 @@ public class AmbariLdapAuthenticationProviderTest extends EasyMockSupport {
   @Inject
   private UserDAO userDAO;
   @Inject
-  private RoleDAO roleDAO;
-  @Inject
   Configuration configuration;
 
   @BeforeClass
@@ -161,7 +156,6 @@ public class AmbariLdapAuthenticationProviderTest extends EasyMockSupport {
     Authentication authentication = new UsernamePasswordAuthenticationToken("allowedUser", "password");
     Authentication result = authenticationProvider.authenticate(authentication);
     assertTrue(result.isAuthenticated());
-    assertNotNull("User was not created", userDAO.findLdapUserByName("allowedUser"));
     result = authenticationProvider.authenticate(authentication);
     assertTrue(result.isAuthenticated());
   }
@@ -174,39 +168,6 @@ public class AmbariLdapAuthenticationProviderTest extends EasyMockSupport {
     Assert.assertTrue(auth == null);
   }
 
-  @Test
-  public void testLdapAdminGroupToRolesMapping() throws Exception {
-
-    Authentication authentication;
-
-    authentication =
-        new UsernamePasswordAuthenticationToken("allowedAdmin", "password");
-    Authentication result = authenticationProvider.authenticate(authentication);
-    assertTrue(result.isAuthenticated());
-
-    UserEntity allowedAdminEntity = userDAO.findLdapUserByName("allowedAdmin");
-
-    authentication =
-        new UsernamePasswordAuthenticationToken("allowedUser", "password");
-    authenticationProvider.authenticate(authentication);
-    UserEntity allowedUserEntity = userDAO.findLdapUserByName("allowedUser");
-
-
-    RoleEntity adminRole = roleDAO.findByName(
-        configuration.getConfigsMap().get(Configuration.ADMIN_ROLE_NAME_KEY));
-    RoleEntity userRole = roleDAO.findByName(
-        configuration.getConfigsMap().get(Configuration.USER_ROLE_NAME_KEY));
-
-
-    assertTrue(allowedAdminEntity.getRoleEntities().contains(userRole));
-    assertTrue(allowedAdminEntity.getRoleEntities().contains(adminRole));
-
-    assertTrue(allowedUserEntity.getRoleEntities().contains(userRole));
-    assertFalse(allowedUserEntity.getRoleEntities().contains(adminRole));
-
-
-  }
-
   @AfterClass
   public static void afterClass() {
     apacheDSContainer.stop();

+ 0 - 2
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapDataPopulatorTest.java

@@ -34,7 +34,6 @@ import org.apache.ambari.server.orm.entities.GroupEntity;
 import org.apache.ambari.server.orm.entities.MemberEntity;
 import org.apache.ambari.server.orm.entities.PrincipalEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.easymock.Capture;
 import org.easymock.EasyMock;
@@ -229,7 +228,6 @@ public class AmbariLdapDataPopulatorTest {
     userEntity.setLdapUser(ldapUser);
     userEntity.setActive(true);
     userEntity.setMemberEntities(new HashSet<MemberEntity>());
-    userEntity.setRoleEntities(new HashSet<RoleEntity>());
     final PrincipalEntity principalEntity = new PrincipalEntity();
     principalEntity.setPrivileges(new HashSet<PrivilegeEntity>());
     userEntity.setPrincipal(principalEntity);

+ 0 - 7
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserDetailsServiceTest.java

@@ -23,7 +23,6 @@ import com.google.inject.Injector;
 import org.apache.ambari.server.orm.GuiceJpaInitializer;
 import org.apache.ambari.server.orm.OrmTestHelper;
 import org.apache.ambari.server.orm.dao.UserDAO;
-import org.apache.ambari.server.orm.entities.UserEntity;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -70,10 +69,4 @@ public class AmbariLocalUserDetailsServiceTest {
   public void testUsernameNotFound() throws Exception {
     userDetailsService.loadUserByUsername("notExists_123123123");
   }
-
-  @Test(expected = UsernameNotFoundException.class)
-  public void testEmptyRoles() throws Exception {
-    UserEntity user = userDAO.findLocalUserByName("userWithoutRoles");
-    userDetailsService.loadUserByUsername(user.getUserName());
-  }
 }

+ 7 - 205
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestAmbariLdapAuthoritiesPopulator.java

@@ -17,49 +17,31 @@
  */
 package org.apache.ambari.server.security.authorization;
 
-import org.apache.ambari.server.configuration.Configuration;
 import org.apache.ambari.server.orm.dao.MemberDAO;
-import org.apache.ambari.server.orm.dao.PrincipalDAO;
-import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
 import org.apache.ambari.server.orm.dao.PrivilegeDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.GroupEntity;
 import org.apache.ambari.server.orm.entities.MemberEntity;
 import org.apache.ambari.server.orm.entities.PrincipalEntity;
-import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
 import org.apache.ambari.server.orm.entities.PrivilegeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
-import org.easymock.Capture;
+import org.easymock.EasyMock;
 import org.easymock.EasyMockSupport;
 import org.junit.Before;
 import org.junit.Test;
 import org.springframework.ldap.core.DirContextOperations;
 
 import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
 import java.util.LinkedList;
 import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
 import static org.easymock.EasyMock.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 
 public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
 
   AuthorizationHelper helper = new AuthorizationHelper();
-  Configuration configuration = createMock(Configuration.class);
   UserDAO userDAO = createMock(UserDAO.class);
-  RoleDAO roleDAO = createMock(RoleDAO.class);
-  PrincipalDAO principalDAO = createMock(PrincipalDAO.class);
-  PrincipalTypeDAO principalTypeDAO = createMock(PrincipalTypeDAO.class);
   MemberDAO memberDAO = createMock(MemberDAO.class);
   PrivilegeDAO privilegeDAO = createMock(PrivilegeDAO.class);
-  LdapServerProperties ldapServerProperties = createMock(LdapServerProperties.class);
   DirContextOperations userData = createMock(DirContextOperations.class);
   UserEntity userEntity = createMock(UserEntity.class);
   PrincipalEntity principalEntity = createMock(PrincipalEntity.class);
@@ -68,23 +50,9 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
   GroupEntity groupEntity = createMock(GroupEntity.class);
   PrivilegeEntity privilegeEntity = createMock(PrivilegeEntity.class);
 
-  Set<RoleEntity> roleSetStub = new HashSet<RoleEntity>();
-  String username = "user";
-  String adminRole = "role";
-  String userRole = "userRole";
-  Map<String, String> configs = new HashMap<String, String>();
-
-  public TestAmbariLdapAuthoritiesPopulator() {
-    configs.put(Configuration.ADMIN_ROLE_NAME_KEY, adminRole);
-    configs.put(Configuration.USER_ROLE_NAME_KEY, userRole);
-
-  }
-
   @Before
   public void setUp() throws Exception {
     resetAll();
-
-    expect(configuration.getConfigsMap()).andReturn(configs).anyTimes();
   }
 
   @Test
@@ -92,15 +60,7 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
     String username = "user";
 
     AmbariLdapAuthoritiesPopulator populator = createMockBuilder(AmbariLdapAuthoritiesPopulator.class)
-        .addMockedMethod("createLdapUser")
-        .withConstructor(
-            configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO, memberDAO, privilegeDAO
-        ).createMock();
-
-
-    expect(ldapServerProperties.isGroupMappingEnabled()).andReturn(false).atLeastOnce();
-
-    expect(configuration.getLdapServerProperties()).andReturn(ldapServerProperties).atLeastOnce();
+        .withConstructor(helper, userDAO, memberDAO, privilegeDAO).createMock();
 
     expect(userEntity.getPrincipal()).andReturn(principalEntity);
     expect(memberDAO.findAllMembersByUser(userEntity)).andReturn(Collections.singletonList(memberEntity));
@@ -111,13 +71,9 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
     principalEntityList.add(groupPrincipalEntity);
     expect(privilegeDAO.findAllByPrincipal(principalEntityList)).andReturn(Collections.singletonList(privilegeEntity));
 
-    populator.createLdapUser(username);
-    expectLastCall();
-
-    expect(userDAO.findLdapUserByName(username)).andReturn(null).andReturn(userEntity);
+    expect(userDAO.findLdapUserByName(username)).andReturn(userEntity);
     replayAll();
 
-
     populator.getGrantedAuthorities(userData, username);
 
     verifyAll();
@@ -127,20 +83,8 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
   @Test
   public void testGetGrantedAuthorities_mappingEnabled() throws Exception {
 
-
     AmbariLdapAuthoritiesPopulator populator = createMockBuilder(AmbariLdapAuthoritiesPopulator.class)
-        .addMockedMethod("createLdapUser")
-        .addMockedMethod("addRole")
-        .addMockedMethod("removeRole")
-        .withConstructor(
-            configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO, memberDAO, privilegeDAO
-        ).createMock();
-
-    expect(userData.getObjectAttribute("ambari_admin")).andReturn(Boolean.TRUE).andReturn(Boolean.FALSE);
-
-    expect(ldapServerProperties.isGroupMappingEnabled()).andReturn(true).atLeastOnce();
-
-    expect(configuration.getLdapServerProperties()).andReturn(ldapServerProperties).atLeastOnce();
+        .withConstructor(helper, userDAO, memberDAO, privilegeDAO).createMock();
 
     expect(userEntity.getPrincipal()).andReturn(principalEntity).anyTimes();
     expect(memberDAO.findAllMembersByUser(userEntity)).andReturn(Collections.singletonList(memberEntity)).anyTimes();
@@ -151,158 +95,16 @@ public class TestAmbariLdapAuthoritiesPopulator extends EasyMockSupport {
     principalEntityList.add(groupPrincipalEntity);
     expect(privilegeDAO.findAllByPrincipal(principalEntityList)).andReturn(Collections.singletonList(privilegeEntity)).anyTimes();
 
-    expect(userDAO.findLdapUserByName(username)).andReturn(null).andReturn(userEntity).times(2);
-
-    populator.createLdapUser(username);
-    expectLastCall();
-    populator.addRole(userEntity, adminRole);
-    expectLastCall();
-    populator.removeRole(userEntity, adminRole);
-    expectLastCall();
+    expect(userDAO.findLdapUserByName(EasyMock.<String> anyObject())).andReturn(null).andReturn(userEntity).once();
 
     replayAll();
 
     //test with admin user
-    populator.getGrantedAuthorities(userData, username);
+    populator.getGrantedAuthorities(userData, "admin");
     //test with non-admin
-    populator.getGrantedAuthorities(userData, username);
-
-    verifyAll();
-  }
-
-  @Test
-  public void testCreateLdapUser() throws Exception {
-    AmbariLdapAuthoritiesPopulator populator = createMockBuilder(AmbariLdapAuthoritiesPopulator.class)
-        .addMockedMethod("addRole")
-        .addMockedMethod("removeRole")
-        .withConstructor(
-            configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO, memberDAO, privilegeDAO
-        ).createMock();
-
-    Capture<UserEntity> createEntity = new Capture<UserEntity>();
-    Capture<UserEntity> addRoleEntity = new Capture<UserEntity>();
-    Capture<PrincipalEntity> principalEntity = new Capture<PrincipalEntity>();
-
-    userDAO.create(capture(createEntity));
-    expectLastCall();
-
-    populator.addRole(capture(addRoleEntity), eq(userRole));
-    expectLastCall();
-
-    PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
-    principalTypeEntity.setId(PrincipalTypeEntity.USER_PRINCIPAL_TYPE);
-    principalTypeEntity.setName(PrincipalTypeEntity.USER_PRINCIPAL_TYPE_NAME);
-
-    expect(principalTypeDAO.findById(1)).andReturn(principalTypeEntity);
-
-    principalDAO.create(capture(principalEntity));
-
-    replayAll();
-
-    populator.createLdapUser(username);
-
-    verifyAll();
-
-    UserEntity capturedCreateEntity = createEntity.getValue();
-    UserEntity capturedAddRoleEntity = addRoleEntity.getValue();
-
-    assertTrue(capturedCreateEntity.getLdapUser());
-    assertEquals(username, capturedCreateEntity.getUserName());
-
-    assertEquals(capturedCreateEntity,capturedAddRoleEntity);
-
-  }
-
-
-  @Test
-  public void testAddRole() throws Exception {
-    AmbariLdapAuthoritiesPopulator populator =
-        new AmbariLdapAuthoritiesPopulator(configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO,
-            memberDAO, privilegeDAO);
-
-    RoleEntity roleEntity = createMock(RoleEntity.class);
-    Set<UserEntity> userEntities = createMock(Set.class);
-    Set<RoleEntity> roleEntities = createMock(Set.class);
-
-    Capture<RoleEntity> createdRole = new Capture<RoleEntity>();
-
-    expect(roleDAO.findByName(adminRole)).andReturn(null).andReturn(roleEntity);
-    expect(roleDAO.findByName(adminRole)).andReturn(roleEntity);
-
-    roleDAO.create(capture(createdRole));
-    expectLastCall();
-
-    expect(userEntity.getUserName()).andReturn(username).anyTimes();
-    expect(userEntity.getRoleEntities()).andReturn(roleEntities).anyTimes();
-
-    expect(roleEntity.getUserEntities()).andReturn(userEntities).anyTimes();
-
-    expect(roleEntities.contains(roleEntity)).andReturn(false);
-    expect(roleEntities.contains(roleEntity)).andReturn(true);
-
-    expect(userEntities.add(userEntity)).andReturn(true);
-    expect(roleEntities.add(roleEntity)).andReturn(true);
-
-    userDAO.merge(userEntity);
-    expectLastCall().andReturn(userEntity);
-    roleDAO.merge(roleEntity);
-    expectLastCall().andReturn(roleEntity);
-
-    expect(userDAO.findLdapUserByName(username)).andReturn(null).andReturn(userEntity);
-    expect(userDAO.findLdapUserByName(username)).andReturn(userEntity);
-
-    userDAO.create(userEntity);
-    expectLastCall();
-
-    replayAll();
-
-    populator.addRole(userEntity, adminRole);
-    populator.addRole(userEntity, adminRole);
+    populator.getGrantedAuthorities(userData, "user");
 
     verifyAll();
-
-    assertEquals(adminRole, createdRole.getValue().getRoleName());
-
   }
 
-
-  @Test
-  public void testRemoveRole() throws Exception {
-    int userId = 123;
-
-    AmbariLdapAuthoritiesPopulator populator =
-        new AmbariLdapAuthoritiesPopulator(configuration, helper, userDAO, roleDAO, principalDAO, principalTypeDAO,
-            memberDAO, privilegeDAO);
-
-    RoleEntity roleEntity = createMock(RoleEntity.class);
-    Set<UserEntity> userEntities = createMock(Set.class);
-    Set<RoleEntity> roleEntities = createMock(Set.class);
-
-    expect(userEntity.getUserId()).andReturn(userId);
-
-    expect(userDAO.findByPK(userId)).andReturn(userEntity);
-
-    expect(roleDAO.findByName(adminRole)).andReturn(roleEntity);
-
-    expect(userEntity.getRoleEntities()).andReturn(roleEntities);
-
-    expect(roleEntities.contains(roleEntity)).andReturn(true);
-
-    expect(userEntity.getUserName()).andReturn(username);
-
-    expect(userEntity.getRoleEntities()).andReturn(roleEntities);
-    expect(roleEntity.getUserEntities()).andReturn(userEntities);
-
-    expect(userEntities.remove(userEntity)).andReturn(true);
-    expect(roleEntities.remove(roleEntity)).andReturn(true);
-
-    expect(userDAO.merge(userEntity)).andReturn(userEntity);
-    expect(roleDAO.merge(roleEntity)).andReturn(roleEntity);
-
-    replayAll();
-
-    populator.removeRole(userEntity, adminRole);
-
-    verifyAll();
-  }
 }

+ 0 - 87
ambari-server/src/test/java/org/apache/ambari/server/security/authorization/TestUsers.java

@@ -35,11 +35,9 @@ import org.apache.ambari.server.orm.dao.GroupDAO;
 import org.apache.ambari.server.orm.dao.MemberDAO;
 import org.apache.ambari.server.orm.dao.PrincipalDAO;
 import org.apache.ambari.server.orm.dao.PrincipalTypeDAO;
-import org.apache.ambari.server.orm.dao.RoleDAO;
 import org.apache.ambari.server.orm.dao.UserDAO;
 import org.apache.ambari.server.orm.entities.PrincipalEntity;
 import org.apache.ambari.server.orm.entities.PrincipalTypeEntity;
-import org.apache.ambari.server.orm.entities.RoleEntity;
 import org.apache.ambari.server.orm.entities.UserEntity;
 import org.junit.After;
 import org.junit.Before;
@@ -66,8 +64,6 @@ public class TestUsers {
   @Inject
   protected MemberDAO memberDAO;
   @Inject
-  protected RoleDAO roleDAO;
-  @Inject
   protected PrincipalTypeDAO principalTypeDAO;
   @Inject
   protected PrincipalDAO principalDAO;
@@ -82,7 +78,6 @@ public class TestUsers {
     injector = Guice.createInjector(module);
     injector.getInstance(GuiceJpaInitializer.class);
     injector.injectMembers(this);
-    users.createDefaultRoles();
     Authentication auth = new UsernamePasswordAuthenticationToken("admin", null);
     SecurityContextHolder.getContext().setAuthentication(auth);
   }
@@ -214,83 +209,6 @@ public class TestUsers {
     fail("Exception was not thrown");
   }
 
-  @Test(expected = AmbariException.class)
-  public void testPromoteUser() throws Exception {
-    users.createUser("admin", "admin");
-    users.createUser("admin2", "admin2");
-    User user = users.getLocalUser("admin");
-    assertTrue(user.getRoles().contains(users.getUserRole()));
-    assertFalse(user.getRoles().contains(users.getAdminRole()));
-    users.promoteToAdmin(user);
-    user = users.getLocalUser("admin2");
-    users.promoteToAdmin(user);
-
-    user = users.getLocalUser("admin");
-    assertTrue(user.getRoles().contains(users.getAdminRole()));
-
-    users.demoteAdmin(user);
-
-    user = users.getLocalUser("admin");
-    assertFalse(user.getRoles().contains(users.getAdminRole()));
-
-    user = users.getLocalUser("admin2");
-    users.demoteAdmin(user);
-
-  }
-
-  @Test(expected = AmbariException.class)
-  public void testRemoveUser() throws Exception {
-    users.createUser("admin", "admin");
-    User user = users.getLocalUser("admin");
-    users.promoteToAdmin(user);
-
-    user = users.getLocalUser("admin");
-    assertTrue(user.getRoles().contains(users.getAdminRole()));
-
-    users.removeUser(user);
-  }
-
-
-  @Test
-  public void testPromoteLdapUser() throws Exception {
-    createLdapUser();
-
-    User ldapUser = users.getLdapUser("ldapUser");
-    users.createUser("localadmin", "admin");
-    User localUser = users.getLocalUser("localadmin");
-    users.promoteToAdmin(localUser);
-
-    users.promoteToAdmin(ldapUser);
-
-    ldapUser = users.getLdapUser("ldapUser");
-    assertTrue(ldapUser.getRoles().contains(users.getAdminRole()));
-
-    users.demoteAdmin(ldapUser);
-
-    ldapUser = users.getLdapUser("ldapUser");
-    assertFalse(ldapUser.getRoles().contains(users.getAdminRole()));
-
-    users.removeUser(ldapUser);
-
-    //toggle group mapping
-    properties.setProperty(Configuration.LDAP_GROUP_BASE_KEY, "ou=groups,dc=ambari,dc=apache,dc=org");
-    createLdapUser();
-
-    try {
-      users.promoteToAdmin(ldapUser);
-      fail("Not allowed with mapping on");
-    } catch (AmbariException e) {
-    }
-
-    try {
-      users.demoteAdmin(ldapUser);
-      fail("Not allowed with mapping on");
-    } catch (AmbariException e) {
-    }
-
-
-  }
-
   private void createLdapUser() {
 
     PrincipalTypeEntity principalTypeEntity = new PrincipalTypeEntity();
@@ -301,7 +219,6 @@ public class TestUsers {
     principalEntity.setPrincipalType(principalTypeEntity);
     principalDAO.create(principalEntity);
 
-    RoleEntity role = roleDAO.findByName(users.getUserRole());
     UserEntity ldapUser = new UserEntity();
 
     ldapUser.setUserName("ldapUser");
@@ -312,10 +229,6 @@ public class TestUsers {
 
     UserEntity userEntity = userDAO.findLdapUserByName("ldapUser");
 
-    userEntity.getRoleEntities().add(role);
-    role.getUserEntities().add(ldapUser);
-
     userDAO.merge(ldapUser);
-    roleDAO.merge(role);
   }
 }

+ 6 - 2
ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeCatalog170Test.java

@@ -247,6 +247,7 @@ public class UpgradeCatalog170Test {
     Order o = createNiceMock(Order.class);
     TypedQuery<HostRoleCommandEntity> q = createNiceMock(TypedQuery.class);
     List<HostRoleCommandEntity> r = new ArrayList<HostRoleCommandEntity>();
+    ResultSet userRolesResultSet = createNiceMock(ResultSet.class);
 
     Method m = AbstractUpgradeCatalog.class.getDeclaredMethod
         ("updateConfigurationProperties", String.class, Map.class, boolean.class, boolean.class);
@@ -292,9 +293,11 @@ public class UpgradeCatalog170Test {
         Collections.singletonMap("min_user_id", "1000"), false, false);
     expectLastCall();
 
+    expect(dbAccessor.executeSelect("SELECT role_name, user_id FROM user_roles")).andReturn(userRolesResultSet).once();
     expect(entityManager.getTransaction()).andReturn(trans).anyTimes();
     expect(entityManager.getCriteriaBuilder()).andReturn(cb).anyTimes();
     expect(entityManager.createQuery(cq)).andReturn(q).anyTimes();
+    expect(userRolesResultSet.next()).andReturn(false).once();
     expect(trans.isActive()).andReturn(true).anyTimes();
     expect(upgradeCatalog.getEntityManagerProvider()).andReturn(entityManagerProvider).anyTimes();
     expect(cb.createQuery(HostRoleCommandEntity.class)).andReturn(cq).anyTimes();
@@ -362,7 +365,8 @@ public class UpgradeCatalog170Test {
     keyValueDAO.remove(showJobsKeyValue);
     privilegeDAO.create(anyObject(PrivilegeEntity.class));
 
-    replay(entityManager, trans, upgradeCatalog, cb, cq, hrc, q);
+    replay(entityManager, trans, upgradeCatalog, cb, cq, hrc, q, userRolesResultSet);
+
     replay(dbAccessor, configuration, injector, cluster, clusters, amc, config, configHelper, pigConfig);
     replay(userDAO, clusterDAO, viewDAO, viewInstanceDAO, permissionDAO);
     replay(resourceTypeDAO, resourceDAO, keyValueDAO, privilegeDAO);
@@ -382,7 +386,7 @@ public class UpgradeCatalog170Test {
     upgradeCatalog.executeDMLUpdates();
 
     verify(upgradeCatalog, dbAccessor, configuration, injector, cluster, clusters, amc, config, configHelper,
-        jobsView, showJobsKeyValue, privilegeDAO, viewDAO, viewInstanceDAO, resourceDAO, keyValueDAO);
+        jobsView, showJobsKeyValue, privilegeDAO, viewDAO, viewInstanceDAO, resourceDAO, keyValueDAO, userRolesResultSet);
   }
 
 

+ 0 - 8
ambari-server/src/test/java/org/apache/ambari/server/upgrade/UpgradeTest.java

@@ -23,15 +23,10 @@ import com.google.inject.Injector;
 import com.google.inject.Key;
 import com.google.inject.TypeLiteral;
 import com.google.inject.persist.PersistService;
-import org.apache.ambari.server.configuration.ComponentSSLConfiguration;
 import org.apache.ambari.server.configuration.Configuration;
-import org.apache.ambari.server.controller.AmbariServer;
 import org.apache.ambari.server.controller.ControllerModule;
 import org.apache.ambari.server.orm.DBAccessor;
-import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
 import org.apache.ambari.server.orm.dao.*;
-import org.apache.ambari.server.security.CertificateManager;
-import org.apache.ambari.server.state.Config;
 import org.apache.ambari.server.utils.VersionUtils;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -45,8 +40,6 @@ import java.sql.SQLException;
 import java.sql.SQLNonTransientConnectionException;
 import java.util.*;
 
-import static org.junit.Assert.assertTrue;
-
 @RunWith(Parameterized.class)
 public class UpgradeTest {
   private static final Logger LOG = LoggerFactory.getLogger(UpgradeTest.class);
@@ -139,7 +132,6 @@ public class UpgradeTest {
     requestDAO.findAllResourceFilters();
     injector.getInstance(RequestScheduleBatchRequestDAO.class).findAll();
     injector.getInstance(RequestScheduleDAO.class).findAll();
-    injector.getInstance(RoleDAO.class).findAll();
     injector.getInstance(RoleSuccessCriteriaDAO.class).findAll();
     injector.getInstance(ServiceComponentDesiredStateDAO.class).findAll();
     injector.getInstance(ServiceDesiredStateDAO.class).findAll();

+ 6 - 2
ambari-server/src/test/java/org/apache/ambari/server/view/ViewRegistryTest.java

@@ -158,6 +158,7 @@ public class ViewRegistryTest {
   private static final ResourceTypeDAO resourceTypeDAO = createNiceMock(ResourceTypeDAO.class);
   private static final SecurityHelper securityHelper = createNiceMock(SecurityHelper.class);
   private static final Configuration configuration = createNiceMock(Configuration.class);
+  private static final ViewInstanceHandlerList handlerList = createNiceMock(ViewInstanceHandlerList.class);
 
   @Test
   public void testReadViewArchives() throws Exception {
@@ -521,7 +522,9 @@ public class ViewRegistryTest {
     expect(viewInstanceDAO.merge(viewInstanceEntity)).andReturn(null);
     expect(viewInstanceDAO.findByName("MY_VIEW{1.0.0}", viewInstanceEntity.getInstanceName())).andReturn(viewInstanceEntity);
 
-    replay(viewDAO, viewInstanceDAO, securityHelper);
+    handlerList.addViewInstance(viewInstanceEntity);
+
+    replay(viewDAO, viewInstanceDAO, securityHelper, handlerList);
 
     registry.addDefinition(viewEntity);
     registry.installViewInstance(viewInstanceEntity);
@@ -532,7 +535,7 @@ public class ViewRegistryTest {
 
     Assert.assertEquals(viewInstanceEntity, viewInstanceDefinitions.iterator().next());
 
-    verify(viewDAO, viewInstanceDAO, securityHelper);
+    verify(viewDAO, viewInstanceDAO, securityHelper, handlerList);
   }
 
   @Test
@@ -856,6 +859,7 @@ public class ViewRegistryTest {
     instance.resourceTypeDAO = resourceTypeDAO;
     instance.securityHelper = securityHelper;
     instance.configuration = configuration;
+    instance.handlerList = handlerList;
 
     return instance;
   }

+ 2 - 1
ambari-server/src/test/python/stacks/1.3.2/HIVE/test_hive_service_check.py

@@ -86,7 +86,8 @@ class TestServiceCheck(RMFTestCase):
                               conf_dir = '/etc/hadoop/conf',
                               keytab='/etc/security/keytabs/hdfs.headless.keytab',
                               kinit_path_local='/usr/bin/kinit',
-                              security_enabled=True
+                              security_enabled=True,
+                              principal='hdfs'
     )
     self.assertResourceCalled('Execute', '/usr/bin/kinit -kt /etc/security/keytabs/smokeuser.headless.keytab ambari-qa; sh /tmp/hcatSmoke.sh hcatsmoke cleanup',
                         logoutput = True,

File diff ditekan karena terlalu besar
+ 0 - 0
ambari-server/src/test/python/stacks/1.3.2/configs/secured.json


+ 2 - 1
ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_service_check.py

@@ -86,7 +86,8 @@ class TestServiceCheck(RMFTestCase):
                         conf_dir = '/etc/hadoop/conf',
                         keytab='/etc/security/keytabs/hdfs.headless.keytab',
                         kinit_path_local='/usr/bin/kinit',
-                        security_enabled=True
+                        security_enabled=True,
+                        principal='hdfs'
     )
     self.assertResourceCalled('Execute', '/usr/bin/kinit -kt /etc/security/keytabs/smokeuser.headless.keytab ambari-qa;  /tmp/hcatSmoke.sh hcatsmoke cleanup',
                         logoutput = True,

File diff ditekan karena terlalu besar
+ 0 - 0
ambari-server/src/test/python/stacks/2.0.6/configs/secured.json


File diff ditekan karena terlalu besar
+ 0 - 0
ambari-server/src/test/python/stacks/2.1/configs/secured.json


+ 12 - 19
ambari-web/app/app.js

@@ -33,27 +33,13 @@ module.exports = Em.Application.create({
     recordCache: []
   }),
   isAdmin: false,
+  isOperator: false,
   /**
    * return url prefix with number value of version of HDP stack
    */
   stackVersionURL: function () {
-    var stackVersion = this.get('currentStackVersion') || this.get('defaultStackVersion');
-    if (stackVersion.indexOf('HDPLocal') !== -1) {
-      return '/stacks/HDPLocal/versions/' + stackVersion.replace(/HDPLocal-/g, '');
-    }
-    return '/stacks/HDP/versions/' + stackVersion.replace(/HDP-/g, '');
-  }.property('currentStackVersion'),
-
-  /**
-   * return url prefix with number value of version of HDP stack
-   */
-  stack2VersionURL: function () {
-    var stackVersion = this.get('currentStackVersion') || this.get('defaultStackVersion');
-    if (stackVersion.indexOf('HDPLocal') !== -1) {
-      return '/stacks2/HDPLocal/versions/' + stackVersion.replace(/HDPLocal-/g, '');
-    }
-    return '/stacks2/HDP/versions/' + stackVersion.replace(/HDP-/g, '');
-  }.property('currentStackVersion'),
+    return '/stacks/{0}/versions/{1}'.format(this.get('currentStackName') || 'HDP', this.get('currentStackVersionNumber'));
+  }.property('currentStackName','currentStackVersionNumber'),
 
   falconServerURL: function () {
     var falconService = this.Service.find().findProperty('serviceName', 'FALCON');
@@ -66,13 +52,20 @@ module.exports = Em.Application.create({
   clusterName: null,
   clockDistance: null, // server clock - client clock
   currentStackVersion: '',
-  currentStackVersionNumber: function () {
-    return this.get('currentStackVersion').replace(/HDP(Local)?-/, '');
+  currentStackName: function() {
+    return Em.get((this.get('currentStackVersion') || this.get('defaultStackVersion')).match(/(.+)-\d.+/), '1');
   }.property('currentStackVersion'),
+
+  currentStackVersionNumber: function () {
+    var regExp = new RegExp(this.get('currentStackName') + '-');
+    return (this.get('currentStackVersion') || this.get('defaultStackVersion')).replace(regExp, '');
+  }.property('currentStackVersion', 'currentStackName'),
+
   isHadoop2Stack: function () {
     return (stringUtils.compareVersions(this.get('currentStackVersionNumber'), "2.0") === 1 ||
       stringUtils.compareVersions(this.get('currentStackVersionNumber'), "2.0") === 0)
   }.property('currentStackVersionNumber'),
+
   isHadoop21Stack: function () {
     return (stringUtils.compareVersions(this.get('currentStackVersionNumber'), "2.1") === 1 ||
       stringUtils.compareVersions(this.get('currentStackVersionNumber'), "2.1") === 0)

+ 0 - 1
ambari-web/app/config.js

@@ -28,7 +28,6 @@ App.testEnableSecurity = true; // By default enable security is tested; turning
 App.testNameNodeHA = true;
 App.apiPrefix = '/api/v1';
 App.defaultStackVersion = 'HDP-2.0.5';
-App.defaultLocalStackVersion = 'HDPLocal-2.0.5';
 App.defaultJavaHome = '/usr/jdk/jdk1.6.0_31';
 App.timeout = 180000; // default AJAX timeout
 App.maxRetries = 3; // max number of retries for certain AJAX calls

+ 4 - 4
ambari-web/app/controllers/global/cluster_controller.js

@@ -22,7 +22,6 @@ App.ClusterController = Em.Controller.extend({
   name: 'clusterController',
   isLoaded: false,
   ambariProperties: null,
-  ambariViews: [],
   clusterDataLoadedPercent: 'width:0', // 0 to 1
 
   isGangliaUrlLoaded: false,
@@ -249,7 +248,6 @@ App.ClusterController = Em.Controller.extend({
   loadClusterData: function () {
     var self = this;
     this.loadAmbariProperties();
-    this.loadAmbariViews();
     if (!App.get('clusterName')) {
       return;
     }
@@ -311,7 +309,7 @@ App.ClusterController = Em.Controller.extend({
         service.StackServices.is_selected = true;
         service.StackServices.is_installed = false;
       },this);
-      App.stackServiceMapper.map(data);
+      App.stackServiceMapper.mapStackServices(data);
       App.config.setPreDefinedServiceConfigs();
       var updater = App.router.get('updateController');
       self.updateLoadStatus('stackComponents');
@@ -385,7 +383,9 @@ App.ClusterController = Em.Controller.extend({
             instanceName: instance.ViewInstanceInfo.instance_name,
             href: instance.ViewInstanceInfo.context_path
           });
-          self.get('ambariViews').pushObject(current_instance);
+          if( current_instance.visible){
+            self.get('ambariViews').pushObject(current_instance);
+          }
         }, this);
       }, this);
     }, this);

+ 0 - 7
ambari-web/app/controllers/installer.js

@@ -761,13 +761,6 @@ App.InstallerController = App.WizardController.extend({
       var step = this.get('isStepDisabled').findProperty('step', i);
       step.set('value', true);
     }
-  },
-
-  /**
-   * Clear loaded recommendations
-   */
-  clearRecommendations: function() {
-    this.set('content.recommendations', undefined)
   }
 });
 

+ 1 - 0
ambari-web/app/controllers/main.js

@@ -44,6 +44,7 @@ App.MainController = Em.Controller.extend({
    */
   initialize: function(){
     App.router.get('clusterController').loadClusterData();
+    App.router.get('mainViewsController').loadAmbariViews();
   },
 
   dataLoading: function () {

+ 6 - 2
ambari-web/app/controllers/main/admin/repositories.js

@@ -31,6 +31,9 @@ App.MainAdminRepositoriesController = Em.Controller.extend({
     if (App.router.get('clusterController.isLoaded')) {
       App.ajax.send({
         name: 'cluster.update_upgrade_version',
+        data: {
+          stackName: App.get('currentStackName')
+        },
         sender: this,
         success: 'updateUpgradeVersionSuccessCallback',
         error: 'updateUpgradeVersionErrorCallback'
@@ -41,7 +44,8 @@ App.MainAdminRepositoriesController = Em.Controller.extend({
   updateUpgradeVersionSuccessCallback: function (data) {
     var upgradeVersion = this.get('upgradeVersion') || App.get('defaultStackVersion');
     var currentVersion = App.get('currentStackVersionNumber');
-    upgradeVersion = upgradeVersion.replace(/HDP-/, '');
+    var stackNamePrefix = App.get('currentStackName') + '-';
+    upgradeVersion = upgradeVersion.replace(stackNamePrefix, '');
     data.items.mapProperty('Versions.stack_version').forEach(function (version) {
       upgradeVersion = (stringUtils.compareVersions(upgradeVersion, version) === -1) ? version : upgradeVersion;
     });
@@ -52,7 +56,7 @@ App.MainAdminRepositoriesController = Em.Controller.extend({
       upgradeVersion = currentVersion;
       upgradeStack = currentStack;
     }
-    upgradeVersion = 'HDP-' + upgradeVersion;
+    upgradeVersion = stackNamePrefix + upgradeVersion;
     this.set('upgradeVersion', upgradeVersion);
     if (currentStack && upgradeStack) {
       this.parseServicesInfo(currentStack, upgradeStack);

+ 79 - 1
ambari-web/app/controllers/main/views_controller.js

@@ -21,9 +21,87 @@ var App = require('app');
 App.MainViewsController = Em.Controller.extend({
   name:'mainViewsController',
 
+  isDataLoaded: false,
+
+  ambariViews: [],
+
+  dataLoading: function () {
+    var viewsController = this;
+    var dfd = $.Deferred();
+    if (this.get('isDataLoaded')) {
+      dfd.resolve(this.get('ambariViews'));
+    } else {
+      var interval = setInterval(function () {
+        if (viewsController.get('isDataLoaded')) {
+          dfd.resolve(viewsController.get('ambariViews'));
+          clearInterval(interval);
+        }
+      }, 50);
+    }
+    return dfd.promise();
+  },
+
+
+  loadAmbariViews: function () {
+    App.ajax.send({
+      name: 'views.info',
+      sender: this,
+      success: 'loadAmbariViewsSuccess',
+      error: 'loadAmbariViewsError'
+    });
+  },
+
+  loadAmbariViewsSuccess: function (data, opt, params) {
+    if (data.items.length) {
+      App.ajax.send({
+        name: 'views.instances',
+        sender: this,
+        success: 'loadViewInstancesSuccess',
+        error: 'loadViewInstancesError'
+      });
+    } else {
+      this.set('ambariViews', []);
+      this.set('isDataLoaded', true);
+    }
+  },
+
+  loadAmbariViewsError: function () {
+    this.set('ambariViews', []);
+    this.set('isDataLoaded', true);
+  },
+
+  loadViewInstancesSuccess: function (data, opt, params) {
+    this.set('ambariViews', []);
+    var instances = [];
+    data.items.forEach(function (view) {
+      view.versions.forEach(function (version) {
+        version.instances.forEach(function (instance) {
+          var current_instance = Em.Object.create({
+            iconPath: instance.ViewInstanceInfo.icon_path || "/img/ambari-view-default.png",
+            label: instance.ViewInstanceInfo.label || version.ViewVersionInfo.label || instance.ViewInstanceInfo.view_name,
+            visible: instance.ViewInstanceInfo.visible || false,
+            version: instance.ViewInstanceInfo.version,
+            description: instance.ViewInstanceInfo.description || Em.I18n.t('views.main.instance.noDescription'),
+            viewName: instance.ViewInstanceInfo.view_name,
+            instanceName: instance.ViewInstanceInfo.instance_name,
+            href: instance.ViewInstanceInfo.context_path
+          });
+          instances.push(current_instance);
+        }, this);
+      }, this);
+    }, this);
+    this.get('ambariViews').pushObjects(instances);
+    this.set('isDataLoaded', true);
+  },
+
+  loadViewInstancesError: function () {
+    this.set('ambariViews', []);
+    this.set('isDataLoaded', true);
+  },
+
   setView: function(event) {
     if(event.context){
-      App.router.transitionTo('main.views.viewDetails', event.context);
+      App.router.transitionTo('views.viewDetails', event.context);
     }
   }
 });

+ 25 - 4
ambari-web/app/controllers/wizard/step5_controller.js

@@ -17,10 +17,11 @@
  */
 
 var App = require('app');
+var blueprintUtils = require('utils/blueprint');
 var numberUtils = require('utils/number_utils');
 var validationUtils = require('utils/validator');
 
-App.WizardStep5Controller = Em.Controller.extend({
+App.WizardStep5Controller = Em.Controller.extend(App.BlueprintMixin, {
 
   name: "wizardStep5Controller",
 
@@ -52,6 +53,14 @@ App.WizardStep5Controller = Em.Controller.extend({
     return this.get('content.controllerName') == 'highAvailabilityWizardController';
   }.property('content.controllerName'),
 
+  /**
+   * Check if <code>installerWizard</code> used
+   * @type {bool}
+   */
+  isInstallerWizard: function () {
+    return this.get('content.controllerName') === 'installerController';
+  }.property('content.controllerName'),
+
   /**
    * Is AddServiceWizard used
    * @type {bool}
@@ -154,6 +163,15 @@ App.WizardStep5Controller = Em.Controller.extend({
     return this.get('servicesMasters').some(function(m) { return m.get('warnMessage'); }) || this.get('generalWarningMessages').some(function(m) { return m; });
   }.property('servicesMasters.@each.warnMessage', 'generalWarningMessages'),
 
+    /**
+   * Clear loaded recommendations
+   */
+  clearRecommendations: function() {
+    if (this.get('content.recommendations')) {
+      this.set('content.recommendations', null);
+    }
+  },
+
   /**
    * List of host with assigned masters
    * Format:
@@ -223,7 +241,7 @@ App.WizardStep5Controller = Em.Controller.extend({
       self.set('submitDisabled', true);
 
       // reset previous recommendations
-      this.set('content.recommendations', null);
+      this.clearRecommendations();
 
       if (self.get('servicesMasters').length === 0) {
         return;
@@ -326,7 +344,7 @@ App.WizardStep5Controller = Em.Controller.extend({
   },
 
   /**
-   * Composes selected values of comboboxes into blueprint format
+   * Composes selected values of comboboxes into master blueprint + merge it with currenlty installed slave blueprint
    */
   getCurrentBlueprint: function() {
     var self = this;
@@ -359,7 +377,7 @@ App.WizardStep5Controller = Em.Controller.extend({
       res.blueprint_cluster_binding.host_groups.push(binding);
     });
 
-    return res;
+    return blueprintUtils.mergeBlueprints(res, self.getCurrentSlaveBlueprint());
   },
 
 /**
@@ -506,7 +524,10 @@ App.WizardStep5Controller = Em.Controller.extend({
       };
 
       if (includeMasters) {
+        // Made partial recommendation request for reflect in blueprint host-layout changes which were made by user in UI
         data.recommendations = self.getCurrentBlueprint();
+      } else if (!self.get('isInstallerWizard')) {
+        data.recommendations = self.getCurrentMasterSlaveBlueprint();
       }
 
       return App.ajax.send({

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini