Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / Utils.hs @ 61bbbed7

History | View | Annotate | Download (7.2 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
    (
26
      debug
27
    , debugFn
28
    , debugXy
29
    , sepSplit
30
    , stdDev
31
    , if'
32
    , select
33
    , applyIf
34
    , commaJoin
35
    , readEitherString
36
    , JSRecord
37
    , loadJSArray
38
    , fromObj
39
    , fromObjWithDefault
40
    , maybeFromObj
41
    , tryFromObj
42
    , fromJVal
43
    , asJSObject
44
    , asObjectList
45
    , fromJResult
46
    , tryRead
47
    , formatTable
48
    , annotateResult
49
    , defaultGroupID
50
    , parseUnit
51
    ) where
52

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

    
57
import Debug.Trace
58

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

    
63
-- * Debug functions
64

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

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

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

    
78
-- * Miscellaneous
79

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

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

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

    
98
-- * Mathematical functions
99

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

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

    
117
-- *  Logical functions
118

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

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

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

    
138

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

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

    
153

    
154
-- * Parsing utility functions
155

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

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

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

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

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