language-puppet (empty) → 0.1.3
raw patch · 25 files changed
+3650/−0 lines, 25 filesdep +Globdep +MissingHdep +basesetup-changed
Dependencies added: Glob, MissingH, base, bytestring, containers, cryptohash, filepath, hslogger, language-puppet, mtl, parsec, pretty, process, regexpr, unix
Files
- Erb/Compute.hs +70/−0
- Erb/Parser.hs +111/−0
- Erb/Ruby.hs +39/−0
- LICENSE +675/−0
- Puppet/DSL/Loader.hs +14/−0
- Puppet/DSL/Parser.hs +516/−0
- Puppet/DSL/Printer.hs +87/−0
- Puppet/DSL/Types.hs +141/−0
- Puppet/Daemon.hs +382/−0
- Puppet/Init.hs +26/−0
- Puppet/Interpreter/Catalog.hs +859/−0
- Puppet/Interpreter/Functions.hs +65/−0
- Puppet/Interpreter/Types.hs +131/−0
- Puppet/NativeTypes.hs +14/−0
- Puppet/NativeTypes/File.hs +46/−0
- Puppet/NativeTypes/Helpers.hs +101/−0
- Puppet/Printers.hs +50/−0
- SafeProcess.hs +68/−0
- Setup.hs +2/−0
- bench/lexer.hs +4/−0
- language-puppet.cabal +93/−0
- ruby/calcerb.rb +56/−0
- test/expr.hs +22/−0
- test/interpreter.hs +52/−0
- test/lexer.hs +26/−0
+ Erb/Compute.hs view
@@ -0,0 +1,70 @@+module Erb.Compute(computeTemplate, getTemplateFile, initTemplateDaemon) where++import Data.List+import Puppet.Interpreter.Types+import Puppet.Init+import SafeProcess+import System.IO+import qualified Data.List.Utils as DLU+import Control.Monad.Error+import Control.Concurrent+import System.Posix.Files+import Paths_language_puppet (getDataFileName)++type TemplateQuery = (Chan TemplateAnswer, String, String, [(String, GeneralValue)])+type TemplateAnswer = Either String String++initTemplateDaemon :: Prefs -> IO (String -> String -> [(String, GeneralValue)] -> IO (Either String String))+initTemplateDaemon (Prefs _ modpath templatepath _ _) = do+ controlchan <- newChan+ forkIO (templateDaemon modpath templatepath controlchan)+ return (templateQuery controlchan)++templateQuery :: Chan TemplateQuery -> String -> String -> [(String, GeneralValue)] -> IO (Either String String)+templateQuery qchan filename scope variables = do+ rchan <- newChan+ writeChan qchan (rchan, filename, scope, variables)+ readChan rchan++templateDaemon :: String -> String -> Chan TemplateQuery -> IO ()+templateDaemon modpath templatepath qchan = do+ (respchan, filename, scope, variables) <- readChan qchan+ let parts = DLU.split "/" filename+ searchpathes | length parts > 1 = [modpath ++ "/" ++ head parts ++ "/templates/" ++ (DLU.join "/" (tail parts)), templatepath ++ "/" ++ filename]+ | otherwise = [templatepath ++ "/" ++ filename]+ acceptablefiles <- filterM fileExist searchpathes+ if(null acceptablefiles)+ then writeChan respchan (Left $ "Can't find template file for " ++ filename ++ ", looked in " ++ show searchpathes)+ else computeTemplate (head acceptablefiles) scope variables >>= writeChan respchan+ templateDaemon modpath templatepath qchan++computeTemplate :: String -> String -> [(String, GeneralValue)] -> IO TemplateAnswer+computeTemplate filename curcontext variables = do+ let rubyvars = "{\n" ++ intercalate ",\n" (concatMap toRuby variables ) ++ "\n}\n"+ input = curcontext ++ "\n" ++ filename ++ "\n" ++ rubyvars+ rubyscriptpath <- getDataFileName "ruby/calcerb.rb"+ ret <- safeReadProcessTimeout "ruby" [rubyscriptpath] input 1000+ case ret of+ Just (Right x) -> return $ Right x+ Just (Left er) -> do+ (tmpfilename, tmphandle) <- openTempFile "/tmp" "templatefail"+ hPutStr tmphandle input+ hClose tmphandle+ return $ Left $ er ++ " - for template " ++ filename ++ " input in " ++ tmpfilename+ Nothing -> do+ return $ Left "Process did not terminate"++getTemplateFile :: String -> CatalogMonad String+getTemplateFile rawpath = do+ throwError rawpath++toRuby (_, Left _) = []+toRuby (_, Right ResolvedUndefined) = []+toRuby (varname, Right varval) = ["\t" ++ show varname ++ " => " ++ toRuby' varval]+toRuby' (ResolvedString str) = show str+toRuby' (ResolvedInt i) = "'" ++ show i ++ "'"+toRuby' (ResolvedBool True) = "true"+toRuby' (ResolvedBool False) = "false"+toRuby' (ResolvedArray rr) = "[" ++ intercalate ", " (map toRuby' rr) ++ "]"+toRuby' (ResolvedHash hh) = "{ " ++ intercalate ", " (map (\(varname, varval) -> show varname ++ " => " ++ toRuby' varval) hh) ++ " }"+toRuby' x = show x
+ Erb/Parser.hs view
@@ -0,0 +1,111 @@+module Erb.Parser where++import Text.Parsec.String+import Text.Parsec.Prim+import Text.Parsec.Char+import Text.Parsec.Combinator+import Text.Parsec.Language (emptyDef)+import Erb.Ruby+import Text.Parsec.Expr+import qualified Text.Parsec.Token as P+++def = emptyDef+ { P.commentStart = "/*"+ , P.commentEnd = "*/"+ , P.commentLine = "#"+ , P.nestedComments = True+ , P.identStart = letter+ , P.identLetter = alphaNum <|> oneOf "_"+ , P.reservedNames = ["if", "else", "case", "elsif"]+ , P.reservedOpNames= ["=>","=","+","-","/","*","+>","->","~>","!"]+ , P.caseSensitive = True+ }++lexer = P.makeTokenParser def+parens = P.parens lexer+braces = P.braces lexer+operator = P.operator lexer+symbol = P.symbol lexer+reservedOp = P.reservedOp lexer+whiteSpace = P.whiteSpace lexer+naturalOrFloat = P.naturalOrFloat lexer+identifier = P.identifier lexer++rubyexpression = buildExpressionParser table term <?> "expression"+ +table = [ [ Infix ( reservedOp "+" >> return PlusOperation ) AssocLeft + , Infix ( reservedOp "-" >> return MinusOperation ) AssocLeft ]+ , [ Infix ( reservedOp "/" >> return DivOperation ) AssocLeft + , Infix ( reservedOp "*" >> return MultiplyOperation ) AssocLeft ]+ , [ Infix ( reservedOp "<<" >> return ShiftLeftOperation ) AssocLeft + , Infix ( reservedOp ">>" >> return ShiftRightOperation ) AssocLeft ]+ , [ Infix ( reservedOp "and" >> return AndOperation ) AssocLeft + , Infix ( reservedOp "or" >> return OrOperation ) AssocLeft ]+ , [ Infix ( reservedOp "==" >> return EqualOperation ) AssocLeft + , Infix ( reservedOp "!=" >> return DifferentOperation ) AssocLeft ]+ , [ Infix ( reservedOp ">" >> return AboveOperation ) AssocLeft + , Infix ( reservedOp ">=" >> return AboveEqualOperation ) AssocLeft+ , Infix ( reservedOp "<=" >> return UnderEqualOperation ) AssocLeft + , Infix ( reservedOp "<" >> return UnderOperation ) AssocLeft ]+ , [ Infix ( reservedOp "=~" >> return RegexpOperation ) AssocLeft + , Infix ( reservedOp "!~" >> return NotRegexpOperation ) AssocLeft ]+ , [ Prefix ( symbol "!" >> return NotOperation ) ]+ , [ Prefix ( symbol "-" >> return NegOperation ) ]+ , [ Infix ( reservedOp "?" >> return ConditionalValue ) AssocLeft ]+ , [ Infix ( reservedOp "." >> return MethodCall ) AssocLeft ]+ ]+term+ = parens rubyexpression+ <|> objectterm+ <|> variablereference++blockinfo = many1 $ noneOf "}"++objectterm = do+ methodname <- identifier >>= return . Value . Literal+ isblock <- optionMaybe (symbol "{")+ case isblock of+ Just _ -> do+ b <- blockinfo+ symbol "}"+ return $ MethodCall methodname (BlockOperation b)+ Nothing -> return $ Object methodname++variablereference = identifier >>= return . Object . Value . Literal++rubystatement = rubyexpression >>= return . Puts++textblock :: Parser [RubyStatement]+textblock = do+ s <- many (noneOf "<")+ let returned = Puts $ Value $ Literal s+ isend <- optionMaybe eof+ case isend of+ Just _ -> return [returned]+ Nothing -> do+ char '<'+ isrub <- optionMaybe (char '%')+ let nextrun = case isrub of+ Just _ -> rubyblock+ Nothing -> textblock+ n <- nextrun+ return (returned : n)+++rubyblock :: Parser [RubyStatement]+rubyblock = do+ isequal <- optionMaybe (char '=')+ parsed <- case isequal of+ Just _ -> spaces >> rubyexpression >>= return . Puts+ Nothing -> spaces >> rubystatement+ string "%>"+ n <- textblock+ return (parsed : n)++erbparser :: Parser [RubyStatement]+erbparser = textblock++parseErbFile fname = do+ input <- readFile fname+ return (runParser erbparser () fname input)
+ Erb/Ruby.hs view
@@ -0,0 +1,39 @@+module Erb.Ruby where++data Value+ = Literal String+ deriving (Show, Ord, Eq)++data Expression+ = LookupOperation Expression Expression+ | PlusOperation Expression Expression+ | MinusOperation Expression Expression+ | DivOperation Expression Expression+ | MultiplyOperation Expression Expression+ | ShiftLeftOperation Expression Expression+ | ShiftRightOperation Expression Expression+ | AndOperation Expression Expression+ | OrOperation Expression Expression+ | EqualOperation Expression Expression+ | DifferentOperation Expression Expression+ | AboveOperation Expression Expression+ | AboveEqualOperation Expression Expression+ | UnderEqualOperation Expression Expression+ | UnderOperation Expression Expression+ | RegexpOperation Expression Expression+ | NotRegexpOperation Expression Expression+ | NotOperation Expression+ | NegOperation Expression+ | ConditionalValue Expression Expression+ | Object Expression+ | MethodCall Expression Expression+ | BlockOperation String+ | Value Value+ | BTrue+ | BFalse+ | Error String+ deriving (Show, Ord, Eq)++data RubyStatement+ = Puts Expression+ deriving(Show)
+ LICENSE view
@@ -0,0 +1,675 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.+ + "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.+ + If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.+
+ Puppet/DSL/Loader.hs view
@@ -0,0 +1,14 @@+module Puppet.DSL.Loader (parseFile) where++import Text.Parsec+import Puppet.DSL.Types+import Puppet.DSL.Parser+import Control.Monad.Error++-- | Helper function that takes a filename and parses its content in the 'ErrorT' monad.+parseFile :: FilePath -> ErrorT String IO [Statement]+parseFile fpath = do+ result <- liftIO $ readFile fpath+ case (runParser mparser () fpath result) of+ Left err -> throwError (show err)+ Right st -> return st
+ Puppet/DSL/Parser.hs view
@@ -0,0 +1,516 @@+{-|+This module exports the functions that will be useful to parse the DSL. They+should be able to parse everything you throw at them. The Puppet language is+extremely irregular, and most valid constructs are not documented in the+official language guide. This parser has been created by parsing the author's+own large manifests and the public Wikimedia ones.++Things that are known to not to be properly supported are :++ * \"plussignement\" such as foo +\> bar. How to handle this is far from+ being obvious, as its actual behaviour is not documented.+-}+module Puppet.DSL.Parser (+ parse,+ mparser,+ exprparser+) where++import Data.Char+import Text.Parsec+import qualified Text.Parsec.Token as P+import Text.Parsec.Expr+import Text.Parsec.Language (emptyDef)+import Data.List.Utils+import Puppet.DSL.Types++def = emptyDef+ { P.commentStart = "/*"+ , P.commentEnd = "*/"+ , P.commentLine = "#"+ , P.nestedComments = True+ , P.identStart = letter+ , P.identLetter = alphaNum <|> oneOf "_"+ , P.reservedNames = ["if", "else", "case", "elsif", "and", "or", "in", "import", "include", "define", "require", "class", "node"]+ , P.reservedOpNames= ["=>","=","+","-","/","*","+>","->","~>","!"]+ , P.caseSensitive = True+ } ++lexer = P.makeTokenParser def+parens = P.parens lexer+--braces = P.braces lexer+--operator = P.operator lexer+symbol = P.symbol lexer+reservedOp = P.reservedOp lexer+reserved = P.reserved lexer+whiteSpace = P.whiteSpace lexer+-- stringLiteral = P.stringLiteral lexer+naturalOrFloat = P.naturalOrFloat lexer++lowerFirstChar :: String -> String+lowerFirstChar x = [toLower $ head x] ++ (tail x)++-- expression parser+{-| This is a parser for Puppet 'Expression's. -}+exprparser = buildExpressionParser table term <?> "expression"+ +table = [ + [ Infix ( reservedOp "?" >> return ConditionalValue ) AssocLeft ]+ , [ Prefix ( symbol "-" >> return NegOperation ) ]+ , [ Prefix ( symbol "!" >> return NotOperation ) ]+ , [ Infix ( reserved "in" >> return IsElementOperation ) AssocLeft ]+ , [ Infix ( reserved "and" >> return AndOperation ) AssocLeft + , Infix ( reserved "or" >> return OrOperation ) AssocLeft ]+ , [ Infix ( reservedOp "<<" >> return ShiftLeftOperation ) AssocLeft + , Infix ( reservedOp ">>" >> return ShiftRightOperation ) AssocLeft ]+ , [ Infix ( reservedOp "/" >> return DivOperation ) AssocLeft + , Infix ( reservedOp "*" >> return MultiplyOperation ) AssocLeft ]+ , [ Infix ( reservedOp "+" >> return PlusOperation ) AssocLeft + , Infix ( reservedOp "-" >> return MinusOperation ) AssocLeft ]+ , [ Infix ( reservedOp "==" >> return EqualOperation ) AssocLeft + , Infix ( reservedOp "!=" >> return DifferentOperation ) AssocLeft ]+ , [ Infix ( reservedOp ">" >> return AboveOperation ) AssocLeft + , Infix ( reservedOp ">=" >> return AboveEqualOperation ) AssocLeft+ , Infix ( reservedOp "<=" >> return UnderEqualOperation ) AssocLeft + , Infix ( reservedOp "<" >> return UnderOperation ) AssocLeft ]+ , [ Infix ( reservedOp "=~" >> return RegexpOperation ) AssocLeft + , Infix ( reservedOp "!~" >> return NotRegexpOperation ) AssocLeft ]+ ]+term = parens exprparser+ <|> puppetInterpolableString+ <|> puppetUndefined+ <|> puppetRegexpExpr+ <|> puppetVariableOrHashLookup+ <|> puppetNumeric+ <|> puppetArray+ <|> puppetHash+ <|> try puppetResourceReference+ <|> try puppetFunctionCall+ <|> puppetLiteralValue+ <?> "Expression terminal"++hashRef = do { symbol "["+ ; e <- exprparser+ ; symbol "]"+ ; return e+ }++puppetVariableOrHashLookup = do { v <- puppetVariable+ ; whiteSpace+ ; hashlist <- many hashRef+ ; case hashlist of+ [] -> return $ Value (VariableReference v)+ _ -> return $ makeLookupOperation v hashlist+ }++makeLookupOperation :: String -> [Expression] -> Expression+makeLookupOperation name exprs = foldl lookups (LookupOperation (Value (VariableReference name)) (head exprs)) (tail exprs)+ where+ lookups ctx v = LookupOperation ctx v++identstring = many1 (alphaNum <|> oneOf "-_")++identifier = do {+ x <- identstring+ ; whiteSpace+ ; return x+ }++puppetResourceReference = do { rtype <- puppetQualifiedReference+ ; symbol "["+ ; rnames <- exprparser `sepBy` (symbol ",")+ ; symbol "]"+ ; if length rnames == 1+ then return $ Value (ResourceReference rtype (head rnames))+ else return $ Value $ PuppetArray $ map (\rname -> Value $ ResourceReference rtype rname) rnames+ }++puppetResourceOverride = do { pos <- getPosition+ ; rtype <- puppetQualifiedReference+ ; symbol "["+ ; rname <- exprparser `sepBy` (symbol ",")+ ; symbol "]"+ ; symbol "{"+ ; e <- puppetAssignment `sepEndBy` (symbol ",")+ ; symbol "}"+ ; return (map (\n -> ResourceOverride rtype n e pos) rname)+ }++puppetInclude = do { pos <- getPosition+ ; try $ reserved "include"+ ; vs <- (puppetQualifiedName <|> puppetLiteral) `sepBy` (symbol ",")+ ; return $ map (\v -> Include v pos) vs+ }++puppetRequire = do { pos <- getPosition+ ; try $ reserved "require"+ ; v <- puppetLiteral `sepBy` (symbol ",")+ ; return $ map (\x -> Require x pos) v+ }++puppetQualifiedName = do { optional (string "::")+ ; firstletter <- lower+ ; parts <- identstring `sepBy` (try $ string "::")+ ; whiteSpace+ ; return $ [firstletter] ++ (join "::" parts)+ }++puppetQualifiedReference = do { optional (string "::")+ ; firstletter <- upper <?> "Uppercase letter for a reference"+ ; parts <- identstring `sepBy` (string "::")+ ; whiteSpace+ ; return $ [toLower firstletter] ++ (join "::" $ map lowerFirstChar parts)+ }++puppetFunctionCall = do { funcname <- identifier+ ; symbol "("+ ; e <- exprparser `sepEndBy` (symbol ",")+ ; symbol ")"+ ; return $ Value (FunctionCall funcname e)+ }++puppetArrayRaw = do { symbol "["+ ; e <- exprparser `sepEndBy` (symbol ",")+ ; symbol "]"+ ; return e+ }++puppetArray = do { e <- puppetArrayRaw+ ; return $ Value (PuppetArray e)+ }++puppetHash = do { symbol "{"+ ; e <- puppetAssignment `sepEndBy` (symbol ",")+ ; symbol "}"+ ; return $ Value (PuppetHash (Parameters e))+ }++puppetAssignment = do { n <- puppetRegexpExpr <|> puppetVariableOrHashLookup <|> puppetLiteralValue+ ; symbol "=>"+ ; v <- exprparser+ ; return $ (n, v)+ }++nodeDeclaration = do { pos <- getPosition+ ; try $ reserved "node"+ ; whiteSpace+ ; n <- puppetRegexp <|> puppetLiteral -- TODO HANDLE+ ; symbol "{"+ ; e <- many stmtparser+ ; symbol "}"+ ; return [ Node n (concat e) pos ]+ }++-- no trailing whiteSpace+puppetVariable = do+ char '$'+ choice+ [ do { char '{' ; o <- many1 $ noneOf "}" ; char '}' ; return o }+ , do { s <- option "" (string "::") ; o <- identstring `sepBy` (try $ string "::") ; return $ s ++ (join "::" o) }+ ]++variableAssignment = do { pos <- getPosition+ ; varname <- puppetVariable+ ; whiteSpace+ ; symbol "="+ ; e <- exprparser+ ; return [VariableAssignment varname e pos]+ }++-- types de base+-- puppetLiteral : toutes les strings puppet++puppetLiteral = doubleQuotedString+ <|> singleQuotedString+ <|> puppetQualifiedName+ <|> identifier++puppetLiteralValue = do { v <- puppetLiteral+ ; return (Value (Literal v))+ }++puppetRegexp = do { char '/'+ ; v <- many ( do { char '\\' ; x <- anyChar; return ['\\', x] } <|> many1 (noneOf "/\\") )+ ; symbol "/"+ ; return $ concat v+ }++puppetRegexpExpr = puppetRegexp >>= return . Value . PuppetRegexp++singleQuotedString = do { char '\''+ ; v <- many ( do { char '\\' ; x <- anyChar; return [x] } <|> many1 (noneOf "'\\") )+ ; char '\''+ ; whiteSpace+ ; return $ concat v+ }++doubleQuotedString = do { char '"'+ ; v <- option "" doubleQuotedStringContent+ ; char '"'+ ; whiteSpace+ ; return v+ }++puppetInterpolableString = do { char '"'+ ; v <- many (+ try ( do { x <- puppetVariable+ ; return $ VariableReference x+ } )+ <|> do { x <- doubleQuotedStringContent+ ; return $ Literal x+ }+ <|> do { char '$'+ ; return $ Literal "$"+ }+ <?> "Interpolable string content"+ )+ ; char '"'+ ; whiteSpace+ ; return $ Value (Interpolable v)+ }++doubleQuotedStringContent = do { x <- many1 (do { char '\\' ; x <- anyChar; return [stringEscape x] } <|> many1 (noneOf "\"\\$") )+ ; return $ concat x+ }++stringEscape 'n' = '\n'+stringEscape 't' = '\t'+stringEscape 'r' = '\r'+stringEscape '"' = '"'+stringEscape '\\' = '\\'+stringEscape '$' = '$'+stringEscape x = error $ "unknown escape pattern \\" ++ [x]++puppetUndefined = do+ try $ string "undef"+ whiteSpace+ return $ Value $ Undefined++puppetNumeric = do { v <- naturalOrFloat+ ; return (case v of+ Left x -> (Value . Integer) x + Right x -> (Value . Double) x+ )+ }++puppetResourceGroup = do+ (virtcount, v) <- try ( do {+ virtcount <- many (char '@')+ ; v <- puppetQualifiedName+ ; symbol "{"+ ; return (virtcount, v)+ } )+ x <- (resourceArrayDeclaration <|> resourceDeclaration) `sepEndBy` (symbol ";" <|> symbol ",")+ symbol "}"+ case virtcount of+ "" -> return $ map (\(rname, rvalues, pos) -> (Resource v rname rvalues Normal pos)) (concat x)+ "@" -> return $ map (\(rname, rvalues, pos) -> (Resource v rname rvalues Virtual pos)) (concat x)+ "@@" -> return $ map (\(rname, rvalues, pos) -> (Resource v rname rvalues Exported pos)) (concat x)+ _ -> unexpected "Too many @'s"+ ++-- todo parse resource collection properly+puppetResourceCollection = do { pos <- getPosition+ ; rtype <- puppetQualifiedReference+ ; chev <- many1 (char '<')+ ; symbol "|"+ ; e <- option BTrue exprparser+ ; symbol "|"+ ; many1 (char '>')+ ; whiteSpace+ ; overrides <- option [] (do { symbol "{"+ ; ne <- puppetAssignment `sepEndBy` (symbol ",")+ ; symbol "}"+ ; return ne+ })+ ; case chev of+ "<" -> return [ VirtualResourceCollection rtype e overrides pos ]+ "<<" -> return [ ResourceCollection rtype e overrides pos ]+ _ -> error $ "Invalid resource collection syntax at " ++ (show pos)+ }++resourceArrayDeclaration = do { pos <- getPosition+ ; v <- puppetArrayRaw+ ; symbol ":"+ ; x <- puppetAssignment `sepEndBy` symbol ","+ ; return $ map (\nm -> (nm, x, pos)) v+ }++resourceDeclaration = do { pos <- getPosition+ ; v <- (puppetVariableOrHashLookup <|> puppetInterpolableString <|> puppetLiteralValue )+ ; whiteSpace+ ; symbol ":"+ ; x <- puppetAssignment `sepEndBy` symbol ","+ ; return [(v, x, pos)]+ }++puppetResourceDefaults = do { pos <- getPosition+ ; rtype <- puppetQualifiedReference+ ; symbol "{"+ ; e <- puppetAssignment `sepBy` symbol ","+ ; symbol "}"+ ; return [ResourceDefault rtype e pos]+ }++puppetClassParameter = do { varname <- puppetVariable+ ; whiteSpace+ ; defaultvalue <- optionMaybe ( do { symbol "="+ ; e <- exprparser+ ; return e+ } )+ ; return (varname, defaultvalue)+ }++puppetClassParameters = do { symbol "("+ ; pmt <- puppetClassParameter `sepBy` symbol ","+ ; symbol ")"+ ; return pmt+ }++puppetClassDefinition = do { pos <- getPosition+ ; try $ reserved "class"+ ; cname <- puppetQualifiedName+ ; params <- option [] puppetClassParameters+ ; cparent <- optionMaybe ( do { string "inherits"; whiteSpace ; p <- puppetQualifiedName; return p } )+ ; symbol "{"+ ; st <- many stmtparser+ ; symbol "}"+ ; return [ClassDeclaration cname cparent params (concat st) pos]+ }++puppetDefine = do { pos <- getPosition+ ; try $ reserved "define"+ ; cname <- puppetQualifiedName+ ; params <- option [] puppetClassParameters+ ; symbol "{"+ ; st <- many stmtparser+ ; symbol "}"+ ; return [DefineDeclaration cname params (concat st) pos]+ }+ ++puppetIfStyleCondition = do { cond <- exprparser <?> "Conditional expression"+ ; symbol "{"+ ; e <- many stmtparser+ ; symbol "}"+ ; return (cond, concat e)+ }+ +puppetElseIfCondition = do { reservedOp "elsif"+ ; whiteSpace+ ; out <- puppetIfStyleCondition+ ; return out+ }++puppetElseCondition = do { reservedOp "else"+ ; whiteSpace+ ; symbol "{"+ ; e <- many stmtparser+ ; symbol "}"+ ; return $ concat e+ }++puppetIfCondition = do { pos <- getPosition+ ; reserved "if"+ ; whiteSpace+ ; maincond <- puppetIfStyleCondition+ ; others <- option [] (many puppetElseIfCondition)+ ; elsec <- option [] puppetElseCondition+ ; return [ConditionalStatement ([maincond] ++ others ++ [(BTrue, elsec)]) pos]+ }++puppetCase = do { + compares <- exprparser `sepBy` symbol ","+ ; symbol ":"+ ; symbol "{"+ ; st <- many stmtparser+ ; symbol "}"+ ; return ( compares, concat st )+ }++puppetRegexpCase = do {+ expression <- puppetRegexp+ ; symbol ":"+ ; symbol "{"+ ; st <- many stmtparser+ ; symbol "}"+ ; return ( [Value (PuppetRegexp expression)], concat st )+ }++defaultCase = do {+ string "default"+ ; symbol ":"+ ; symbol "{"+ ; st <- many stmtparser+ ; symbol "}"+ ; return ( [BTrue], concat st )+ }++condsToExpression :: Expression -> ([Expression], [Statement]) -> [(Expression, [Statement])]+condsToExpression e (exprs, stmts) = map (\x -> condToExpression e (x, stmts)) exprs++condToExpression :: Expression -> (Expression, [Statement]) -> (Expression, [Statement])+condToExpression _ (BTrue, stmts) = (BTrue, stmts)+condToExpression e (Value (PuppetRegexp regexp), stmts) = (RegexpOperation e (Value (PuppetRegexp regexp)), stmts)+condToExpression e (cnd, stmts) = (EqualOperation e cnd, stmts)++puppetCaseCondition = do { pos <- getPosition+ ; reservedOp "case"+ ; whiteSpace+ ; expr1 <- exprparser+ ; symbol "{"+ ; condlist <- many1 (puppetRegexpCase <|> try defaultCase <|> puppetCase)+ ; symbol "}"+ ; return $ [ConditionalStatement (concat (map (\x -> condsToExpression expr1 x) condlist)) pos]+ }++puppetMainFunctionCall = do { pos <- getPosition+ ; name <- identifier+ ; whiteSpace+ ; hasParens <- optionMaybe $ symbol "("+ ; refs <- exprparser `sepEndBy` symbol ","+ ; case hasParens of+ Just _ -> symbol ")"+ _ -> return ""+ ; return [MainFunctionCall name refs pos]+ }++puppetChains = do { pos <- getPosition+ ; refs <- try (puppetResourceReference `sepBy1` symbol "->")+ ; let refToPair (Value (ResourceReference rtype name)) = (rtype, name)+ refToPair x = error $ "Could not run refToPair on " ++ show x+ ; let pairs = map refToPair refs+ ; let refpairs = zip pairs (tail pairs)+ ; return $ map (\((n1,v1),(n2,v2)) -> DependenceChain (n1,v1) (n2,v2) pos) refpairs+ }++puppetImport = do { pos <- getPosition+ ; try $ reserved "import"+ ; pattern <- puppetLiteral+ ; return [Import pattern pos]+ }++stmtparser = variableAssignment+ <|> puppetInclude+ <|> puppetRequire+ <|> puppetImport+ <|> nodeDeclaration+ <|> puppetDefine+ <|> puppetIfCondition+ <|> puppetCaseCondition+ <|> puppetResourceGroup+ <|> try (puppetResourceDefaults)+ <|> try (puppetResourceOverride)+ <|> try (puppetResourceCollection)+ <|> puppetClassDefinition+ <|> puppetChains+ <|> puppetMainFunctionCall+ <?> "Statement"++mparser = do {+ whiteSpace+ ; result <- many stmtparser+ ; eof+ ; return $ concat result+}+
+ Puppet/DSL/Printer.hs view
@@ -0,0 +1,87 @@+module Puppet.DSL.Printer (+ showAST,+ showVarMap+) where++import Text.PrettyPrint+import Puppet.DSL.Types+import qualified Data.Map as Map+import Text.Parsec.Pos++-- | This shows the parsed AST a bit like the original syntax.+showAST :: [Statement] -> String+showAST x = render (vcat (map showStatement x))++showStatement :: Statement -> Doc+showStatement (Node name x _) = text "node" <+> text name <+> lbrace $$ nest 4 (vcat (map showStatement x)) $$ rbrace+showStatement (VariableAssignment name x _) = text "$" <> text name <+> text "=" <+> showExpression x+showStatement (Include inc _) = text("include " ++ inc)+showStatement (Require req _) = text("require " ++ req)+showStatement (Resource rtype rname params Normal _) = text (rtype) <+> lbrace <+> showExpression rname <> text ":" $$ nest 4 ( showAssignments params ) <> text ";" $$ rbrace +showStatement (Resource rtype rname params Virtual p) = text "@" <> showStatement (Resource rtype rname params Normal p)+showStatement (Resource rtype rname params Exported p) = text "@@" <> showStatement (Resource rtype rname params Normal p)+showStatement (ResourceDefault rtype params _) = text (rtype) <+> braces (showAssignments params)+showStatement (ClassDeclaration cname Nothing params statements _) = text "class" <+> text cname <+> parens ( hcat (punctuate (text ",") (map showOptionalParameter params)) ) <+> lbrace $$ nest 4 (vcat (map showStatement statements)) $$ rbrace+showStatement (ClassDeclaration cname (Just parent) params statements _) = text "class" <+> text cname <> parens ( hcat (punctuate (text ",") (map showOptionalParameter params)) ) <+> text "inherits" <+> text parent <+> lbrace $$ nest 4 (vcat (map showStatement statements)) $$ rbrace+showStatement (DefineDeclaration cname params statements _) = text "define" <+> text cname <+> parens ( hcat (punctuate (text ",") (map showOptionalParameter params)) ) <+> lbrace $$ nest 4 (vcat (map showStatement statements)) $$ rbrace+showStatement (ConditionalStatement x _) = text "CONDITION LIST" $$ nest 4 ( vcat (map showCondition x) )+showStatement x = text (show x)++showCondition :: (Expression, [Statement]) -> Doc+showCondition (BTrue, []) = empty+showCondition (e, stmts) = showExpression e <+> text "{" $$ nest 4 ( vcat (map showStatement stmts)) $$ text "}"++showOptionalParameter :: (String, Maybe Expression) -> Doc+showOptionalParameter (param, Nothing) = text "$" <> text param+showOptionalParameter (param, (Just e)) = text "$" <> text param <+> text "=" <+> showExpression e++showExpressionBuilder :: String -> Expression -> Expression -> Doc+showExpressionBuilder symb a b = char '(' <> showExpression a <+> text symb <+> showExpression b <> char ')'++showExpression :: Expression -> Doc+showExpression (Value x) = showValue x+showExpression (ConditionalValue var conds) = showExpression var <+> text "=>" <+> showExpression conds+showExpression (PlusOperation a b) = showExpressionBuilder "+" a b+showExpression (MinusOperation a b) = showExpressionBuilder "-" a b+showExpression (DivOperation a b) = showExpressionBuilder "/" a b+showExpression (MultiplyOperation a b) = showExpressionBuilder "*" a b+showExpression (ShiftLeftOperation a b) = showExpressionBuilder "<<" a b+showExpression (ShiftRightOperation a b) = showExpressionBuilder ">>" a b+showExpression (AndOperation a b) = showExpressionBuilder "and" a b+showExpression (OrOperation a b) = showExpressionBuilder "or" a b+showExpression (EqualOperation a b) = showExpressionBuilder "==" a b+showExpression (DifferentOperation a b) = showExpressionBuilder "!=" a b+showExpression (AboveOperation a b) = showExpressionBuilder ">" a b+showExpression (AboveEqualOperation a b) = showExpressionBuilder ">=" a b+showExpression (UnderEqualOperation a b) = showExpressionBuilder "<=" a b+showExpression (UnderOperation a b) = showExpressionBuilder "<" a b+showExpression (RegexpOperation a b) = showExpressionBuilder "=~" a b+showExpression (NotRegexpOperation a b) = showExpressionBuilder "!~" a b+showExpression (NotOperation a) = char '(' <> char '!' <+> showExpression a <> char ')'+showExpression (NegOperation a) = char '(' <> char '-' <+> showExpression a <> char ')'+showExpression (BTrue) = text "true"+showExpression (BFalse) = text "false"+showExpression (LookupOperation a b) = showExpression a <> char '[' <> showExpression b <> char ']'+showExpression x = text (show x)++showValue :: Value -> Doc+showValue (Literal x) = text( show x )+showValue (VariableReference x) = text "$" <> text x+showValue (FunctionCall funcname args) = text funcname <> parens ( hcat (map showExpression args ) )+showValue (PuppetArray x) = brackets ( hcat ( punctuate (text ", ") (map showExpression x)))+showValue (ResourceReference rtype rname) = text rtype <> brackets (showExpression rname)+showValue (PuppetHash (Parameters params)) = hang lbrace 2 (showAssignments params) $$ rbrace+showValue (Integer x) = integer x+showValue x = text (show x)++showAssignments :: [(Expression, Expression)] -> Doc+showAssignments params = vcat ( punctuate (text ", ") (map showAssignment params ) )++showAssignment :: (Expression, Expression) -> Doc+showAssignment (param, value) = showExpression param <+> text "=>" <+> showExpression value++-- | Useful for displaying a map of variables.+showVarMap :: Map.Map String (Expression, SourcePos) -> String+showVarMap x = render $ vcat (map descLine (Map.toList x))+ where+ descLine (name, (expr, pos)) = text name <+> char '=' <+> showExpression expr <+> char '(' <> text (show pos) <> char ')'
+ Puppet/DSL/Types.hs view
@@ -0,0 +1,141 @@+-- | Types used when parsing the Puppet DSL.+-- A good knowledge of the Puppet language in required to understand them.+module Puppet.DSL.Types where++import Text.Parsec.Pos++data Parameters = Parameters [(Expression, Expression)] deriving(Show, Ord, Eq)++-- |This type is used to differenciate the distinct top level types that are+-- exposed by the DSL.+data TopLevelType+ -- |This is for node entries.+ = TopNode+ -- |This is for defines.+ | TopDefine+ -- |This is for classes.+ | TopClass+ -- |This one is special. It represents top level statements that are not+ -- part of a node, define or class. It is defined as spurious because it is+ -- not what you are supposed to be. Also the caching system doesn't like+ -- them too much right now.+ | TopSpurious+ deriving (Show, Ord, Eq)++-- |This function returns the 'TopLevelType' of a statement if it is either a+-- node, class or define. It returns Nothing otherwise.+convertTopLevel :: Statement -> Either Statement (TopLevelType, String, Statement)+convertTopLevel x@(Node name _ _) = Right (TopNode, name, x)+convertTopLevel x@(ClassDeclaration name _ _ _ _) = Right (TopClass, name, x)+convertTopLevel x@(DefineDeclaration name _ _ _) = Right (TopDefine, name, x)+convertTopLevel x = Left x++-- | The 'Value' type represents a Puppet value. It is the terminal in a puppet+-- 'Expression'+data Value+ -- |String literal.+ = Literal String+ -- |An interpolable string, represented as a 'Value' list.+ | Interpolable [Value]+ -- |A Puppet Regexp. This is very hackish as it alters the behaviour of some+ -- functions (such as conditional values).+ | PuppetRegexp String+ | Double Double+ | Integer Integer+ -- |Reference to a variable. The string contains what is acutally typed in+ -- the manifest.+ | VariableReference String+ | Empty+ | ResourceReference String Expression -- restype resname+ | PuppetArray [Expression]+ | PuppetHash Parameters+ | FunctionCall String [Expression]+ -- |This is special and quite hackish too.+ | Undefined+ deriving(Show, Ord, Eq)++data Virtuality = Normal | Virtual | Exported deriving(Show, Ord, Eq)++-- | The actual puppet statements+data Statement+ = Node String ![Statement] SourcePos -- ^ This holds the node name and list of statements.+ -- | This holds the variable name and the expression that it represents.+ | VariableAssignment String Expression SourcePos+ | Include String SourcePos+ | Import String SourcePos+ | Require String SourcePos+ -- | This holds the resource type, name, parameter list and virtuality.+ | Resource String Expression ![(Expression, Expression)] Virtuality SourcePos+ {-| This is a resource default declaration, such as File {owner => \'root\';+ }. It holds the resource type and the list of default parameters.+ -}+ | ResourceDefault String ![(Expression, Expression)] SourcePos+ {-| This works like 'Resource', but the 'Expression' holds the resource+ name.+ -}+ | ResourceOverride String Expression ![(Expression, Expression)] SourcePos+ {-| The pairs hold on the left a value that is resolved as a boolean, and on+ the right the list of statements that correspond to this. This will be+ generated by if\/then\/else statement, but also by the case statement.+ -}+ | ConditionalStatement ![(Expression, [Statement])] SourcePos+ {-| The class declaration holds the class name, the optional name of the+ class it inherits from, a list of parameters with optional default values,+ and the list of statements it contains.+ -}+ | ClassDeclaration String (Maybe String) ![(String, Maybe Expression)] ![Statement] SourcePos+ {-| The define declaration is like the 'ClassDeclaration' except it can't+ inherit from anything.+ -}+ | DefineDeclaration String ![(String, Maybe Expression)] ![Statement] SourcePos+ {-| This is the resource collection syntax (\<\<\| \|\>\>). It holds+ the conditional expression, and an eventual list of overrides. This is+ important as the same token conveys two distinct Puppet concepts : resource+ collection and resource overrides.+ -}+ | ResourceCollection String !Expression ![(Expression, Expression)] SourcePos+ -- |Same as 'ResourceCollection', but for \<\| \|\>.+ | VirtualResourceCollection String !Expression ![(Expression, Expression)] SourcePos+ | DependenceChain !(String,Expression) !(String,Expression) SourcePos+ | MainFunctionCall String ![Expression] SourcePos+ {-| This is a magic statement that is used to hold the spurious top level+ statements that comes in the same file as the correct top level statement+ that is stored in the second field. The first field contains pairs of+ filenames and statements. This is designed so that the interpreter can know+ whether it has already been evaluated.+ -}+ | TopContainer ![(String, Statement)] !Statement -- magic statement that is used to embody the spurious top level statements+ deriving(Show, Ord, Eq)++-- | Expressions will be described with a and b being the first and second field+-- of the constructor.+data Expression+ = LookupOperation !Expression !Expression -- ^ a[b]+ | IsElementOperation !Expression !Expression -- ^ a in b+ | PlusOperation !Expression !Expression -- ^ a + b+ | MinusOperation !Expression !Expression -- ^ a - b+ | DivOperation !Expression !Expression -- ^ a / b+ | MultiplyOperation !Expression !Expression -- ^ a * b+ | ShiftLeftOperation !Expression !Expression -- ^ a << b+ | ShiftRightOperation !Expression !Expression -- ^ a >> b+ | AndOperation !Expression !Expression -- ^ a & b+ | OrOperation !Expression !Expression -- ^ a | b+ | EqualOperation !Expression !Expression -- ^ a == b+ | DifferentOperation !Expression !Expression -- ^ a != b+ | AboveOperation !Expression !Expression -- ^ a > b+ | AboveEqualOperation !Expression !Expression -- ^ a >= b+ | UnderEqualOperation !Expression !Expression -- ^ a <= b+ | UnderOperation !Expression !Expression -- ^ a < b+ | RegexpOperation !Expression !Expression+ -- ^ a =~ b (b should be a 'PuppetRegexp')+ | NotRegexpOperation !Expression !Expression -- ^ a !~ b+ | NotOperation !Expression -- ^ ! a+ | NegOperation !Expression -- ^ - a+ | ConditionalValue !Expression !Expression+ -- ^ a ? b (b should be a 'PuppetHash')+ | Value Value -- ^ 'Value' terminal+ | ResolvedResourceReference String String -- ^ Resolved resource reference+ | BTrue -- ^ True expression, this could have been better to use a 'Value'+ | BFalse -- ^ False expression+ | Error String -- ^ Not used anymore.+ deriving(Show, Ord, Eq)
+ Puppet/Daemon.hs view
@@ -0,0 +1,382 @@+module Puppet.Daemon (initDaemon) where++import Puppet.Init+import Puppet.Interpreter.Types+import Puppet.Interpreter.Catalog+import Puppet.DSL.Types+import Puppet.DSL.Loader+import Erb.Compute+import Control.Concurrent+import System.Posix.Files+import System.FilePath.Glob (globDir, compile)+import System.FilePath.Posix (takeDirectory)+import Control.Monad.State+import Control.Monad.Error+import qualified System.Log.Logger as LOG+import Data.List +import Data.Either (rights, lefts)+import Data.Foldable (foldlM)+import qualified Data.List.Utils as DLU+import qualified Data.Map as Map+import Text.Parsec.Pos (initialPos)++-- this daemon returns a catalog when asked for a node and facts+data DaemonMessage+ = QCatalog (String, Facts, Chan DaemonMessage)+ | RCatalog (Either String FinalCatalog)++-- nbstats nbrequests+data DaemonStats = DaemonStats Int Integer+ deriving (Show)+++logDebug = LOG.debugM "Puppet.Daemon"+logInfo = LOG.infoM "Puppet.Daemon"+logWarning = LOG.warningM "Puppet.Daemon"+logError = LOG.errorM "Puppet.Daemon"++{-| This is a high level function, that will initialize the parsing and+interpretation infrastructure from the 'Prefs' structure, and will return a+function that will take a node name, 'Facts' and return either an error or the+'FinalCatalog'.++It will internaly initialize several threads that communicate with channels. It+should scale well, althrough it hasn't really been tested yet. It should cache+the ASL of every .pp file, and could use a bit of memory. As a comparison, it+fits in 60 MB with the author's manifests, but really breathes when given 300 MB+of heap space. In this configuration, even if it spawns a ruby process for every+template evaluation, it is way faster than the puppet stack.++It is recommended to ask for as many parser and interpreter threads as there are+CPUs.++Known bugs :++* It might be buggy when top level statements that are not class/define/nodes+are altered, or when files loaded with require are changed.++* Exported resources are not yet supported.++* The catalog is not computed exactly the same way Puppet does. Take a look at+"Puppet.Interpreter.Catalog" for a list of differences.++* Parsing incompatibilities are listed in "Puppet.DSL.Parser".++* There might be race conditions because file status are checked before they+are opened. This means the program might end with an exception when the file+is not existent. This will need fixing.++-}+initDaemon :: Prefs -> IO ( String -> Facts -> IO(Either String FinalCatalog) )+initDaemon prefs = do+ logDebug "initDaemon"+ controlChan <- newChan+ getstmts <- initParserDaemon prefs+ templatefunc <- initTemplateDaemon prefs+ forkIO (master prefs controlChan getstmts templatefunc)+ return (gCatalog controlChan)++master :: Prefs+ -> Chan DaemonMessage+ -> (TopLevelType -> String -> IO (Either String Statement))+ -> (String -> String -> [(String, GeneralValue)] -> IO (Either String String))+ -> IO ()+master prefs chan getstmts gettemplate = do+ message <- readChan chan+ case message of+ QCatalog (nodename, facts, respchan) -> do+ logDebug ("Received query for node " ++ nodename)+ (stmts, warnings) <- getCatalog getstmts gettemplate nodename facts+ mapM logWarning warnings+ case stmts of+ Left x -> writeChan respchan (RCatalog $ Left x)+ Right x -> writeChan respchan (RCatalog $ Right x)+ _ -> logError "Bad message type for master"+ master prefs chan getstmts gettemplate++gCatalog :: Chan DaemonMessage -> String -> Facts -> IO (Either String FinalCatalog)+gCatalog channel nodename facts = do+ respchan <- newChan+ writeChan channel $ QCatalog (nodename, facts, respchan)+ response <- readChan respchan+ case response of+ RCatalog x -> return x+ _ -> return $ Left "Bad answer from the master"++-- this daemon returns a list of statements when asked for a top class/define name+data ParserMessage+ = QStatement (TopLevelType, String, Chan ParserMessage)+ | RStatement (Either String Statement)++initParserDaemon :: Prefs -> IO+ ( TopLevelType -> String -> IO (Either String Statement)+ )+initParserDaemon prefs = do+ logDebug "initParserDaemon"+ controlChan <- newChan+ getparsed <- initParsedDaemon prefs+ forkIO (pmaster prefs controlChan (getparsed))+ return (getStatements controlChan)++-- extracts data from a filestatus+extractFStatus fs = (deviceID fs, fileID fs, modificationTime fs, fileSize fs)++getFileInfo :: FilePath -> IO (Maybe FileStatus)+getFileInfo fpath = do+ fexists <- fileExist fpath+ if fexists+ then do+ stat <- getFileStatus fpath+ return $ Just stat+ else return Nothing++getFirstFileInfo :: Maybe (FilePath, FileStatus) -> FilePath -> IO (Maybe (FilePath, FileStatus))+getFirstFileInfo (Just x) _ = return $ Just x+getFirstFileInfo Nothing y = do+ stat <- getFileInfo y+ case stat of+ Just x -> return $ Just (y, x)+ Nothing -> return Nothing++-- checks whether data pointed but the filepath has the corresponding file status+checkFileInfo :: FilePath -> FileStatus -> ErrorT String IO Bool+checkFileInfo fpath fstatus = do+ stat <- liftIO $ getFileInfo fpath+ case stat of+ Just nfstatus -> return (extractFStatus nfstatus == extractFStatus fstatus)+ Nothing -> return False++compilefilelist :: Prefs -> TopLevelType -> String -> [FilePath]+compilefilelist prefs TopNode _ = [manifest prefs ++ "/site.pp"]+compilefilelist prefs _ name = moduleInfo+ where+ moduleInfo | length nameparts == 1 = [modules prefs ++ "/" ++ name ++ "/manifests/init.pp"]+ | otherwise = [modules prefs ++ "/" ++ (head nameparts) ++ "/manifests/" ++ (DLU.join "/" (tail nameparts)) ++ ".pp"]+ nameparts = DLU.split "::" name++findFile :: Prefs -> TopLevelType -> String -> ErrorT String IO (FilePath, FileStatus)+findFile prefs qtype resname = do+ let filelist = compilefilelist prefs qtype resname+ fileinfo <- liftIO $ foldlM (getFirstFileInfo) Nothing filelist+ case fileinfo of+ Just x -> return x+ Nothing -> throwError ("Could not find file for " ++ show qtype ++ " " ++ resname ++ " when looking in " ++ (show filelist))++globImport :: FilePath -> Statement -> ErrorT String IO [FilePath]+globImport origfile (Import importname ipos) = do+ importedfiles <- liftIO $ globDir [compile importname] (takeDirectory origfile) >>= return . concat . fst+ if null importedfiles+ then throwError $ "Could not import " ++ importname ++ " at " ++ show ipos+ else return importedfiles+globImport _ x = throwError $ "Should not run globImport on " ++ show x++{-+ given a filename and a file status, will parse this file and update the cache with the parsed values++ it must also parse all required files and store everything about them before returning+ -}+loadUpdateFile :: FilePath -> FileStatus -> (TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse ) ) -> ErrorT String IO ([Statement], [(TopLevelType, String, Statement)])+loadUpdateFile fname fstatus updatepinfo = do+ liftIO $ logDebug ("Loading file " ++ fname)+ parsed <- parseFile fname+ let toplevels = map convertTopLevel parsed+ oktoplevels = rights toplevels+ othertoplevels = lefts toplevels+ (imports, spurioustoplevels) = partition isImport othertoplevels+ isImport (Import _ _) = True+ isImport _ = False+ relatedtops <- mapM (globImport fname) imports >>= return . concat+ -- save this spurious top levels+ if null spurioustoplevels+ then return ()+ else do+ liftIO ( updatepinfo TopSpurious fname (ClassDeclaration "::" Nothing [] spurioustoplevels (initialPos fname), fname, fstatus, relatedtops) >> return () )+ liftIO $ logWarning ("Spurious top level statement in file " ++ fname ++ ", expect bugs in case you modify them" )+ -- saves all good top levels+ liftIO $ mapM (\(rtype, resname, resstatement) -> updatepinfo rtype resname (resstatement, fname, fstatus, relatedtops)) oktoplevels+ return (imports, oktoplevels)++reparseStatements :: Prefs -> (TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse ) ) -> TopLevelType -> String -> ErrorT String IO Statement+reparseStatements prefs updatepinfo qtype nodename = do+ (fname, fstatus) <- findFile prefs qtype nodename+ reparseFile fname fstatus updatepinfo qtype nodename++reparseFile :: FilePath -> FileStatus -> (TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse ) ) -> TopLevelType -> String -> ErrorT String IO Statement+reparseFile fname fstatus updatepinfo qtype nodename = do+ (imports, oktoplevels) <- loadUpdateFile fname fstatus updatepinfo+ imported <- mapM (loadImport updatepinfo fname) imports >>= return . concat+ let searchstatement = find (\(qt,nm,_) -> (qt == qtype) && (nm == nodename)) (oktoplevels ++ imported)+ case searchstatement of+ Just (_,_,x) -> return x+ Nothing -> throwError ("Could not find correct top level statement for " ++ (show qtype) ++ " " ++ nodename)++ ++loadImport :: (TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse ) ) -> FilePath -> Statement -> ErrorT String IO [(TopLevelType, String, Statement)]+loadImport updatepinfo fdir mimport = do+ matched <- globImport fdir mimport+ -- globDir [compile importstring] fdir >>= return . concat . fst+ fileinfos <- liftIO $ mapM getFileInfo matched+ let fpathinfos = zip matched fileinfos+ goodpathinfos = concatMap unjust fpathinfos+ unjust (a, Just b) = [(a,b)]+ unjust _ = []+ mapM (\(fname, finfo) -> loadUpdateFile fname finfo updatepinfo) goodpathinfos >>= return . concatMap snd++loadRelated :: + ( TopLevelType -> String -> ErrorT String IO (Maybe CacheEntry) )+ -> FilePath+ -> ErrorT String IO [(String, Statement)]+loadRelated getpinfo filename = do+ res <- getpinfo TopSpurious filename+ case res of+ Nothing -> return []+ Just (stmts, _, _, related) -> do+ relstatements <- mapM (loadRelated getpinfo) related >>= return . concat+ return $ (filename,stmts):relstatements++handlePRequest :: Prefs ->+ ( TopLevelType -> String -> ErrorT String IO (Maybe CacheEntry)+ , TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse )+ , String -> IO ( ParsedCacheResponse )+ ) -> TopLevelType -> String -> ErrorT String IO Statement+handlePRequest prefs (getpinfo, updatepinfo, invalidateinfo) qtype nodename = do+ res <- getpinfo qtype nodename+ case res of+ Just (stmts, fpath, fstatus, related) -> do+ -- for this to work, everything must be cached+ -- this is buggy as the required stuff will not be invalidated properly+ relstatements <- mapM (loadRelated getpinfo) (fpath:related) >>= return . concat+ isfileinfoaccurate <- checkFileInfo fpath fstatus+ statements <- if isfileinfoaccurate+ then return stmts+ else do+ liftIO $ invalidateinfo fpath+ finfo <- liftIO $ getFileInfo fpath+ case finfo of+ Just fstat -> reparseFile fpath fstat updatepinfo qtype nodename+ Nothing -> reparseStatements prefs updatepinfo qtype nodename+ if null relstatements+ then return statements+ else return (TopContainer relstatements statements)+ Nothing -> reparseStatements prefs updatepinfo qtype nodename >> handlePRequest prefs (getpinfo, updatepinfo, invalidateinfo) qtype nodename++pmaster :: Prefs -> Chan ParserMessage ->+ ( TopLevelType -> String -> ErrorT String IO (Maybe CacheEntry)+ , TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse )+ , String -> IO ( ParsedCacheResponse )+ ) -> IO ()+pmaster prefs chan cachefuncs = do+ pmessage <- readChan chan+ case pmessage of+ QStatement (qtype, name, respchan) -> do+ out <- runErrorT $ handlePRequest prefs cachefuncs qtype name + case out of+ Left x -> writeChan respchan $ RStatement $ Left x+ Right y -> writeChan respchan $ RStatement $ Right y+ _ -> logError "Bad message type received by Puppet.Daemon.pmaster"+ pmaster prefs chan cachefuncs++getStatements :: Chan ParserMessage -> TopLevelType -> String -> IO (Either String Statement)+getStatements channel qtype classname = do+ respchan <- newChan+ writeChan channel $ QStatement (qtype, classname, respchan)+ response <- readChan respchan+ case response of+ RStatement x -> return x+ _ -> return $ Left "Bad answer from the pmaster"++-- this is a cache entry, it stores a top level statement, the path of the corresponding file and its status+-- it also stores a list of top level statements that are related+type CacheEntry = (Statement, FilePath, FileStatus, [FilePath])+data ParsedCacheQuery+ = GetParsedData TopLevelType String (Chan ParsedCacheResponse)+ | UpdateParsedData TopLevelType String CacheEntry (Chan ParsedCacheResponse)+ | InvalidateCacheFile String (Chan ParsedCacheResponse)+ | GetStats (Chan DaemonStats)+data ParsedCacheResponse+ = CacheError String+ | RCacheEntry CacheEntry+ | NoCacheEntry+ | CacheUpdated+ +-- this one is singleton, and is used to cache de parsed values, along with the file names they depend on+initParsedDaemon :: Prefs -> IO+ ( TopLevelType -> String -> ErrorT String IO (Maybe CacheEntry)+ , TopLevelType -> String -> CacheEntry -> IO ( ParsedCacheResponse )+ , String -> IO ( ParsedCacheResponse )+ )+initParsedDaemon prefs = do+ logDebug "initParsedDaemon"+ controlChan <- newChan+ forkIO ( evalStateT (parsedmaster prefs controlChan) (Map.empty, Map.empty, 0 :: Integer) )+ return (getParsedInformation controlChan, updateParsedInformation controlChan, invalidateCachedFile controlChan)++getParsedInformation :: Chan ParsedCacheQuery -> TopLevelType -> String -> ErrorT String IO (Maybe CacheEntry)+getParsedInformation cchan qtype name = do+ respchan <- liftIO newChan+ liftIO $ writeChan cchan $ GetParsedData qtype name respchan+ out <- liftIO $ readChan respchan+ case out of+ RCacheEntry x -> return $ Just x+ NoCacheEntry -> return Nothing+ CacheError x -> throwError x+ _ -> throwError "Unknown cache response type"++updateParsedInformation :: Chan ParsedCacheQuery -> TopLevelType -> String -> CacheEntry -> IO (ParsedCacheResponse)+updateParsedInformation pchannel qtype name centry = do+ respchan <- newChan+ writeChan pchannel $ UpdateParsedData qtype name centry respchan+ readChan respchan++invalidateCachedFile :: Chan ParsedCacheQuery -> String -> IO (ParsedCacheResponse)+invalidateCachedFile pchannel name = do+ respchan <- newChan+ writeChan pchannel $ InvalidateCacheFile name respchan+ readChan respchan++-- state : (parsed statements map, file association map, nbrequests)+parsedmaster :: Prefs -> Chan ParsedCacheQuery -> StateT + ( Map.Map (TopLevelType, String) CacheEntry+ , Map.Map FilePath (FileStatus, [(TopLevelType, String)])+ , Integer+ ) IO ()+parsedmaster prefs controlchan = do+ curmsg <- liftIO $ readChan controlchan+ case curmsg of+ GetStats respchan -> do+ (curmap, _, nbrequests) <- get+ liftIO $ writeChan respchan $ DaemonStats (Map.size curmap) nbrequests+ GetParsedData qtype name respchan -> do+ (curmap, _, _) <- get+ modify (\(mp, fm, rq) -> (mp, fm, rq + 1))+ case (Map.lookup (qtype, name) curmap) of+ Just x -> liftIO $ writeChan respchan (RCacheEntry x)+ Nothing -> liftIO $ writeChan respchan NoCacheEntry+ UpdateParsedData qtype name val@(_, filepath, filestatus, _) respchan -> do+ liftIO $ logDebug ("Updating parsed cache for " ++ show qtype ++ " " ++ name)+ (mp, fm, rq) <- get+ let + -- retrieve the current status+ curstatus = Map.lookup filepath fm+ fmclean = case curstatus of+ Just (cs,_) -> if extractFStatus cs /= extractFStatus filestatus+ then Map.delete filepath fm+ else fm+ _ -> fm+ addsnd (a1, b1) (_, b2) = (a1, b1 ++ b2)+ fileassocmap = Map.insertWith addsnd filepath (filestatus, [(qtype, name)]) fmclean+ statementmap = Map.insert (qtype, name) val mp+ put (statementmap, fileassocmap, rq+1)+ liftIO $ writeChan respchan CacheUpdated+ InvalidateCacheFile fname respchan -> do+ liftIO $ logDebug $ "Invalidating files for " ++ fname+ (mp, fm, rq) <- get+ let+ nfm = Map.delete fname fm+ nmp = case (Map.lookup fname fm) of+ Just (_, remlist) -> foldl' (\mp' el -> Map.delete el mp') mp remlist+ Nothing -> mp+ put (nmp, nfm, rq)+ liftIO $ writeChan respchan CacheUpdated+ parsedmaster prefs controlchan
+ Puppet/Init.hs view
@@ -0,0 +1,26 @@+{-| This is a helper module for the "Puppet.Daemon" module -}+module Puppet.Init where++import Puppet.Interpreter.Types+import qualified Data.Map as Map++data Prefs = Prefs {+ manifest :: FilePath, -- ^ The path to the manifests.+ modules :: FilePath, -- ^ The path to the modules.+ templates :: FilePath, -- ^ The path to the template.+ compilepoolsize :: Int, -- ^ Size of the compiler pool.+ parsepoolsize :: Int -- ^ Size of the parser pool.+} deriving (Show)++-- | Generates the 'Prefs' structure from a single path.+--+-- > genPrefs "/etc/puppet"+genPrefs :: String -> Prefs+genPrefs basedir = Prefs (basedir ++ "/manifests") (basedir ++ "/modules") (basedir ++ "/templates") 1 1++-- | Generates 'Facts' from pairs of strings.+--+-- > genFacts [("hostname","test.com")]+genFacts :: [(String,String)] -> Facts+genFacts = Map.fromList . concatMap (\(a,b) -> [(a, ResolvedString b), ("::" ++ a, ResolvedString b)])+
+ Puppet/Interpreter/Catalog.hs view
@@ -0,0 +1,859 @@+{-| This module exports the 'getCatalog' function, that computes catalogs from+parsed manifests. The behaviour of this module is probably non canonical on many+details. The problem is that most of Puppet behaviour is undocumented or+extremely vague. It might be possible to delve into the source code or to write+tests, but ruby is unreadable and tests are boring.++Here is a list of known discrepencies with Puppet :++* Variables coming from an inherited class can only be referenced using the+scope of the child class.++* Resources references using the <| |> syntax are not yet supported.+-}+module Puppet.Interpreter.Catalog (+ getCatalog+ ) where++import Puppet.DSL.Types+import Puppet.NativeTypes+import Puppet.NativeTypes.Helpers+import Puppet.Interpreter.Functions+import Puppet.Interpreter.Types++import Data.List+import Data.Char (isDigit)+import Data.Maybe (isJust, fromJust, catMaybes)+import Data.Either (lefts, rights, partitionEithers)+import Text.Parsec.Pos+import Control.Monad.State+import Control.Monad.Error+import qualified Data.Map as Map+import qualified Data.Set as Set++qualified [] = False+qualified str = case isPrefixOf "::" str of+ False -> qualified (tail str)+ True -> True++throwPosError msg = do+ p <- getPos+ throwError (msg ++ " at " ++ show p)++-- Int handling stuff+isInt :: String -> Bool+isInt = and . map isDigit+readint :: String -> CatalogMonad Integer+readint x = if (isInt x)+ then return (read x)+ else throwPosError $ "Expected an integer instead of '" ++ x++modifyScope f sc = sc { curScope = f $ curScope sc }+modifyVariables f sc = sc { curVariables = f $ curVariables sc }+modifyClasses f sc = sc { curClasses = f $ curClasses sc }+modifyDefaults f sc = sc { curDefaults = f $ curDefaults sc }+incrementResId sc = sc { curResId = (curResId sc) + 1 }+setStatePos npos sc = sc { curPos = npos }+emptyDefaults sc = sc { curDefaults = [] }+pushWarning t sc = sc { getWarnings = (getWarnings sc) ++ [t] }+pushCollect r sc = sc { curCollect = r : (curCollect sc) }+pushUnresRel r sc = sc { unresolvedRels = r : (unresolvedRels sc) }++getCatalog :: (TopLevelType -> String -> IO (Either String Statement))+ -- ^ The \"get statements\" function. Given a top level type and its name it+ -- should return the corresponding statement.+ -> (String -> String -> [(String, GeneralValue)] -> IO (Either String String))+ -- ^ The \"get template\" function. Given a file name, a scope name and a+ -- list of variables, it should return the computed template.+ -> String -- ^ Name of the node.+ -> Facts -- ^ Facts of this node.+ -> IO (Either String FinalCatalog, [String])+getCatalog getstatements gettemplate nodename facts = do+ let convertedfacts = Map.map+ (\fval -> (Right fval, initialPos "FACTS"))+ facts+ (output, finalstate) <- runStateT ( runErrorT ( computeCatalog getstatements nodename ) ) (ScopeState ["::"] convertedfacts Map.empty [] 1 (initialPos "dummy") Map.empty getstatements [] [] [] gettemplate)+ case output of+ Left x -> return (Left x, getWarnings finalstate)+ Right _ -> return (output, getWarnings finalstate)++computeCatalog :: (TopLevelType -> String -> IO (Either String Statement)) -> String -> CatalogMonad FinalCatalog+computeCatalog getstatements nodename = do+ nodestatements <- liftIO $ getstatements TopNode nodename+ case nodestatements of+ Left x -> throwError x+ Right nodestmts -> evaluateStatements nodestmts >>= finalResolution+++-- this validates the resolved resources+-- it should only be called with native types or the validatefunction lookup with abord with an error+finalizeResource :: CResource -> CatalogMonad (ResIdentifier, RResource)+finalizeResource (CResource cid cname ctype cparams _ cpos) = do+ setPos cpos+ rname <- resolveGeneralString cname+ rparams <- mapM (\(a,b) -> do { ra <- resolveGeneralString a; rb <- resolveGeneralValue b; return (ra,rb); }) cparams+ -- add collected relations+ -- TODO+ if Map.member ctype nativeTypes == False+ then throwPosError $ "Can't find native type " ++ ctype+ else return ()+ let mrrelations = []+ prefinalresource = RResource cid rname ctype (Map.fromList rparams) mrrelations cpos+ validatefunction = puppetvalidate (nativeTypes Map.! ctype)+ validated = validatefunction prefinalresource+ case validated of+ Left err -> throwError (err ++ " for resource " ++ ctype ++ "[" ++ rname ++ "] at " ++ show cpos)+ Right finalresource -> return $ ((ctype, rname), finalresource)++-- This checks if a resource is to be collected.+-- This returns a list as it can either return the original+-- resource, the resource with a "normal" virtuality, or both,+-- for exported resources (so that they can still be found as collected)+collectionChecks :: CResource -> CatalogMonad [CResource]+collectionChecks res = do+ if (crvirtuality res == Normal)+ then return [res]+ else do+ isCollected <- get >>= return . curCollect >>= mapM (\x -> x res)+ case (or isCollected, crvirtuality res) of+ (True, Exported) -> return [res { crvirtuality = Normal }, res]+ (True, _) -> return [res { crvirtuality = Normal } ]+ (False, _) -> return [res ]++finalResolution :: Catalog -> CatalogMonad FinalCatalog+finalResolution cat = do+ --liftIO $ putStrLn $ "FINAL RESOLUTION"+ collected <- mapM collectionChecks cat >>= mapM evaluateDefine . concat+ let (real, allvirtual) = partition (\x -> crvirtuality x == Normal) (concat collected)+ (_, exported) = partition (\x -> crvirtuality x == Virtual) allvirtual+ --export stuff+ --liftIO $ putStrLn "EXPORTED:"+ --liftIO $ mapM print exported+ resolved <- mapM finalizeResource real >>= createResourceMap+ --get >>= return . unresolvedRels >>= liftIO . (mapM print)+ return resolved++createResourceMap :: [(ResIdentifier, RResource)] -> CatalogMonad FinalCatalog+createResourceMap = foldM insertres Map.empty+ where+ insertres curmap (resid, res) = let+ oldres = Map.lookup resid curmap+ newmap = Map.insert resid res curmap+ in case (rrtype res, oldres) of+ ("class", _) -> return newmap+ (_, Just r ) -> throwError $ "Resource already defined:"+ ++ "\n\t" ++ (rrtype r) ++ "[" ++ (rrname r) ++ "] at " ++ show (rrpos r)+ ++ "\n\t" ++ (rrtype res) ++ "[" ++ (rrname res) ++ "] at " ++ show (rrpos res)+ (_, Nothing) -> return newmap++getstatement :: TopLevelType -> String -> CatalogMonad Statement+getstatement qtype name = do+ curcontext <- get+ let stmtsfunc = getStatementsFunction curcontext+ estatement <- liftIO $ stmtsfunc qtype name+ case estatement of+ Left x -> throwPosError x+ Right y -> return y++-- State alteration functions+pushScope name = modify (modifyScope (\x -> [name] ++ x))+pushDefaults name = modify (modifyDefaults (\x -> [name] ++ x))+popScope = modify (modifyScope tail)+getScope = do+ scope <- get >>= return . curScope+ if (null scope)+ then throwError "empty scope, shouldn't happen"+ else return $ head scope+addLoaded name position = modify (modifyClasses (Map.insert name position))+getNextId = do+ curscope <- get+ put $ incrementResId curscope+ return (curResId curscope)+setPos p = modify (setStatePos p)+getPos = get >>= return . curPos+putVariable k v = do+ curscope <- getScope+ let qual = qualified k+ kk | qual || (curscope == "::") = k+ | otherwise = "::" ++ k+ modify (modifyVariables (Map.insert (curscope ++ kk) v))+getVariable vname = get >>= return . Map.lookup vname . curVariables+addNestedTopLevel rtype rname rstatement = do+ curstate <- get+ let ctop = nestedtoplevels curstate+ curscope = head (curScope curstate)+ nname | curscope == "::" = rname+ | otherwise = curscope ++ "::" ++ rname+ nstatement = case rstatement of+ DefineDeclaration _ prms stms cpos -> DefineDeclaration nname prms stms cpos+ x -> x+ ntop = Map.insert (rtype, nname) nstatement ctop+ nstate = curstate { nestedtoplevels = ntop }+ put nstate+addWarning nwrn = modify (pushWarning nwrn)+addCollect ncol = modify (pushCollect ncol)+-- this pushes the relations only if they exist+-- the parameter is of the form+-- ( [dstrelations], srcresource, type, pos )+addUnresRel ncol@(rels, _, _, _) = do+ if null rels+ then return ()+ else modify (pushUnresRel ncol)++-- finds out if a resource name refers to a define+checkDefine :: String -> CatalogMonad (Maybe Statement)+checkDefine dname = if Map.member dname nativeTypes+ then return Nothing+ else do+ curstate <- get+ let ntop = nestedtoplevels curstate+ getsmts = getStatementsFunction curstate+ check = Map.lookup (TopDefine, dname) ntop+ case check of+ Just x -> return $ Just x+ Nothing -> do+ def1 <- liftIO $ getsmts TopDefine dname+ case def1 of+ Left err -> throwPosError ("Could not find the definition of " ++ dname ++ " err = " ++ err)+ Right s -> return $ Just s++{-+Partition parameters between those that are actual parameters and those that define relationships.++Those that define relationship must be properly resolved or hell will break loose. This is a BUG.+-}+partitionParamsRelations :: [(GeneralString, GeneralValue)] -> ([(GeneralString, GeneralValue)], [(LinkType, GeneralValue, GeneralValue)])+partitionParamsRelations rparameters = (realparams, relations)+ where realparams = filteredparams+ relations = concatMap convertrelation filteredrelations+ convertrelation :: (GeneralString, GeneralValue) -> [(LinkType, GeneralValue, GeneralValue)]+ convertrelation (_, Right ResolvedUndefined) = []+ convertrelation (reltype, Right (ResolvedArray rs)) = concatMap (\x -> convertrelation (reltype, Right x)) rs+ convertrelation (reltype, Right (ResolvedRReference rt rv)) = [(fromJust $ getRelationParameterType reltype, Right $ ResolvedString rt, Right rv)]+ convertrelation (reltype, Right (ResolvedString "undef")) = [(fromJust $ getRelationParameterType reltype, Right $ ResolvedString "undef", Right $ ResolvedString "undef")]+ convertrelation (_, Left x) = error ("partitionParamsRelations unresolved : " ++ show x)+ convertrelation x = error ("partitionParamsRelations error : " ++ show x)+ (filteredrelations, filteredparams) = partition (isJust . getRelationParameterType . fst) rparameters -- filters relations with actual parameters++-- TODO check whether parameters changed+checkLoaded name = do+ curscope <- get+ case (Map.lookup name (curClasses curscope)) of+ Nothing -> return False+ Just _ -> return True++-- apply default values to a resource+applyDefaults :: CResource -> CatalogMonad CResource+applyDefaults res = do+ defs <- get >>= return . curDefaults + foldM applyDefaults' res defs++applyDefaults' :: CResource -> Statement -> CatalogMonad CResource +applyDefaults' r@(CResource i rname rtype rparams rvirtuality rpos) (ResourceDefault dtype defs dpos) = do+ srname <- resolveGeneralString rname+ rdefs <- mapM (\(a,b) -> do { ra <- tryResolveExpressionString a; rb <- tryResolveExpression b; return (ra, rb); }) defs+ let (nparams, nrelations) = mergeParams rparams rdefs False + if (dtype == rtype)+ then do+ addUnresRel (nrelations, (rtype, Right srname), UDefault, dpos)+ return $ CResource i rname rtype nparams rvirtuality rpos+ else return r+applyDefaults' r@(CResource i rname rtype rparams rvirtuality rpos) (ResourceOverride dtype dname defs dpos) = do+ srname <- resolveGeneralString rname+ sdname <- resolveExpressionString dname+ rdefs <- mapM (\(a,b) -> do { ra <- tryResolveExpressionString a; rb <- tryResolveExpression b; return (ra, rb); }) defs+ let (nparams, nrelations) = mergeParams rparams rdefs True+ if ((dtype == rtype) && (srname == sdname))+ then do+ addUnresRel (nrelations, (rtype, Right srname), UDefault, dpos)+ return $ CResource i rname rtype nparams rvirtuality rpos+ else return r+applyDefaults' r d = throwError $ "Can't apply non default statement " ++ show d ++ " to resource " ++ show r++-- merge defaults and actual parameters depending on the override flag+mergeParams :: [(GeneralString, GeneralValue)] -> [(GeneralString, GeneralValue)] -> Bool -> ([(GeneralString, GeneralValue)], [(LinkType, GeneralValue, GeneralValue)])+mergeParams srcparams defs override = let+ (dstparams, dstrels) = partitionParamsRelations defs+ srcprm = Map.fromList srcparams+ dstprm = Map.fromList dstparams+ prm = if override+ then Map.toList $ Map.union dstprm srcprm+ else Map.toList $ Map.union srcprm dstprm+ in (prm, dstrels)++-- The actual meat++evaluateDefine :: CResource -> CatalogMonad [CResource]+evaluateDefine r@(CResource _ rname rtype rparams rvirtuality rpos) = do+ isdef <- checkDefine rtype+ case (rvirtuality, isdef) of+ (Normal, Just (DefineDeclaration dtype args dstmts dpos)) -> do+ --oldpos <- getPos+ setPos dpos+ pushScope $ "#DEFINE#" ++ dtype+ -- add variables+ mrrparams <- mapM (\(gs, gv) -> do { rgs <- resolveGeneralString gs; rgv <- tryResolveGeneralValue gv; return (rgs, (rgv, dpos)); }) rparams+ let expr = gs2gv rname+ mparams = Map.fromList mrrparams+ putVariable "title" (expr, rpos)+ putVariable "name" (expr, rpos)+ mapM (loadClassVariable rpos mparams) args+ + -- parse statements+ res <- mapM (evaluateStatements) dstmts+ nres <- handleDelayedActions (concat res)+ popScope+ return nres+ _ -> return [r]+ ++-- handling delayed actions (such as defaults)+handleDelayedActions :: Catalog -> CatalogMonad Catalog+handleDelayedActions res = do+ dres <- mapM applyDefaults res >>= mapM evaluateDefine >>= return . concat+ modify emptyDefaults+ return dres++-- node+evaluateStatements :: Statement -> CatalogMonad Catalog+evaluateStatements (Node _ stmts position) = do+ setPos position+ res <- mapM (evaluateStatements) stmts+ nres <- handleDelayedActions (concat res)+ return nres++-- include+evaluateStatements (Include includename position) = setPos position >> getstatement TopClass includename >>= evaluateStatements+evaluateStatements x@(ClassDeclaration _ _ _ _ _) = evaluateClass x Map.empty Nothing+evaluateStatements n@(DefineDeclaration dtype _ _ _) = do+ addNestedTopLevel TopDefine dtype n+ return []+evaluateStatements (ConditionalStatement exprs position) = do+ setPos position+ trues <- filterM (\(expr, _) -> resolveBoolean (Left expr)) exprs+ case trues of+ ((_,stmts):_) -> mapM evaluateStatements stmts >>= return . concat+ _ -> return []++evaluateStatements (Resource rtype rname parameters virtuality position) = do+ setPos position+ case rtype of+ -- checks whether we are handling a parametrized class+ "class" -> do+ rparameters <- mapM (\(a,b) -> do { pa <- resolveExpressionString a; pb <- tryResolveExpression b; return (pa, pb) } ) parameters+ classname <- resolveExpressionString rname+ topstatement <- getstatement TopClass classname+ let classparameters = Map.fromList $ map (\(pname, pvalue) -> (pname, (pvalue, position))) rparameters+ evaluateClass topstatement classparameters Nothing+ _ -> do+ resid <- getNextId+ rparameters <- mapM (\(a,b) -> do { pa <- tryResolveExpressionString a; pb <- tryResolveExpression b; return (pa, pb) } ) parameters+ srname <- tryResolveExpressionString rname+ let (realparams, relations) = partitionParamsRelations rparameters+ -- push all the relations+ addUnresRel (relations, (rtype, srname), UNormal, position)+ return [CResource resid srname rtype realparams virtuality position]++evaluateStatements x@(ResourceDefault _ _ _ ) = do+ pushDefaults x+ return []+evaluateStatements x@(ResourceOverride _ _ _ _) = do+ pushDefaults x+ return []+evaluateStatements (DependenceChain (srctype, srcname) (dsttype, dstname) position) = do+ setPos position+ gdstname <- tryResolveExpression dstname+ gsrcname <- tryResolveExpressionString srcname+ addUnresRel ( [(RRequire, Right $ ResolvedString dsttype, gdstname)], (srctype, gsrcname), UPlus, position )+ return []+-- <<| |>>+evaluateStatements (ResourceCollection rtype expr overrides position) = do+ setPos position+ if null overrides+ then return ()+ else throwPosError "Collection overrides not handled"+ func <- collectionFunction Exported rtype expr+ addCollect func+ return []+-- <| |>+evaluateStatements (VirtualResourceCollection rtype expr overrides position) = do+ setPos position+ if null overrides+ then return ()+ else throwPosError "Collection overrides not handled"+ func <- collectionFunction Virtual rtype expr+ addCollect func+ return []++evaluateStatements (VariableAssignment vname vexpr position) = do+ setPos position+ rvexpr <- tryResolveExpression vexpr+ putVariable vname (rvexpr, position)+ return []++evaluateStatements (MainFunctionCall fname fargs position) = do+ setPos position+ rargs <- mapM resolveExpression fargs+ executeFunction fname rargs++evaluateStatements (TopContainer toplevels curstatement) = do+ mapM (\(fname, stmt) -> evaluateClass stmt Map.empty (Just fname)) toplevels+ evaluateStatements curstatement++evaluateStatements x = throwError ("Can't evaluate " ++ (show x))++-- function used to load defines / class variables into the global context+loadClassVariable :: SourcePos -> Map.Map String (GeneralValue, SourcePos) -> (String, Maybe Expression) -> CatalogMonad ()+loadClassVariable position inputs (paramname, defvalue) = do+ let inputvalue = Map.lookup paramname inputs+ (v, vpos) <- case (inputvalue, defvalue) of+ (Just x , _ ) -> return x+ (Nothing, Just y ) -> return (Left y, position)+ (Nothing, Nothing) -> throwError $ "Must define parameter " ++ paramname ++ " at " ++ (show position)+ rv <- tryResolveGeneralValue v+ putVariable paramname (rv, vpos)+ return ()++-- class+-- ClassDeclaration String (Maybe String) [(String, Maybe Expression)] [Statement] SourcePos+-- nom, heritage, parametres, contenu+evaluateClass :: Statement -> Map.Map String (GeneralValue, SourcePos) -> Maybe String -> CatalogMonad Catalog+evaluateClass (ClassDeclaration classname inherits parameters statements position) inputparams actualname = do+ isloaded <- case actualname of+ Nothing -> checkLoaded classname+ Just x -> checkLoaded x+ if isloaded+ then return []+ else do+ resid <- getNextId -- get this resource id, for the dummy class that will be used to handle relations+ oldpos <- getPos -- saves where we were at class declaration so that we known were the class was included+ setPos position + pushScope classname -- sets the scope+ mapM (loadClassVariable position inputparams) parameters -- add variables for parametrized classes+ + -- load inherited classes+ inherited <- case inherits of+ Just parentclass -> do+ mystatement <- getstatement TopClass parentclass+ case mystatement of+ ClassDeclaration _ ni np ns no -> evaluateClass (ClassDeclaration classname ni np ns no) Map.empty (Just parentclass)+ _ -> throwError "Should not happen : TopClass return something else than a ClassDeclaration in evaluateClass"+ Nothing -> return []+ case actualname of+ Nothing -> addLoaded classname oldpos+ Just x -> addLoaded x oldpos++ -- parse statements+ res <- mapM (evaluateStatements) statements+ nres <- handleDelayedActions (concat res)+ mapM (addClassDependency classname) nres -- this adds a dummy dependency to this class+ -- for all resources that do not already depend on a class+ -- this is probably not puppet perfect with resources that+ -- depend explicitely on a class+ popScope+ return $+ [CResource resid (Right classname) "class" [] Normal position]+ ++ inherited+ ++ nres++evaluateClass (TopContainer topstmts myclass) inputparams actualname = do+ mapM (\(n,x) -> evaluateClass x Map.empty (Just n)) topstmts+ evaluateClass myclass inputparams actualname++evaluateClass x _ _ = throwError ("Someone managed to run evaluateClass against " ++ show x)++addClassDependency :: String -> CResource -> CatalogMonad ()+addClassDependency cname (CResource _ rname rtype _ _ position) = addUnresRel (+ [(RRequire, Right $ ResolvedString "class", Right $ ResolvedString cname)]+ , (rtype, rname)+ , UPlus, position)++tryResolveExpression :: Expression -> CatalogMonad GeneralValue+tryResolveExpression e = tryResolveGeneralValue (Left e)++tryResolveGeneralValue :: GeneralValue -> CatalogMonad GeneralValue+tryResolveGeneralValue n@(Right _) = return n+tryResolveGeneralValue (Left BTrue) = return $ Right $ ResolvedBool True+tryResolveGeneralValue (Left BFalse) = return $ Right $ ResolvedBool False+tryResolveGeneralValue (Left (Value x)) = tryResolveValue x+tryResolveGeneralValue n@(Left (ResolvedResourceReference _ _)) = return n+tryResolveGeneralValue (Left (Error x)) = throwPosError x+tryResolveGeneralValue (Left (ConditionalValue checkedvalue (Value (PuppetHash (Parameters hash))))) = do+ rcheck <- resolveExpression checkedvalue+ rhash <- mapM (\(vn, vv) -> do { rvn <- resolveExpression vn; return (rvn, vv) }) hash+ case (filter (\(a,_) -> (a == ResolvedString "default") || (compareRValues a rcheck)) rhash) of+ [] -> throwPosError ("No value could be selected when comparing to " ++ show rcheck)+ ((_,x):_) -> tryResolveExpression x+tryResolveGeneralValue n@(Left (EqualOperation a b)) = compareGeneralValue n a b [EQ]+tryResolveGeneralValue n@(Left (AboveEqualOperation a b)) = compareGeneralValue n a b [GT,EQ]+tryResolveGeneralValue n@(Left (AboveOperation a b)) = compareGeneralValue n a b [GT]+tryResolveGeneralValue n@(Left (UnderEqualOperation a b)) = compareGeneralValue n a b [LT,EQ]+tryResolveGeneralValue n@(Left (UnderOperation a b)) = compareGeneralValue n a b [LT]+tryResolveGeneralValue n@(Left (DifferentOperation a b)) = compareGeneralValue n a b [LT,GT]++tryResolveGeneralValue n@(Left (OrOperation a b)) = do+ ra <- tryResolveBoolean $ Left a+ rb <- tryResolveBoolean $ Left b+ case (ra, rb) of+ (Right (ResolvedBool rra), Right (ResolvedBool rrb)) -> return $ Right $ ResolvedBool $ rra || rrb+ _ -> return n+tryResolveGeneralValue n@(Left (AndOperation a b)) = do+ ra <- tryResolveBoolean $ Left a+ rb <- tryResolveBoolean $ Left b+ case (ra, rb) of+ (Right (ResolvedBool rra), Right (ResolvedBool rrb)) -> return $ Right $ ResolvedBool $ rra && rrb+ _ -> return n+tryResolveGeneralValue (Left (NotOperation x)) = do+ rx <- tryResolveBoolean $ Left x+ case rx of+ Right (ResolvedBool b) -> return $ Right $ ResolvedBool $ (not b)+ _ -> return rx+tryResolveGeneralValue (Left (LookupOperation a b)) = do+ ra <- tryResolveExpression a+ rb <- tryResolveExpressionString b+ case (ra, rb) of+ (Right (ResolvedArray ar), Right num) -> do+ bnum <- readint num+ let nnum = fromIntegral bnum+ if(length ar >= nnum)+ then throwPosError ("Invalid array index " ++ num)+ else return $ Right (ar !! nnum)+ (Right (ResolvedHash ar), Right idx) -> do+ let filtered = filter (\(x,_) -> x == idx) ar+ case filtered of+ [] -> throwError "TODO empty filtered"+ [(_,x)] -> return $ Right $ x+ x -> throwPosError ("Hum, WTF tryResolveGeneralValue " ++ show x)+ (_, Left y) -> throwPosError ("Could not resolve index " ++ show y)+ (Left x, _) -> throwPosError ("Could not resolve lookup " ++ show x)+ (Right x, _) -> throwPosError ("Could not resolve something that is not an array nor a hash, but " ++ show x)+tryResolveGeneralValue o@(Left (IsElementOperation b a)) = do+ ra <- tryResolveExpression a+ rb <- tryResolveExpressionString b+ case (ra, rb) of+ (Right (ResolvedArray ar), Right idx) -> do+ let filtered = filter (compareRValues (ResolvedString idx)) ar+ if null filtered+ then return $ Right $ ResolvedBool False+ else return $ Right $ ResolvedBool True+ _ -> return o+ +tryResolveGeneralValue e = throwPosError ("tryResolveGeneralValue not implemented for " ++ show e)++resolveGeneralValue :: GeneralValue -> CatalogMonad ResolvedValue+resolveGeneralValue e = do+ x <- tryResolveGeneralValue e+ case x of+ Left n -> throwPosError ("Could not resolveGeneralValue " ++ show n)+ Right p -> return p++tryResolveExpressionString :: Expression -> CatalogMonad GeneralString+tryResolveExpressionString s = do+ resolved <- tryResolveExpression s+ case resolved of+ Right e -> rstring e >>= return . Right+ Left e -> return $ Left e++rstring :: ResolvedValue -> CatalogMonad String+rstring resolved = case resolved of+ ResolvedString s -> return s+ ResolvedInt i -> return (show i)+ e -> do+ p <- getPos+ throwError ("'" ++ show e ++ "' will not resolve to a string at " ++ show p)++resolveExpression :: Expression -> CatalogMonad ResolvedValue+resolveExpression e = do+ resolved <- tryResolveExpression e+ case resolved of+ Right r -> return r+ Left x -> do+ p <- getPos+ throwError ("Can't resolve expression '" ++ show x ++ "' at " ++ show p ++ " was '" ++ show e ++ "'")++resolveExpressionString :: Expression -> CatalogMonad String+resolveExpressionString x = do+ resolved <- resolveExpression x+ case resolved of+ ResolvedString s -> return s+ ResolvedInt i -> return (show i)+ e -> do+ p <- getPos+ throwError ("Can't resolve expression '" ++ show e ++ "' to a string at " ++ show p)++tryResolveValue :: Value -> CatalogMonad GeneralValue+tryResolveValue (Literal x) = return $ Right $ ResolvedString x+tryResolveValue (Integer x) = return $ Right $ ResolvedInt x++tryResolveValue n@(ResourceReference rtype vals) = do+ rvals <- tryResolveExpression vals+ case rvals of+ Right resolved -> return $ Right $ ResolvedRReference rtype resolved+ _ -> return $ Left $ Value n++tryResolveValue (VariableReference vname) = do+ -- TODO check scopes !!!+ curscp <- getScope+ let varnames | qualified vname = [vname] ++ remtopscope vname -- scope is explicit+ | curscp == "::" = ["::" ++ vname] -- we are toplevel+ | otherwise = [curscp ++ "::" ++ vname, "::" ++ vname] -- check for local scope, then global+ remtopscope (':':':':xs) = [xs]+ remtopscope _ = []+ matching <- mapM getVariable varnames >>= return . catMaybes+ if null matching+ then do+ position <- getPos+ addWarning ("Could not resolveValue " ++ show varnames ++ " at " ++ show position)+ return $ Left $ Value $ VariableReference (head varnames)+ else return $ case (head matching) of+ (x,_) -> x++tryResolveValue n@(Interpolable x) = do+ resolved <- mapM tryResolveValueString x+ if (null $ lefts resolved)+ then return $ Right $ ResolvedString $ concat $ rights resolved+ else return $ Left $ Value n++tryResolveValue n@(PuppetHash (Parameters x)) = do+ resolvedKeys <- mapM (tryResolveExpressionString . fst) x+ resolvedValues <- mapM (tryResolveExpression . snd) x+ if ((null $ lefts resolvedKeys) && (null $ lefts resolvedValues))+ then return $ Right $ ResolvedHash $ zip (rights resolvedKeys) (rights resolvedValues)+ else return $ Left $ Value n++tryResolveValue n@(PuppetArray expressions) = do+ resolvedExpressions <- mapM tryResolveExpression expressions+ if (null $ lefts resolvedExpressions)+ then return $ Right $ ResolvedArray $ rights resolvedExpressions+ else return $ Left $ Value n++-- TODO+tryResolveValue (FunctionCall "fqdn_rand" args) = if (null args)+ then throwPosError "Empty argument list in fqdn_rand call"+ else do+ nargs <- mapM resolveExpressionString args+ curmax <- readint (head nargs)+ fqdn_rand curmax (tail nargs) >>= return . Right . ResolvedInt+tryResolveValue (FunctionCall "mysql_password" args) = if (length args /= 1)+ then throwPosError "mysql_password takes a single argument"+ else do+ es <- tryResolveExpressionString (head args)+ case es of+ Right s -> mysql_password s >>= return . Right . ResolvedString+ Left u -> return $ Left u+tryResolveValue (FunctionCall "jbossmem" _) = return $ Right $ ResolvedString "512"+tryResolveValue (FunctionCall "template" [name]) = do+ fname <- tryResolveExpressionString name+ case fname of+ Left x -> throwPosError $ "Can't resolve template path " ++ show x+ Right filename -> do+ vars <- get >>= mapM (\(varname, (varval, _)) -> do { rvarval <- tryResolveGeneralValue varval; return (varname, rvarval) }) . Map.toList . curVariables+ scp <- getScope+ templatefunc <- get >>= return . computeTemplateFunction+ out <- liftIO (templatefunc filename scp vars)+ case out of+ Right x -> return $ Right $ ResolvedString x+ Left err -> throwPosError err+tryResolveValue (FunctionCall "inline_template" _) = return $ Right $ ResolvedString "TODO"+tryResolveValue (FunctionCall "regsubst" [str, src, dst, flags]) = do+ rstr <- tryResolveExpressionString str+ rsrc <- tryResolveExpressionString src+ rdst <- tryResolveExpressionString dst+ rflags <- tryResolveExpressionString flags+ case (rstr, rsrc, rdst, rflags) of+ (Right sstr, Right ssrc, Right sdst, Right sflags) -> regsubst sstr ssrc sdst sflags >>= return . Right . ResolvedString+ x -> throwPosError ("Could not run regsubst because something here could not be resolved: " ++ show x)+tryResolveValue (FunctionCall "regsubst" [str, src, dst]) = tryResolveValue (FunctionCall "regsubst" [str, src, dst, Value $ Literal ""])+tryResolveValue (FunctionCall "regsubst" args) = throwPosError ("Bad argument count for regsubst " ++ show args)+ +tryResolveValue n@(FunctionCall "versioncmp" [a,b]) = do+ ra <- tryResolveExpressionString a+ rb <- tryResolveExpressionString b+ case (ra, rb) of+ (Right sa, Right sb) -> return $ Right $ ResolvedInt (versioncmp sa sb)+ _ -> return $ Left $ Value n+tryResolveValue n@(FunctionCall "file" filelist) = do+ -- resolving the list of file pathes+ rfilelist <- mapM tryResolveExpressionString filelist+ let (lf, rf) = partitionEithers rfilelist+ if null lf+ then do+ content <- liftIO $ file rf+ case content of+ Nothing -> do+ position <- getPos+ addWarning $ "Files " ++ show rf ++ " could not be found at " ++ show position+ return $ Right $ ResolvedString ""+ Just x -> return $ Right $ ResolvedString x+ else return $ Left $ Value n+ +tryResolveValue (FunctionCall fname _) = throwPosError ("FunctionCall " ++ fname ++ " not implemented")++tryResolveValue Undefined = return $ Right $ ResolvedUndefined+tryResolveValue (PuppetRegexp x) = return $ Right $ ResolvedRegexp x++tryResolveValue x = throwPosError ("tryResolveValue not implemented for " ++ show x)++tryResolveValueString :: Value -> CatalogMonad GeneralString+tryResolveValueString x = do+ r <- tryResolveValue x+ case r of+ Right (ResolvedString v) -> return $ Right v+ Right (ResolvedInt i) -> return $ Right (show i)+ Right v -> throwError ("Can't resolve valuestring for " ++ show v)+ Left v -> return $ Left v++getRelationParameterType :: GeneralString -> Maybe LinkType+getRelationParameterType (Right "require" ) = Just RRequire+getRelationParameterType (Right "notify" ) = Just RNotify+getRelationParameterType (Right "before" ) = Just RBefore+getRelationParameterType (Right "register") = Just RRegister+getRelationParameterType _ = Nothing++-- this function saves a new condition for collection+pushRealize :: ResolvedValue -> CatalogMonad ()+pushRealize (ResolvedRReference rtype (ResolvedString rname)) = do+ let myfunction :: CResource -> CatalogMonad Bool+ myfunction = (\(CResource _ mcrname mcrtype _ _ _) -> do+ srname <- resolveGeneralString mcrname+ return ((srname == rname) && (mcrtype == rtype))+ )+ addCollect myfunction+ return ()+pushRealize (ResolvedRReference _ x) = throwPosError (show x ++ " was not resolved to a string")+pushRealize x = throwPosError ("A reference was expected instead of " ++ show x)++executeFunction :: String -> [ResolvedValue] -> CatalogMonad Catalog+executeFunction "fail" [ResolvedString errmsg] = throwPosError ("Error: " ++ errmsg)+executeFunction "fail" args = throwPosError ("Error: " ++ show args)+executeFunction "realize" rlist = mapM pushRealize rlist >> return []+executeFunction "create_resources" [mrtype, rdefs] = do+ mrrtype <- case mrtype of+ ResolvedString x -> return x+ _ -> throwPosError $ "Resource type must be a string and not " ++ show mrtype+ arghash <- case rdefs of+ ResolvedHash x -> return x+ _ -> throwPosError $ "Resource definition must be a hash, and not " ++ show rdefs + position <- getPos+ let prestatements = map (\(rname, rargs) -> (Value $ Literal rname, resolved2expression rargs)) arghash+ resources <- mapM (\(resname, pval) -> do+ realargs <- case pval of+ Value (PuppetHash (Parameters h)) -> return h+ _ -> throwPosError "This should not happen, create_resources argument is not a hash"+ return $ Resource mrrtype resname realargs Normal position+ ) prestatements+ mapM evaluateStatements resources >>= return . concat+executeFunction "create_resources" x = throwPosError ("Bad arguments to create_resources: " ++ show x)+executeFunction a b = do+ position <- getPos+ addWarning $ "Function " ++ a ++ "(" ++ show b ++ ") not handled at " ++ show position+ return []++compareExpression :: Expression -> Expression -> CatalogMonad (Maybe Ordering)+compareExpression a b = do+ ra <- tryResolveExpression a+ rb <- tryResolveExpression b+ case (ra, rb) of+ (Right rra, Right rrb) -> return $ Just $ compareValues rra rrb+ _ -> return $ compareSemiResolved ra rb++compareSemiResolved :: GeneralValue -> GeneralValue -> Maybe Ordering+compareSemiResolved a@(Right _) b@(Left _) = compareSemiResolved b a+compareSemiResolved (Left (Value (VariableReference _))) (Left (Value (VariableReference _))) = Just EQ+compareSemiResolved (Left (Value (VariableReference _))) (Left (Value (Literal ""))) = Just EQ+compareSemiResolved (Left (Value (VariableReference _))) (Left (Value (Literal "false"))) = Just EQ+compareSemiResolved a b = Just (compare a b)++compareGeneralValue :: GeneralValue -> Expression -> Expression -> [Ordering] -> CatalogMonad GeneralValue+compareGeneralValue n a b acceptable = do+ cmp <- compareExpression a b+ case cmp of+ Nothing -> return n+ Just x -> return $ Right $ ResolvedBool (elem x acceptable)+compareValues :: ResolvedValue -> ResolvedValue -> Ordering+compareValues a@(ResolvedString _) b@(ResolvedInt _) = compareValues b a+compareValues (ResolvedInt a) (ResolvedString b) | isInt b = compare a (read b)+ | otherwise = LT+compareValues (ResolvedString a) (ResolvedRegexp b) = if (regmatch a b) then EQ else LT+compareValues x y = compare x y++compareRValues :: ResolvedValue -> ResolvedValue -> Bool+compareRValues a b = (compareValues a b) == EQ++-- used to handle the special cases when we know it is a boolean context+tryResolveBoolean :: GeneralValue -> CatalogMonad GeneralValue+tryResolveBoolean v = do+ rv <- tryResolveGeneralValue v+ case rv of+ Right (ResolvedString "") -> return $ Right $ ResolvedBool False+ Right (ResolvedString _) -> return $ Right $ ResolvedBool True+ Right (ResolvedInt 0) -> return $ Right $ ResolvedBool False+ Right (ResolvedInt _) -> return $ Right $ ResolvedBool True+ Right (ResolvedUndefined) -> return $ Right $ ResolvedBool False+ Left (Value (VariableReference _)) -> return $ Right $ ResolvedBool False+ Left (EqualOperation (Value (VariableReference _)) (Value (Literal ""))) -> return $ Right $ ResolvedBool True -- case where a variable was not resolved and compared to the empty string+ Left (EqualOperation (Value (VariableReference _)) (Value (Literal "true"))) -> return $ Right $ ResolvedBool False -- case where a variable was not resolved and compared to the string "true"+ Left (EqualOperation (Value (VariableReference _)) (Value (Literal "false"))) -> return $ Right $ ResolvedBool True -- case where a variable was not resolved and compared to the string "false"+ _ -> return rv+ +resolveBoolean :: GeneralValue -> CatalogMonad Bool+resolveBoolean v = do+ rv <- tryResolveBoolean v+ case rv of+ Right (ResolvedBool x) -> return x+ n -> throwPosError ("Could not resolve " ++ show n ++ "(was " ++ show rv ++ ") as a boolean")++resolveGeneralString :: GeneralString -> CatalogMonad String+resolveGeneralString (Right x) = return x+resolveGeneralString (Left y) = resolveExpressionString y++gs2gv :: GeneralString -> GeneralValue+gs2gv (Left e) = Left e+gs2gv (Right s) = Right $ ResolvedString s++collectionFunction :: Virtuality -> String -> Expression -> CatalogMonad (CResource -> CatalogMonad Bool)+collectionFunction virt mrtype exprs = do+ finalfunc <- case exprs of+ BTrue -> return (\_ -> return True)+ EqualOperation a b -> do+ ra <- resolveExpression a+ rb <- resolveExpression b+ paramname <- case ra of+ ResolvedString pname -> return pname+ _ -> throwPosError $ "We only support collection of the form 'parameter == value'" + defstatement <- checkDefine mrtype+ paramset <- case defstatement of+ Nothing -> case (Map.lookup mrtype nativeTypes) of+ Just (PuppetTypeMethods _ ps) -> return ps+ Nothing -> throwPosError $ "Unknown type " ++ mrtype ++ " when trying to collect"+ Just (DefineDeclaration _ params _ _) -> return $ Set.fromList $ map fst params+ Just x -> throwPosError $ "Expected a DefineDeclaration here instead of " ++ show x+ if (Set.notMember paramname paramset) && (paramname /= "tag")+ then throwPosError $ "Parameter " ++ paramname ++ " is not a valid parameter. It should be in : " ++ show (Set.toList paramset)+ else return ()+ return (\r -> do+ let param = filter (\x -> fst x == Right paramname) (crparams r)+ if length param == 0+ then return False+ else do+ cmp <- resolveGeneralValue $ snd (head param)+ return (cmp == rb)+ )+ x -> throwPosError $ "TODO : implement collection function for " ++ show x+ return (\res ->+ if ((crtype res == mrtype) && (crvirtuality res == virt))+ then finalfunc res+ else return False+ )+++resolved2expression :: ResolvedValue -> Expression+resolved2expression (ResolvedString str) = Value $ Literal str+resolved2expression (ResolvedInt i) = Value $ Integer i+resolved2expression (ResolvedBool True) = BTrue+resolved2expression (ResolvedBool False) = BFalse+resolved2expression (ResolvedRReference mrtype name) = Value $ ResourceReference mrtype (resolved2expression name)+resolved2expression (ResolvedArray vals) = Value $ PuppetArray $ map resolved2expression vals+resolved2expression (ResolvedHash hash) = Value $ PuppetHash $ Parameters $ map (\(s,v) -> (Value $ Literal s, resolved2expression v)) hash+resolved2expression (ResolvedUndefined) = Value $ Undefined+resolved2expression (ResolvedRegexp a) = Value $ PuppetRegexp a
+ Puppet/Interpreter/Functions.hs view
@@ -0,0 +1,65 @@+module Puppet.Interpreter.Functions + (fqdn_rand+ ,regsubst+ ,mysql_password+ ,regmatch+ ,versioncmp+ ,file+ ) where++import Data.Hash.MD5+import qualified Crypto.Hash.SHA1 as SHA1+import qualified Data.ByteString.Char8 as BS+import Data.String.Utils (join)+import Text.RegexPR+import Puppet.Interpreter.Types+import Control.Monad.Error+import System.IO+{-+TODO : achieve compatibility with puppet+the first String must be the fqdn+-}+fqdn_rand :: Integer -> [String] -> CatalogMonad Integer+fqdn_rand n args = return (hash `mod` n)+ where+ fullstring = Data.String.Utils.join ":" args+ hash = md5i $ Str fullstring++mysql_password :: String -> CatalogMonad String+mysql_password pwd = return $ '*':hash+ where+ hash = BS.unpack $ SHA1.hash (BS.pack pwd)++regsubst :: String -> String -> String -> String -> CatalogMonad String+regsubst str src dst flags = do+ let multiline = elem 'M' flags+ extended = elem 'E' flags+ insensitive = elem 'I' flags+ global = elem 'G' flags+ refunc | global = gsubRegexPR+ | otherwise = subRegexPR+ if multiline+ then throwError "Multiline flag not implemented"+ else return ()+ if extended+ then throwError "Extended flag not implemented"+ else return ()+ if insensitive+ then throwError "Case insensitive flag not implemented"+ else return ()+ return $ refunc src dst str++regmatch :: String -> String -> Bool+regmatch str reg = case matchRegexPR str reg of+ Just _ -> True+ Nothing -> False++-- TODO+versioncmp :: String -> String -> Integer+versioncmp a b | a > b = 1+ | a < b = -1+ | otherwise = 0++file :: [String] -> IO (Maybe String)+file [] = return Nothing+file (x:xs) = catch (withFile x ReadMode hGetContents >>= return . Just) (\_ -> file xs)
+ Puppet/Interpreter/Types.hs view
@@ -0,0 +1,131 @@+module Puppet.Interpreter.Types where++import Puppet.DSL.Types+import Text.Parsec.Pos+import Control.Monad.State+import Control.Monad.Error+import qualified Data.Map as Map++-- | This is the potentially unsolved list of resources in the catalog.+type Catalog =[CResource]+type Facts = Map.Map String ResolvedValue++-- | Relationship link type.+data LinkType = RNotify | RRequire | RBefore | RRegister deriving(Show, Ord, Eq)++-- | The list of resolved values that are used to define everything in a+-- 'FinalCatalog' and in the resolved parts of a 'Catalog'. They are to be+-- compared with the 'Value's.+data ResolvedValue+ = ResolvedString !String+ | ResolvedRegexp !String+ | ResolvedInt !Integer+ | ResolvedBool !Bool+ | ResolvedRReference !String !ResolvedValue+ | ResolvedArray ![ResolvedValue]+ | ResolvedHash ![(String, ResolvedValue)]+ | ResolvedUndefined+ deriving(Show, Eq, Ord)++-- | This type holds a value that is either from the ASL or fully resolved.+type GeneralValue = Either Expression ResolvedValue+-- | This type holds a value that is either from the ASL or a fully resolved+-- String.+type GeneralString = Either Expression String++{-| This describes the resources before the final resolution. This is required+as they must somehow be collected while the 'Statement's are interpreted, but+the necessary 'Expression's are not yet available. This is because in Puppet the+'Statement' order should not alter the catalog's content.++The relations are not stored here, as they are pushed into a separate internal+data structure by the interpreter.+-}+data CResource = CResource {+ crid :: Int, -- ^ Resource ID, used in the Puppet YAML.+ crname :: GeneralString, -- ^ Resource name.+ crtype :: String, -- ^ Resource type.+ crparams :: [(GeneralString, GeneralValue)], -- ^ Resource parameters.+ crvirtuality :: Virtuality, -- ^ Resource virtuality.+ pos :: SourcePos -- ^ Source code position of the resource definition.+ } deriving(Show)++-- | Resource identifier, made of a type, name pair.+type ResIdentifier = (String, String)++-- | Resource relation, made of a 'LinkType', 'ResIdentifier' pair.+type Relation = (LinkType, ResIdentifier)++{-| This is a fully resolved resource that will be used in the 'FinalCatalog'.+-}+data RResource = RResource {+ rrid :: !Int, -- ^ Resource ID.+ rrname :: !String, -- ^ Resource name.+ rrtype :: !String, -- ^ Resource type.+ rrparams :: !(Map.Map String ResolvedValue), -- ^ Resource parameters.+ rrelations :: ![Relation], -- ^ Resource relations.+ rrpos :: !SourcePos -- ^ Source code position of the resource definition.+ } deriving(Show, Ord, Eq)+ ++type FinalCatalog = Map.Map ResIdentifier RResource++type ScopeName = String++-- | Type of update\/override, so they can be applied in the correct order. This+-- part is probably not behaving like vanilla puppet, as it turns out this are+-- many fairly acceptable behaviours and the correct one is not documented.+data RelUpdateType = UNormal | UOverride | UDefault | UPlus deriving (Show, Ord, Eq)++{-| The most important data structure for the interpreter. It stores its+internal state.+-}+data ScopeState = ScopeState {+ curScope :: ![ScopeName],+ -- ^ The list of scopes. It works like a stack, and its initial value must+ -- be @[\"::\"]@+ curVariables :: !(Map.Map String (GeneralValue, SourcePos)),+ -- ^ The list of known variables. It should be noted that the interpreter+ -- tries to resolve them as soon as it can, so that it can store their+ -- current scope.+ curClasses :: !(Map.Map String SourcePos),+ -- ^ The list of classes that have already been included, along with the+ -- place where this happened.+ curDefaults :: ![Statement],+ -- ^ List of defaults to apply. All defaults are applied at the end of the+ -- interpretation of each top level statement.+ curResId :: !Int, -- ^ Stores the value of the current 'crid'.+ curPos :: !SourcePos,+ -- ^ Current position of the evaluated statement. This is mostly used to+ -- give useful error messages.+ nestedtoplevels :: !(Map.Map (TopLevelType, String) Statement),+ -- ^ List of \"top levels\" that have been parsed inside another top level.+ -- Their behaviour is curently non canonical as the scoping rules are+ -- unclear.+ getStatementsFunction :: TopLevelType -> String -> IO (Either String Statement),+ -- ^ This is a function that, given the type of a top level statement and+ -- its name, should return it.+ getWarnings :: ![String], -- ^ List of warnings.+ curCollect :: ![CResource -> CatalogMonad Bool],+ -- ^ A bit complicated, this stores the collection functions. These are+ -- functions that determine whether a resource should be collected or not.+ unresolvedRels :: ![([(LinkType, GeneralValue, GeneralValue)], (String, GeneralString), RelUpdateType, SourcePos)],+ -- ^ This stores unresolved relationships, because the original string name+ -- can't be resolved. Fieds are [ ( [dstrelations], srcresource, type, pos ) ]+ computeTemplateFunction :: String -> String -> [(String, GeneralValue)] -> IO (Either String String)+ -- ^ Function that takes a filename, the current scope and a list of+ -- variables. It returns an error or the computed template.+}++-- | The monad all the interpreter lives in. It is 'ErrorT' with a state.+type CatalogMonad = ErrorT String (StateT ScopeState IO)++generalizeValueE :: Expression -> GeneralValue+generalizeValueE e = Left e+generalizeValueR :: ResolvedValue -> GeneralValue+generalizeValueR e = Right e+generalizeStringE :: Expression -> GeneralString+generalizeStringE s = Left s+generalizeStringS :: String -> GeneralString+generalizeStringS s = Right s+
+ Puppet/NativeTypes.hs view
@@ -0,0 +1,14 @@+{-| This module holds the /native/ Puppet resource types. -}+module Puppet.NativeTypes (nativeTypes) where++import Puppet.NativeTypes.Helpers+import Puppet.NativeTypes.File+import qualified Data.Map as Map++fakeTypes = map faketype ["class", "ssh_authorized_key_secure"]++defaultTypes = map defaulttype ["augeas","computer","cron","exec","filebucket","group","host","interface","k5login","macauthorization","mailalias","maillist","mcx","mount","nagios_command","nagios_contact","nagios_contactgroup","nagios_host","nagios_hostdependency","nagios_hostescalation","nagios_hostextinfo","nagios_hostgroup","nagios_service","nagios_servicedependency","nagios_serviceescalation","nagios_serviceextinfo","nagios_servicegroup","nagios_timeperiod","notify","package","resources","router","schedule","scheduledtask","selboolean","selmodule","service","sshauthorizedkey","sshkey","stage","tidy","user","vlan","yumrepo","zfs","zone","zpool","mysql_database","mysql_user","mysql_grant"]++-- | The map of native types. They are described in "Puppet.NativeTypes.Helpers".+nativeTypes :: Map.Map PuppetTypeName (PuppetTypeMethods)+nativeTypes = Map.fromList (fakeTypes ++ defaultTypes ++ nativeFile)
+ Puppet/NativeTypes/File.hs view
@@ -0,0 +1,46 @@+module Puppet.NativeTypes.File (nativeFile) where++import Puppet.NativeTypes.Helpers+import Control.Monad.Error+import Puppet.Interpreter.Types+import qualified Data.Map as Map+import qualified Data.Set as Set++nativeFile = [("file", PuppetTypeMethods validateFile parameterset)]++-- Autorequires: If Puppet is managing the user or group that owns a file, the file resource will autorequire them. If Puppet is managing any parent directories of a file, the file resource will autorequire them.+parameterset = Set.fromList $ map fst parameterfunctions+parameterfunctions = + [("backup" , [string])+ ,("checksum" , [values ["md5", "md5lite", "mtime", "ctime", "none"]])+ ,("content" , [string])+ ,("ensure" , [defaultvalue "present", string])+ ,("force" , [string, values ["true","false"]])+ ,("group" , [defaultvalue "root", string])+ ,("ignore" , [string])+ ,("links" , [string])+ ,("mode" , [integer])+ ,("owner" , [string])+ ,("path" , [string])+ ,("provider" , [values ["posix","windows"]])+ ,("purge" , [string, values ["true","false"]])+ ,("recurse" , [string, values ["inf","true","false","remote"]])+ ,("recurselimit", [integer])+ ,("replace" , [string, values ["true","false"]])+ ,("sourceselect", [values ["first","all"]])+ ,("target" , [string])+ ,("source" , [])+ ]++validateFile :: PuppetTypeValidate+validateFile = defaultValidate parameterset >=> parameterFunctions parameterfunctions >=> validateSourceOrContent+++validateSourceOrContent :: PuppetTypeValidate+validateSourceOrContent res = let+ parammap = rrparams res+ source = Map.member "source" parammap+ content = Map.member "content" parammap+ in if (source && content)+ then Left "Source and content can't be specified at the same time"+ else Right res
+ Puppet/NativeTypes/Helpers.hs view
@@ -0,0 +1,101 @@+{-| These are the function and data types that are used to define the Puppet+native types.+-}+module Puppet.NativeTypes.Helpers where++import Puppet.Interpreter.Types+import qualified Data.Map as Map+import qualified Data.Set as Set+import Data.Char (isDigit)+import Control.Monad++type PuppetTypeName = String+-- |This is a function type than can be bound. It is the type of all subsequent+-- validators.+type PuppetTypeValidate = RResource -> Either String RResource+data PuppetTypeMethods = PuppetTypeMethods {+ puppetvalidate :: PuppetTypeValidate,+ puppetfields :: Set.Set String+ }++faketype :: PuppetTypeName -> (PuppetTypeName, PuppetTypeMethods)+faketype tname = (tname, PuppetTypeMethods (\x -> Right x) Set.empty)++defaulttype :: PuppetTypeName -> (PuppetTypeName, PuppetTypeMethods)+defaulttype tname = (tname, PuppetTypeMethods (defaultValidate Set.empty) Set.empty)++{-| This helper will validate resources given a list of fields. It will run+'checkParameterList' and then 'addDefaults'. -}+defaultValidate :: Set.Set String -> PuppetTypeValidate+defaultValidate validparameters = checkParameterList validparameters >=> addDefaults++-- | This validator checks that no unknown parameters have been set (except tag)+checkParameterList :: Set.Set String -> PuppetTypeValidate+checkParameterList validparameters res | Set.null validparameters = Right res+ | otherwise = if Set.null setdiff+ then Right res+ else Left $ "Unknown parameters " ++ (show $ Set.toList setdiff)+ where+ keyset = Map.keysSet (rrparams res)+ setdiff = Set.difference keyset (Set.insert "tag" validparameters)++-- | This validator always accept the resources, but add the default parameters+-- (such as title and name).+addDefaults :: PuppetTypeValidate+addDefaults res = Right (res { rrparams = newparams } )+ where+ newparams = Map.filter (/= ResolvedUndefined) $ Map.union defaults (rrparams res) + defaults = Map.fromList [("name", nm),("title", nm)]+ nm = ResolvedString $ rrname res++{-| This checks that a given parameter is a string. If it is a 'ResolvedInt' or+'ResolvedBool' it will convert them to strings.+-}+string :: String -> PuppetTypeValidate+string param res = case (Map.lookup param (rrparams res)) of+ Just (ResolvedString _) -> Right res+ Just (ResolvedInt n) -> Right (insertparam res param (ResolvedString $ show n))+ Just (ResolvedBool True) -> Right (insertparam res param (ResolvedString "true"))+ Just (ResolvedBool False) -> Right (insertparam res param (ResolvedString "false"))+ Just x -> Left $ "Parameter " ++ param ++ " should be a string, and not " ++ show x+ Nothing -> Right res++-- | Makes sure that the parameter, if defined, has a value among this list.+values :: [String] -> String -> PuppetTypeValidate+values valuelist param res = case (Map.lookup param (rrparams res)) of+ Just (ResolvedString x) -> if (elem x valuelist)+ then Right res+ else Left $ "Parameter " ++ param ++ " value should be one of " ++ show valuelist+ Just _ -> Left $ "Parameter " ++ param ++ " value should be one of " ++ show valuelist+ Nothing -> Right res++-- | This fills the default values of unset parameters.+defaultvalue :: String -> String -> PuppetTypeValidate+defaultvalue value param res = case (Map.lookup param (rrparams res)) of+ Just _ -> Right res+ Nothing -> Right $ insertparam res param (ResolvedString value)++insertparam :: RResource -> String -> ResolvedValue -> RResource+insertparam res param value = res { rrparams = Map.insert param value (rrparams res) }++-- | Checks that a given parameter, if set, is a 'ResolvedInt'. If it is a+-- 'ResolvedString' it will attempt to parse it.+integer :: String -> PuppetTypeValidate+integer prm res = string prm res >>= integer' prm+ where+ integer' pr rs = case (Map.lookup pr (rrparams rs)) of+ Nothing -> Right rs+ Just (ResolvedString x) -> if (all isDigit x)+ then Right $ insertparam rs pr (ResolvedInt $ read x)+ else Left $ "Parameter " ++ pr ++ " should be a number"+ Just (ResolvedInt _) -> Right rs+ _ -> Left $ "Parameter " ++ pr ++ " must be an integer"++-- | Helper that takes a list of stuff and will generate a validator.+parameterFunctions :: [(String, [String -> PuppetTypeValidate])] -> PuppetTypeValidate+parameterFunctions argrules rs = foldM parameterFunctions' rs argrules+ where+ parameterFunctions' :: RResource -> (String, [String -> PuppetTypeValidate]) -> Either String RResource+ parameterFunctions' r (param, validationfunctions) = foldM (parameterFunctions'' param) r validationfunctions+ parameterFunctions'' :: String -> RResource -> (String -> PuppetTypeValidate) -> Either String RResource+ parameterFunctions'' param r validationfunction = validationfunction param r
+ Puppet/Printers.hs view
@@ -0,0 +1,50 @@+module Puppet.Printers (+ showRes+ , showRRes+ , showFCatalog+) where++import Puppet.Interpreter.Types+import qualified Data.Map as Map+import Data.List++showRes (CResource _ rname rtype params virtuality _) = putStrLn $ rtype ++ " " ++ show rname ++ " " ++ show params ++ " " ++ show virtuality+showRRes (RResource _ rname rtype params relations _) = putStrLn $ rtype ++ " " ++ show rname ++ " " ++ show params ++ " " ++ show relations++showFCatalog :: FinalCatalog -> String+showFCatalog rmap = let+ rawlist = groupBy (\((rtype1,_), _) ((rtype2,_), _) -> rtype1 == rtype2) (sort $ Map.toList rmap)+ rlist = map (map snd) rawlist+ out = concatMap showuniqueres rlist+ in out++-- helpers++commasep :: [String] -> String+commasep = intercalate ", " +commaretsep :: [String] -> String+commaretsep = intercalate ",\n" ++showValue :: ResolvedValue -> String+showValue (ResolvedString x) = show x+showValue (ResolvedInt x) = show x+showValue (ResolvedBool True) = "true"+showValue (ResolvedBool False) = "false"+showValue (ResolvedRReference rt rn) = rt ++ "[" ++ showValue rn ++ "]"+showValue (ResolvedArray ar) = "[" ++ commasep (map showValue ar) ++ "]"+showValue (ResolvedHash h) = "{" ++ commasep (map (\(k,v) -> k ++ " => " ++ showValue v) h) ++ "}"+showValue (ResolvedUndefined) = "undef"++showuniqueres :: [RResource] -> String+showuniqueres res = mrtype ++ " {\n" ++ concatMap showrres res ++ "}\n"+ where+ showrres (RResource _ rname _ params rels mpos) =+ " " ++ show rname ++ ":" ++ " #" ++ show mpos ++ "\n"+ ++ commaretsep (map showparams (Map.toList params))+ ++ commareqs ((null rels) || (Map.null params))+ ++ commaretsep (map showrequire (sort rels)) ++ ";\n"+ commareqs c | c = ""+ | otherwise = ",\n"+ showparams (name, val) = " " ++ name ++ " => " ++ showValue val+ showrequire (ltype, dst) = " " ++ show ltype ++ " " ++ show dst+ mrtype = rrtype (head res)
+ SafeProcess.hs view
@@ -0,0 +1,68 @@+-- from http://stackoverflow.com/questions/8820903/haskell-how-to-timeout-a-function-that-runs-an-external-command++module SafeProcess where++import Control.Concurrent+import Control.Exception+import System.Exit+import System.IO+import System.Timeout+import System.Posix.Signals+import System.Process+import System.Process.Internals++safeReadProcessTimeout :: String -> [String] -> String -> Int -> IO (Maybe (Either String String))+safeReadProcessTimeout prog args input tout = timeout (tout*1000) $ safeReadProcess prog args input++safeCreateProcess :: String -> [String] -> StdStream -> StdStream -> StdStream+ -> ( ( Maybe Handle+ , Maybe Handle+ , Maybe Handle+ , ProcessHandle+ ) -> IO a )+ -> IO a+safeCreateProcess prog args streamIn streamOut streamErr fun = bracket+ ( do+ h <- createProcess (proc prog args) + { std_in = streamIn+ , std_out = streamOut+ , std_err = streamErr+ , create_group = True }+ return h+ )+-- "interruptProcessGroupOf" is in the new System.Process. Since some+-- programs return funny exit codes i implemented a "terminateProcessGroupOf".+-- (\(_, _, _, ph) -> interruptProcessGroupOf ph >> waitForProcess ph)+ (\(_, _, _, ph) -> terminateProcessGroup ph >> waitForProcess ph)+ fun+{-# NOINLINE safeCreateProcess #-}++safeReadProcess :: String -> [String] -> String -> IO (Either String String)+safeReadProcess prog args str =+ safeCreateProcess prog args CreatePipe CreatePipe Inherit+ (\(Just inh, Just outh, _, ph) -> do+ hSetBinaryMode inh True+ hSetBinaryMode outh True+ hPutStr inh str+ hClose inh+ -- fork a thread to consume output+ output <- hGetContents outh+ outMVar <- newEmptyMVar+ forkIO $ evaluate (length output) >> putMVar outMVar ()+ -- wait on output+ takeMVar outMVar+ hClose outh+ ex <- waitForProcess ph+ case ex of+ ExitSuccess -> return $ Right output+ ExitFailure r -> return $ Left $ prog ++ " " ++ show args ++ " failed, errorcode = " ++ show r+ )++terminateProcessGroup :: ProcessHandle -> IO ()+terminateProcessGroup ph = do+ let (ProcessHandle pmvar) = ph+ ph_ <- readMVar pmvar+ case ph_ of+ OpenHandle pid -> do -- pid is a POSIX pid+ signalProcessGroup 15 pid+ _ -> return ()
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ bench/lexer.hs view
@@ -0,0 +1,4 @@+module Main where++main :: IO ()+main = do print "cool"
+ language-puppet.cabal view
@@ -0,0 +1,93 @@+-- language-puppet.cabal auto-generated by cabal init. For additional+-- options, see+-- http://www.haskell.org/cabal/release/cabal-latest/doc/users-guide/authors.html#pkg-descr.+-- The name of the package.+Name: language-puppet++-- The package version. See the Haskell package versioning policy+-- (http://www.haskell.org/haskellwiki/Package_versioning_policy) for+-- standards guiding when and how versions should be incremented.+Version: 0.1.3++-- A short (one-line) description of the package.+Synopsis: Tools to parse and evaluate the Puppet DSL.++-- A longer description of the package.+Description: This is a set of libraries designed to work with the Puppet DSL. It can be used to parse .pp files, compile and interpret them, evaluate the templates. It is still very experimental but is already pretty useful when working with the manifests.++-- The license under which the package is released.+License: GPL-3++-- The file containing the license text.+License-file: LICENSE++-- The package author(s).+Author: Simon Marechal++-- An email address to which users can send suggestions, bug reports,+-- and patches.+Maintainer: bartavelle@gmail.com++-- A copyright notice.+-- Copyright: ++Category: Language++Build-type: Simple++-- Extra files to be distributed with the package, such as examples or+-- a README.+-- Extra-source-files: ++-- Constraint on the version of Cabal needed to build this package.+Cabal-version: >=1.8++Data-Files:+ ruby/calcerb.rb+++Library+ ghc-options: -Wall -fno-warn-missing-signatures -fno-warn-unused-do-bind -funbox-strict-fields+ -- Modules exported by the library.+ Exposed-modules: Puppet.DSL.Parser, Puppet.DSL.Printer, Puppet.Daemon, Puppet.Init, Puppet.DSL.Loader, Puppet.Printers, Puppet.NativeTypes, Puppet.DSL.Types,+ Puppet.Interpreter.Types, Puppet.Interpreter.Catalog, Puppet.NativeTypes.Helpers+ + -- Packages needed in order to build this package.+ Build-depends: base >=3 && <5,parsec,MissingH,containers,pretty,mtl,unix,hslogger,filepath,Glob,regexpr,process,bytestring,cryptohash+ + -- Modules not exported by this package.+ Other-modules: Puppet.Interpreter.Functions, Puppet.NativeTypes.File, Erb.Compute, SafeProcess, Paths_language_puppet, Erb.Parser, Erb.Ruby+ + -- Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.+ -- Build-tools: ++ GHC-Prof-Options: -auto-all+ +Test-Suite test-lexer+ hs-source-dirs: test+ type: exitcode-stdio-1.0+ ghc-options: -Wall+ build-depends: language-puppet,base,Glob,mtl+ main-is: lexer.hs+Test-Suite test-expr+ hs-source-dirs: test+ type: exitcode-stdio-1.0+ ghc-options: -Wall+ build-depends: language-puppet,base,parsec+ main-is: expr.hs+Test-Suite test-interpreter+ hs-source-dirs: test+ type: exitcode-stdio-1.0+ ghc-options: -Wall+ build-depends: language-puppet,base,Glob,mtl,containers,parsec+ main-is: interpreter.hs++++benchmark bench-lexer+ hs-source-dirs: bench+ type: exitcode-stdio-1.0+ ghc-options: -Wall+ build-depends: language-puppet,base+ main-is: lexer.hs+
+ ruby/calcerb.rb view
@@ -0,0 +1,56 @@+require 'erb'+require 'digest/md5'++class Scope+ def initialize(scpv, ctx)+ @mvars = eval(scpv)+ @context = ctx+ end++ def lookupvar(name)+ if has_variable?(name)+ @mvars[name]+ elsif has_variable?("::" + name)+ @mvars["::" + name]+ elsif has_variable?(@context + "::" + name)+ @mvars[@context + "::" + name]+ else+ :undef+ end+ end++ def has_variable?(name)+ @mvars.include?(name)+ end+end++class ErbBinding+ def initialize(scp, ctx)+ @scope = Scope.new(scp, ctx)+ end+ def get_binding+ return binding()+ end+ def has_variable?(name)+ @scope.has_variable?(name.to_s)+ end+ def method_missing(sname)+ name = sname.to_s+ if name == 'scope'+ @scope+ else+ @scope.lookupvar(name)+ end+ end+end++context = $stdin.readline.chomp!+templatefile = $stdin.readline.chomp!+varscope = $stdin.read+content = IO.read(templatefile)++nerb = ERB.new(content, nil, "-")+binding = ErbBinding.new(varscope, context).get_binding++out = nerb.result(binding)+puts out
+ test/expr.hs view
@@ -0,0 +1,22 @@+module Main where++import Puppet.DSL.Parser+import Puppet.DSL.Types+import Text.Parsec++testcases = + [ ("5 + 3 * 2", PlusOperation (Value $ Integer 5) (MultiplyOperation (Value $ Integer 3) (Value $ Integer 2)) )+ , ("5+2 == 7", EqualOperation ( PlusOperation (Value $ Integer 5) (Value $ Integer 2) ) (Value $ Integer 7) )+ ]++main :: IO ()+main = do+ let testres = map (\(t,v) -> (runParser exprparser () "test" t, v)) testcases+ badstuff = filter (\(Right r,t) -> r /= t) testres+ if (null badstuff)+ then return ()+ else do+ print badstuff+ error "fail"++
+ test/interpreter.hs view
@@ -0,0 +1,52 @@+module Main where++import System.FilePath.Glob+import Control.Monad.Error+import Puppet.DSL.Loader+import Puppet.DSL.Types+import Puppet.Interpreter.Catalog+import Puppet.Interpreter.Types+import qualified Data.Map as Map+import Data.Either+import Data.List+import Text.Parsec.Pos++getstatement :: Map.Map (TopLevelType, String) Statement -> TopLevelType -> String -> IO (Either String Statement)+getstatement stmtlist toplevel name = case (Map.lookup (toplevel, name) stmtlist) of+ Just x -> return $ Right x+ Nothing -> return $ Left "not found"++gettemplate :: String -> String -> c -> IO (Either String String)+gettemplate n _ _ = return $ Right n++main :: IO ()+main = do+ filelist <- globDir [compile "*.pp"] "test/interpreter" >>= return . head . fst+ testres <- mapM testinterpreter filelist+ let testsrs = map fst testres+ isgood = and $ map snd testres+ outlist = zip [1..(length testres)] testsrs+ mapM_ (\(n,t) -> putStrLn $ show n ++ " " ++ t) outlist+ if (isgood)+ then return ()+ else error "fail"++testinterpreter :: FilePath -> IO (String, Bool)+testinterpreter fp = do+ parsed <- runErrorT (parseFile fp)+ case parsed of+ Left err -> return (err, False)+ Right p -> do+ let facts = Map.fromList [("hostname",ResolvedString "test")]+ toplevels = map convertTopLevel p+ oktoplevels = rights toplevels+ othertoplevels = lefts toplevels+ topclass = ClassDeclaration "::" Nothing [] othertoplevels (initialPos fp)+ stmtpmap :: Map.Map (TopLevelType, String) Statement+ stmtpmap = foldl' (\mp (ttype,tname,ts) -> Map.insert (ttype,tname) (TopContainer [(fp, topclass)] ts) mp) Map.empty oktoplevels+ ctlg <- getCatalog (getstatement stmtpmap) gettemplate "test" facts+ print ctlg+ case ctlg of+ (Right _, _) -> return ("PASS", True)+ (Left x, y) -> error x+
+ test/lexer.hs view
@@ -0,0 +1,26 @@+module Main where++import System.FilePath.Glob+import Control.Monad.Error+import Puppet.DSL.Loader++main :: IO ()+main = do+ filelist <- globDir [compile "*.pp"] "test/lexer" >>= return . head . fst+ testres <- mapM testparser filelist+ let testsrs = map fst testres+ isgood = and $ map snd testres+ outlist = zip [1..(length testres)] testsrs+ mapM_ (\(n,t) -> putStrLn $ show n ++ " " ++ t) outlist+ if (isgood)+ then return ()+ else error "fail"++-- returns errors+testparser :: FilePath -> IO (String, Bool)+testparser fp = do+ parsed <- runErrorT (parseFile fp)+ case parsed of+ Right _ -> return ("PASS", True)+ Left err -> return (err, False)+