AnalysisServer.curry 14.9 KB
Newer Older
1
2
3
4
5
6
7
--------------------------------------------------------------------------
--- This is the main module of the analysis system.
--- One can either use the 'main' operation to start the system
--- in "server mode" or "batch mode" or use one of the operations below
--- to use the analysis system in another Curry program.
---
--- @author Heiko Hoffmann, Michael Hanus
8
--- @version May 2015
9
10
--------------------------------------------------------------------------

11
module AnalysisServer(main, initializeAnalysisSystem, analyzeModuleAsText,
12
                      analyzeModuleForBrowser, analyzeFunctionForBrowser,
13
14
                      analyzeGeneric, analyzePublic, analyzeInterface)
  where
15

16
17
import ReadNumeric(readNat)
import Char(isSpace)
18
import Directory
19
import FlatCurry(QName)
20
import Socket(Socket(..),listenOn,listenOnFresh,sClose,waitForSocketAccept)
21
22
23
import IO
import ReadShowTerm(readQTerm,showQTerm)
import System(system,sleep,setEnviron,getArgs)
24
import FileGoodies(stripSuffix,splitDirectoryBaseName)
25
26
27
28
import AnalysisCollection
import ServerFormats
import ServerFunctions(WorkerMessage(..))
import Configuration
29
30
import GenericProgInfo
import Analysis(Analysis,AOutFormat(..))
31
32
33
34
35
36
37
38
39
40
41
42
43

-- Messages to communicate with the analysis server from external programs.
data AnalysisServerMessage = 
    GetAnalysis
  | AnalyzeModule    String String String Bool
  | AnalyzeEntity  String String String String
  | StopServer
  | SetCurryPath String
  | ParseError

--- Main function to start the server.
--- Without any program arguments, the server is started on a socket.
--- Otherwise, it is started in batch mode to analyze a module.
Michael Hanus 's avatar
Michael Hanus committed
44
main :: IO ()
45
main = do
46
  debugMessage 1 systemBanner
47
  initializeAnalysisSystem
48
  args <- getArgs
49
  processArgs False args
Michael Hanus 's avatar
Michael Hanus committed
50

Michael Hanus 's avatar
Michael Hanus committed
51
processArgs :: Bool -> [String] -> IO ()
52
processArgs enforce args = case args of
Michael Hanus 's avatar
Michael Hanus committed
53
  [] -> mainServer Nothing
54
55
56
57
58
59
60
61
62
  ["-p",port]  -> maybe showError
                        (\ (p,r) -> if all isSpace r
                                    then mainServer (Just p)
                                    else showError )
                        (readNat port)
  ["-h"]       -> showHelp
  ["-?"]       -> showHelp
  ["--help"]   -> showHelp
  ("-r":rargs) -> processArgs True rargs
Michael Hanus 's avatar
Michael Hanus committed
63
64
65
66
  (('-':'D':kvs):rargs) -> let (key,eqvalue) = break (=='=') kvs
                            in if null eqvalue
                               then showError
                               else do updateCurrentProperty key (tail eqvalue)
67
                                       processArgs enforce rargs
Michael Hanus 's avatar
Michael Hanus committed
68
  [ananame,mname] ->
69
      if ananame `elem` registeredAnalysisNames
70
      then analyzeModuleAsText ananame (stripSuffix mname) enforce >>= putStrLn
71
      else showError
Michael Hanus 's avatar
Michael Hanus committed
72
  _ -> showError
73
 where
Michael Hanus 's avatar
Michael Hanus committed
74
75
  showError =
    error ("Illegal arguments (use '--help' for description):\n"++unwords args)
76
77

--- Initializations to be done when the system is started.
78
79
initializeAnalysisSystem :: IO ()
initializeAnalysisSystem = updateRCFile
80

Michael Hanus 's avatar
Michael Hanus committed
81
showHelp :: IO ()
82
showHelp = putStrLn $
Michael Hanus 's avatar
Michael Hanus committed
83
  "Usage: cass <options> [-p <port>] :\n" ++
84
85
86
  "       start analysis system in server mode\n\n"++
  "       <port>: port number for communication\n" ++
  "               (if omitted, a free port number is selected)\n\n"++
Michael Hanus 's avatar
Michael Hanus committed
87
  "Usage: cass <options> <analysis name> <module name> :\n"++
88
  "       analyze a module with a given analysis\n\n"++
Michael Hanus 's avatar
Michael Hanus committed
89
  "where <options> can contain:\n"++
