d2eb1c73588d8afe0adeb12c9cfad8053810b565
[aquarium] / src / main / scala / gr / grnet / aquarium / logic / accounting / RoleAgreements.scala
1 /*
2  * Copyright 2011-2012 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35
36 package gr.grnet.aquarium.logic.accounting
37
38 import dsl.DSLAgreement
39 import gr.grnet.aquarium.util.Loggable
40 import gr.grnet.aquarium.Configurator
41 import gr.grnet.aquarium.Configurator.{MasterConfigurator, Keys}
42 import io.Source
43 import java.io.{InputStream, File}
44 import java.util.regex.Pattern
45
46 /**
47  * Encapsulates mappings from user roles to Aquarium policies. The mappings
48  * are used during new user registration to automatically set a policy to
49  * a user according to its role.
50  *
51  * The configuration is read from a configuration file pointed to by the
52  * main Aquarium configuration file. The
53  *
54  * @author Georgios Gousios <gousiosg@gmail.com>
55  */
56 object RoleAgreements extends Loggable {
57
58   private var mappings: Map[String, DSLAgreement] = loadMappings
59
60   /**
61    * Returns the agreement that matches the provided role. The search for a
62    * matching agreement is done with the current version of the Aquarium
63    * policy.
64    */
65   def agreementForRole(role : String) = mappings.get(role.toLowerCase) match {
66     case Some(x) => x
67     case None => mappings.get("*").getOrElse(
68       throw new RuntimeException("Cannot find agreement for default role *"))
69   }
70
71   /**
72    * Trigger reloading of the mappings file.
73    */
74   def reloadMappings = mappings = loadMappings
75
76   /**
77    * Load and parse the mappings file
78    */
79   private[logic] def loadMappings = synchronized {
80     val config = MasterConfigurator.get(Keys.aquarium_role_agreement_map)
81     val configFile = MasterConfigurator.findConfigFile(
82       Configurator.RolesAgreementsName, Keys.aquarium_role_agreement_map,
83       Configurator.RolesAgreementsName)
84
85     def loadFromClasspath: Source = {
86       getClass.getClassLoader.getResourceAsStream(Configurator.RolesAgreementsName) match {
87         case x: InputStream =>
88           logger.warn("Using default role to agreement mappings, this is " +
89             "problably not what you want")
90           Source.fromInputStream(x)
91         case null =>
92           logger.error("No valid role to agreement mappings configuration found, " +
93             "Aquarium will fail")
94           null
95       }
96     }
97
98     val source = if (configFile.exists && configFile.isFile) {
99         if (configFile.isFile)
100           Source.fromFile(configFile)
101         else {
102           logger.warn(("Configured file %s is a directory. " +
103             "Trying the default one.").format(config))
104           loadFromClasspath
105         }
106     } else {
107         logger.warn("Configured file %s for role-agreement mappings cannot " +
108           "be found. Trying the default one.".format(config))
109         loadFromClasspath
110     }
111
112     parseMappings(source)
113   }
114
115   def parseMappings(src: Source) = {
116     val p = Pattern.compile("^\\s*([\\*a-zA-Z0-9-_]+)\\s*=\\s*([a-zA-Z0-9-_]+).*$")
117
118     val mappings = src.getLines.foldLeft(Map[String, DSLAgreement]()) {
119       (acc, l) =>
120         l match {
121           case x if (x.matches("^\\s*$")) => acc
122           case x if (x.matches("^\\s*\\#")) => acc
123           case x if (p.matcher(x).find()) =>
124             // Ugly code warning
125             val m = p.matcher(x)
126             m.find()
127             val role = m.group(1)
128             val agrName = m.group(2)
129             Policy.policy.findAgreement(agrName) match {
130               case Some(x) => acc ++ Map(role -> x)
131               case None =>
132                 logger.warn("No agreement with name %s".format(agrName))
133                 acc
134             }
135           case _ => acc
136         }
137     }
138     if (!mappings.keysIterator.contains("*"))
139       throw new RuntimeException("Cannot find agreement for default role *")
140     mappings
141   }
142 }