Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / Utils.hs @ ebf38064

History | View | Annotate | Download (7.1 kB)

1
{-| Utility functions. -}
2

    
3
{-
4

    
5
Copyright (C) 2009, 2010, 2011 Google Inc.
6

    
7
This program is free software; you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation; either version 2 of the License, or
10
(at your option) any later version.
11

    
12
This program is distributed in the hope that it will be useful, but
13
WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
General Public License for more details.
16

    
17
You should have received a copy of the GNU General Public License
18
along with this program; if not, write to the Free Software
19
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20
02110-1301, USA.
21

    
22
-}
23

    
24
module Ganeti.HTools.Utils
25
  ( debug
26
  , debugFn
27
  , debugXy
28
  , sepSplit
29
  , stdDev
30
  , if'
31
  , select
32
  , applyIf
33
  , commaJoin
34
  , readEitherString
35
  , JSRecord
36
  , loadJSArray
37
  , fromObj
38
  , fromObjWithDefault
39
  , maybeFromObj
40
  , tryFromObj
41
  , fromJVal
42
  , asJSObject
43
  , asObjectList
44
  , fromJResult
45
  , tryRead
46
  , formatTable
47
  , annotateResult
48
  , defaultGroupID
49
  , parseUnit
50
  ) where
51

    
52
import Data.Char (toUpper)
53
import Data.List
54
import qualified Text.JSON as J
55

    
56
import Debug.Trace
57

    
58
import Ganeti.HTools.Types
59
-- we will re-export these for our existing users
60
import Ganeti.HTools.JSON
61

    
62
-- * Debug functions
63

    
64
-- | To be used only for debugging, breaks referential integrity.
65
debug :: Show a => a -> a
66
debug x = trace (show x) x
67

    
68
-- | Displays a modified form of the second parameter before returning
69
-- it.
70
debugFn :: Show b => (a -> b) -> a -> a
71
debugFn fn x = debug (fn x) `seq` x
72

    
73
-- | Show the first parameter before returning the second one.
74
debugXy :: Show a => a -> b -> b
75
debugXy = seq . debug
76

    
77
-- * Miscellaneous
78

    
79
-- | Apply the function if condition holds, otherwise use default value.
80
applyIf :: Bool -> (a -> a) -> a -> a
81
applyIf b f x = if b then f x else x
82

    
83
-- | Comma-join a string list.
84
commaJoin :: [String] -> String
85
commaJoin = intercalate ","
86

    
87
-- | Split a list on a separator and return an array.
88
sepSplit :: Eq a => a -> [a] -> [[a]]
89
sepSplit sep s
90
  | null s    = []
91
  | null xs   = [x]
92
  | null ys   = [x,[]]
93
  | otherwise = x:sepSplit sep ys
94
  where (x, xs) = break (== sep) s
95
        ys = drop 1 xs
96

    
97
-- * Mathematical functions
98

    
99
-- Simple and slow statistical functions, please replace with better
100
-- versions
101

    
102
-- | Standard deviation function.
103
stdDev :: [Double] -> Double
104
stdDev lst =
105
  -- first, calculate the list length and sum lst in a single step,
106
  -- for performance reasons