90
91
92
  "-Dname=val : set property (of ~/.curryanalysisrc) 'name' as 'val'\n"++
  "-r         : force re-analysis (i.e., ignore old analysis information)\n"++
  "\nRegistered analyses names:\n" ++
93
94
  unlines registeredAnalysisNames

95
--- Start the analysis server on a socket.
96
97
mainServer :: Maybe Int -> IO ()
mainServer mbport = do
98
  putStrLn "Start Server"
99
100
101
  (port1,socket1) <- maybe listenOnFresh
                           (\p -> listenOn p >>= \s -> return (p,s))
                           mbport
102
103
104
105
106
107
108
109
  putStrLn ("Server Port: "++show port1)
  storeServerPortNumber port1
  getDefaultPath >>= setEnviron "CURRYPATH" 
  numworkers <- numberOfWorkers
  if numworkers>0
   then do
    serveraddress <- getServerAddress
    (workerport,workersocket) <- listenOnFresh
110
    debugMessage 2 ("SERVER: port to workers: "++show workerport)
111
    handles <- startWorkers numworkers workersocket serveraddress workerport []
112
    serverLoop socket1 handles
113
114
    sClose workersocket
   else
115
    serverLoop socket1 []
116
117


118
119
120
121
122
123
124
125
126
127
128
--- Run the analysis system and show the analysis results in standard textual
--- representation.
--- The third argument is a flag indicating whether the
--- (re-)analysis should be enforced.
--- Note that, before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
analyzeModuleAsText :: String -> String -> Bool -> IO String
analyzeModuleAsText ananame mname enforce =
  analyzeModule ananame (stripSuffix mname) enforce AText >>=
             return . formatResult mname "Text" Nothing True

129
130
131
132
133
--- Run the analysis system to show the analysis results in the BrowserGUI.
--- Note that, before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
analyzeModuleForBrowser :: String -> String -> AOutFormat -> IO [(QName,String)]
analyzeModuleForBrowser ananame moduleName aoutformat =
134
  analyzeModule ananame moduleName False aoutformat >>=
135
136
137
138
139
140
141
142
143
144
145
    return . either pinfo2list (const [])
 where
   pinfo2list pinfo = let (pubinfo,privinfo) = progInfo2Lists pinfo
                       in pubinfo++privinfo

--- Run the analysis system to show the analysis result of a single function
--- in the BrowserGUI.
--- Note that before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
analyzeFunctionForBrowser :: String -> QName -> AOutFormat -> IO String
analyzeFunctionForBrowser ananame qn@(mname,_) aoutformat = do
146
  analyzeModule ananame mname False aoutformat >>=
147
    return . either (maybe "" id . lookupProgInfo qn) (const "")
148

149
--- Analyze a complete module for a given analysis result format.
150
151
--- The third argument is a flag indicating whether the
--- (re-)analysis should be enforced.
152
153
--- Note that before its first use, the analysis system must be initialized
--- by 'initializeAnalysisSystem'.
154
analyzeModule :: String -> String -> Bool -> AOutFormat
155
              -> IO (Either (ProgInfo String) String)
156
analyzeModule ananame moduleName enforce aoutformat = do
157
158
159
160
  let (mdir,mname) = splitDirectoryBaseName moduleName
  getDefaultPath >>= setEnviron "CURRYPATH"
  curdir <- getCurrentDirectory
  unless (mdir==".") $ setCurrentDirectory mdir
161
  numworkers <- numberOfWorkers
162
163
164
165
166
167
  aresult <-
   if numworkers>0
     then do
      serveraddress <- getServerAddress
      (port,socket) <- listenOnFresh
      handles <- startWorkers numworkers socket serveraddress port []
168
      result <- runAnalysisWithWorkers ananame aoutformat enforce handles mname
169
170
171
      stopWorkers handles
      sClose socket
      return result
172
     else runAnalysisWithWorkers ananame aoutformat enforce [] mname
173
174
175
  setCurrentDirectory curdir
  return aresult

176
177
178
179
180
181
--- Start the analysis system with a particular analysis.
--- The analysis must be a registered one if workers are used.
--- If it is a combined analysis, the base analysis must be also
--- a registered one.
analyzeGeneric :: Analysis a -> String -> IO (Either (ProgInfo a) String)
analyzeGeneric analysis moduleName = do
182
  initializeAnalysisSystem
183
  let (mdir,mname) = splitDirectoryBaseName moduleName
184
  getDefaultPath >>= setEnviron "CURRYPATH" 
185
186
  curdir <- getCurrentDirectory
  unless (mdir==".") $ setCurrentDirectory mdir
187
  numworkers <- numberOfWorkers
188
189
190
191
192
193
  aresult <-
    if numworkers>0
     then do
      serveraddress <- getServerAddress
      (port,socket) <- listenOnFresh
      handles <- startWorkers numworkers socket serveraddress port []
194
      result <- analyzeMain analysis mname handles False True
195
196
197
198
      stopWorkers handles
      sClose socket
      return result
     else
199
      analyzeMain analysis mname [] False True
200
201
202
  setCurrentDirectory curdir
  return aresult
 
203
204
205
206
207
208
209
210
211
212
--- Start the analysis system with a given analysis to compute properties
--- of a module interface.
--- The analysis must be a registered one if workers are used.
--- If it is a combined analysis, the base analysis must be also
--- a registered one.
analyzePublic :: Analysis a -> String -> IO (Either (ProgInfo a) String)
analyzePublic analysis moduleName =
  analyzeGeneric analysis moduleName
  >>= return . either (Left . publicProgInfo) Right

213
214
215
216
217
218
--- Start the analysis system with a given analysis to compute properties
--- of a module interface.
--- The analysis must be a registered one if workers are used.
--- If it is a combined analysis, the base analysis must be also
--- a registered one.
analyzeInterface :: Analysis a -> String -> IO (Either [(QName,a)] String)
219
analyzeInterface analysis moduleName =
220
  analyzeGeneric analysis moduleName
221
  >>= return . either (Left . publicListFromProgInfo) Right
222
223
224
225
226
227
228

--------------------------------------------------------------------------
-- start a number of workers at server start
startWorkers:: Int -> Socket -> String -> Int -> [Handle] -> IO [Handle]
startWorkers number workersocket serveraddress workerport handles = do
  if number>0
    then do
229
      debugMessage 4 ("Number:"++(show number))
230
231
      let command = baseDir++"/cass_worker "++serveraddress++" "
                                            ++(show workerport)++" &"
232
      debugMessage 4 ("system command: "++command)
233
      system command
234
      debugMessage 4 ("Wait for socket accept for client "++show number)
235
      connection <- waitForSocketAccept workersocket waitTime
236
      debugMessage 4 ("Socket accept for client "++show number)
237
238
239
240
241
242
243
244
245
246
      case connection of
        Just (_,handle) -> do
          startWorkers (number-1) workersocket serveraddress workerport
                       (handle:handles)
        Nothing -> do
          putStrLn ("startWorkers: connection error worker "++(show number))
          startWorkers (number-1) workersocket serveraddress workerport handles
    else return handles

-- stop all workers at server stop
Michael Hanus 's avatar
Michael Hanus committed
247
stopWorkers :: [Handle] -> IO ()
248
249
250
251
252
253
254
255
stopWorkers [] = done
stopWorkers (handle:whandles) = do
  hPutStrLn handle (showQTerm StopWorker)
  hClose handle
  stopWorkers whandles

--------------------------------------------------------------------------
-- server loop to answer analysis requests over network
Michael Hanus 's avatar
Michael Hanus committed
256
serverLoop :: Socket -> [Handle] -> IO ()
257
serverLoop socket1 whandles = do
258
  --debugMessage 3 "SERVER: serverLoop"
259
260
  connection <- waitForSocketAccept socket1 waitTime
  case connection of 
261
262
263
    Just (_,handle) -> serverLoopOnHandle socket1 whandles handle
    Nothing -> do
      putStrLn "serverLoop: connection error: time out in waitForSocketAccept"
264
      sleep 1
265
266
267
268
269
270
271
272
273
274
275
276
277
      serverLoop socket1 whandles

--- Reads a line from an input handle and returns it.
hGetLineUntilEOF  :: Handle -> IO String
hGetLineUntilEOF h = do
  eof <- hIsEOF h
  if eof
   then return ""
   else do c <- hGetChar h
           if c=='\n' then return ""
                      else do cs <- hGetLineUntilEOF h
                              return (c:cs)

Michael Hanus 's avatar
Michael Hanus committed
278
serverLoopOnHandle :: Socket -> [Handle] -> Handle -> IO ()
279
280
281
282
serverLoopOnHandle socket1 whandles handle = do
  eof <- hIsEOF handle
  if eof
   then do hClose handle
283
           debugMessage 2 "SERVER connection: eof"
284
285
286
           serverLoop socket1 whandles
   else do
     string <- hGetLineUntilEOF handle