107
  let (ll', sx) = foldl' (\(rl, rs) e ->
108
                           let rl' = rl + 1
109
                               rs' = rs + e
110
                           in rl' `seq` rs' `seq` (rl', rs')) (0::Int, 0) lst
111
      ll = fromIntegral ll'::Double
112
      mv = sx / ll
113
      av = foldl' (\accu em -> let d = em - mv in accu + d * d) 0.0 lst
114
  in sqrt (av / ll) -- stddev
115

    
116
-- *  Logical functions
117

    
118
-- Avoid syntactic sugar and enhance readability. These functions are proposed
119
-- by some for inclusion in the Prelude, and at the moment they are present
120
-- (with various definitions) in the utility-ht package. Some rationale and
121
-- discussion is available at <http://www.haskell.org/haskellwiki/If-then-else>
122

    
123
-- | \"if\" as a function, rather than as syntactic sugar.
124
if' :: Bool -- ^ condition
125
    -> a    -- ^ \"then\" result
126
    -> a    -- ^ \"else\" result
127
    -> a    -- ^ \"then\" or "else" result depending on the condition
128
if' True x _ = x
129
if' _    _ y = y
130

    
131
-- | Return the first result with a True condition, or the default otherwise.
132
select :: a            -- ^ default result
133
       -> [(Bool, a)]  -- ^ list of \"condition, result\"
134
       -> a            -- ^ first result which has a True condition, or default
135
select def = maybe def snd . find fst
136

    
137
-- | Annotate a Result with an ownership information.
138
annotateResult :: String -> Result a -> Result a
139
annotateResult owner (Bad s) = Bad $ owner ++ ": " ++ s
140
annotateResult _ v = v
141

    
142
-- | Try to extract a key from a object with better error reporting
143
-- than fromObj.
144
tryFromObj :: (J.JSON a) =>
145
              String     -- ^ Textual "owner" in error messages
146
           -> JSRecord   -- ^ The object array
147
           -> String     -- ^ The desired key from the object
148
           -> Result a
149
tryFromObj t o = annotateResult t . fromObj o
150

    
151

    
152
-- * Parsing utility functions
153

    
154
-- | Parse results from readsPrec.
155
parseChoices :: (Monad m, Read a) => String -> String -> [(a, String)] -> m a
156
parseChoices _ _ ((v, ""):[]) = return v
157
parseChoices name s ((_, e):[]) =
158
    fail $ name ++ ": leftover characters when parsing '"
159
           ++ s ++ "': '" ++ e ++ "'"
160
parseChoices name s _ = fail $ name ++ ": cannot parse string '" ++ s ++ "'"
161

    
162
-- | Safe 'read' function returning data encapsulated in a Result.
163
tryRead :: (Monad m, Read a) => String -> String -> m a
164
tryRead name s = parseChoices name s $ reads s
165

    
166
-- | Format a table of strings to maintain consistent length.
167
formatTable :: [[String]] -> [Bool] -> [[String]]
168
formatTable vals numpos =
169
    let vtrans = transpose vals  -- transpose, so that we work on rows
170
                                 -- rather than columns
171
        mlens = map (maximum . map length) vtrans
172
        expnd = map (\(flds, isnum, ml) ->
173
                         map (\val ->
174
                                  let delta = ml - length val
175
                                      filler = replicate delta ' '
176
                                  in if delta > 0
177
                                     then if isnum
178
                                          then filler ++ val
179
                                          else val ++ filler
180
                                     else val
181
                             ) flds
182
                    ) (zip3 vtrans numpos mlens)
183
   in transpose expnd
184

    
185
-- | Default group UUID (just a string, not a real UUID).
186
defaultGroupID :: GroupID
187
defaultGroupID = "00000000-0000-0000-0000-000000000000"
188

    
189
-- | Tries to extract number and scale from the given string.
190
--
191
-- Input must be in the format NUMBER+ SPACE* [UNIT]. If no unit is
192
-- specified, it defaults to MiB. Return value is always an integral
193
-- value in MiB.
194
parseUnit :: (Monad m, Integral a, Read a) => String -> m a
195
parseUnit str =
196
  -- TODO: enhance this by splitting the unit parsing code out and
197
  -- accepting floating-point numbers
198
  case reads str of
199
    [(v, suffix)] ->
200
      let unit = dropWhile (== ' ') suffix
201
          upper = map toUpper unit
202
          siConvert x = x * 1000000 `div` 1048576
203
      in case () of
204
           _ | null unit -> return v
205
             | unit == "m" || upper == "MIB" -> return v
206
             | unit == "M" || upper == "MB"  -> return $ siConvert v
207
             | unit == "g" || upper == "GIB" -> return $ v * 1024
208
             | unit == "G" || upper == "GB"  -> return $ siConvert
209
                                                (v * 1000)
210
             | unit == "t" || upper == "TIB" -> return $ v * 1048576
211
             | unit == "T" || upper == "TB"  -> return $
212
                                                siConvert (v * 1000000)
213
             | otherwise -> fail $ "Unknown unit '" ++ unit ++ "'"
214
    _ -> fail $ "Can't parse string '" ++ str ++ "'"