287
     debugMessage 2 ("SERVER got message: "++string)
288
     let force = False
289
290
291
292
293
294
295
296
     case parseServerMessage string of
       ParseError -> do
         sendServerError handle ("Illegal message received: "++string)
         serverLoopOnHandle socket1 whandles handle
       GetAnalysis -> do
         sendServerResult handle showAnalysisNamesAndFormats
         serverLoopOnHandle socket1 whandles handle
       AnalyzeModule ananame outForm modname public ->
297
         catch (runAnalysisWithWorkers ananame AText force whandles modname >>=
298
299
300
301
                return . formatResult modname outForm Nothing public >>=
                sendResult)
               sendAnalysisError
       AnalyzeEntity ananame outForm modname functionName ->
302
         catch (runAnalysisWithWorkers ananame AText force whandles modname >>=
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
                return . formatResult modname outForm
                                      (Just functionName) False >>= sendResult)
               sendAnalysisError
       SetCurryPath path -> do
         setEnviron "CURRYPATH" path
         changeWorkerPath path whandles
         sendServerResult handle ""
         serverLoopOnHandle socket1 whandles handle
       StopServer -> do
         stopWorkers whandles
         sendServerResult handle ""
         hClose handle
         sClose socket1
         putStrLn "Stop Server"
         removeServerPortNumber
318
 where
319
  sendResult resultstring = do
320
    debugMessage 4 ("formatted result:\n"++resultstring)
321
322
    sendServerResult handle resultstring
    serverLoopOnHandle socket1 whandles handle
323

324
325
326
  sendAnalysisError err = do
    sendServerError handle ("ERROR in analysis server: "++showError err)
    serverLoopOnHandle socket1 whandles handle
327
328

-- Send a server result in the format "ok <n>\n<result text>" where <n>
329
-- is the number of lines of the <result text>.
Michael Hanus 's avatar
Michael Hanus committed
330
sendServerResult :: Handle -> String -> IO ()
331
332
333
334
335
336
sendServerResult handle resultstring = do
  let resultlines = lines resultstring
  hPutStrLn handle ("ok " ++ show (length resultlines))
  hPutStr handle (unlines resultlines)
  hFlush handle

337
-- Send a server error in the format "error <error message>\n".
Michael Hanus 's avatar
Michael Hanus committed
338
sendServerError :: Handle -> String -> IO ()
339
sendServerError handle errstring = do
340
  debugMessage 1 errstring
341
342
343
  hPutStrLn handle ("error "++errstring)
  hFlush handle

344
345
346
-- Inform the worker threads about a given changed library search path
changeWorkerPath :: String -> [Handle] -> IO ()
changeWorkerPath _ [] = done
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
changeWorkerPath path (handle:whandles) = do
  hPutStrLn handle (showQTerm (ChangePath path))
  changeWorkerPath path whandles

-- parse incoming message for type of request
parseServerMessage :: String -> AnalysisServerMessage
parseServerMessage message = case words message of
  [] -> ParseError
  w:ws -> case w of 
    "GetAnalysis" -> GetAnalysis
    "AnalyzeModule" -> case ws of 
      s1:s2:s3:[] -> checkFormat s2 $ AnalyzeModule s1 s2 s3 False
    "AnalyzeInterface" -> case ws of 
      s1:s2:s3:[] -> checkFormat s2 $ AnalyzeModule s1 s2 s3 True
      _ -> ParseError
    "AnalyzeFunction" -> case ws of
      s1:s2:s3:s4:[] -> checkFormat s2 $ AnalyzeEntity s1 s2 s3 s4
      _ -> ParseError
    "AnalyzeTypeConstructor" -> case ws of
      s1:s2:s3:s4:[] -> checkFormat s2 $ AnalyzeEntity s1 s2 s3 s4
      _ -> ParseError
    "AnalyzeDataConstructor" -> case ws of
      s1:s2:s3:s4:[] -> checkFormat s2 $ AnalyzeEntity s1 s2 s3 s4
      _ -> ParseError  
    "SetCurryPath" -> case ws of
      s:[] -> SetCurryPath s
      _ -> ParseError
    "StopServer" -> StopServer
    _ -> ParseError 
 where
  checkFormat fmt msg = if fmt `elem` serverFormats then msg else ParseError

--- Show all analysis names and formats.
showAnalysisNamesAndFormats :: String
showAnalysisNamesAndFormats =
  unlines (concatMap (\an -> map ((an++" ")++) serverFormats)
383
                     registeredAnalysisNames)
384