2-- Module : Streamly.Internal.FileSystem.Event.Linux
3-- Copyright : (c) 2020 Composewell Technologies
4-- License : BSD-3-Clause
5-- Maintainer : streamly@composewell.com
6-- Stability : pre-release
11-- Use 'watchPaths' with a list of file system paths you want to watch as
12-- argument. It returns a stream of 'Event' representing the file system events
13-- occurring under the watched paths.
16-- Stream.mapM_ (putStrLn . 'showEvent') $ 'watchPaths' [Array.fromCString\# "dir"#]
19-- 'Event' is an opaque type. Accessor functions (e.g. 'showEvent' above)
20-- provided in this module are used to determine the attributes of the event.
22-- Identical successive events may be coalesced into a single event.
26-- For reference documentation see:
28-- * <https://man7.org/linux/man-pages/man7/inotify.7.html inotify man page>
30-- We try to keep the macOS\/Linux/Windows event handling APIs and defaults
31-- semantically and syntactically as close as possible.
35-- When testing on Linux Kernel version @5.3.0-53-generic #47-Ubuntu@, the last
36-- event for the root path seems to be delayed until one more event occurs.
38-- = Differences between macOS and Linux APIs:
40-- 1. macOS watch is based on the path provided to it, if the path is
41-- deleted and recreated it will still be watched, if the path moves to another
42-- path it won't be watched anymore. Whereas Linux watch is based on a handle
43-- to the path, if the path is deleted and recreated it won't be watched, if
44-- the path moves to another it can still be watched (though this is
47-- 2. macOS watches the directory hierarchy recursively, Linux watches only one
48-- level of dir, recursive watch has to be built in user space by watching for
49-- create events and adding the new directories to the watch. Not sure how this
50-- will scale for too many paths.
52-- 3. In macOS the path of the subject of the event is absolute, in Linux the
53-- path is the name of the object inside the dir being watched.
55-- 4. On Linux 'watchPaths' fails if a path does not exist, on macOS it does
60#if HAVE_DECL_IN_EXCL_UNLINK
61module Streamly.Internal.FileSystem.Event.Linux
63 -- * Subscribing to events
65 -- ** Default configuration
78 -- ** Events of Interest
79 -- *** Root Level Events
83 -- *** Item Level Metadata change
86 -- *** Item Level Access
92 -- *** Item CRUD events
102 -- XXX watchPaths is redundant now because we can use watchTrees with
103 -- setRecursiveMode False. Perhaps we can use a common "watch" API.
118 -- ** Exception Conditions
121 -- ** Root Level Events
127 -- ** Item Level Metadata change
130 -- ** Item Level Access
136 -- ** Item CRUD events
151import Control.Monad (void, when)
152import Control.Monad.IO.Class (MonadIO, liftIO)
153import Data.Bits ((.|.), (.&.), complement)
154import Data.Char (ord)
155import Data.Foldable (foldlM)
156import Data.Functor.Identity (runIdentity)
157import Data.IntMap.Lazy (IntMap)
158import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef)
159import Data.List.NonEmpty (NonEmpty)
160#if !(MIN_VERSION_base(4,11,0))
161import Data.Semigroup (Semigroup(..))
163import Data.Word (Word8, Word32)
164import Foreign.C.Error (throwErrnoIfMinus1)
165import Foreign.C.String (CString)
166import Foreign.C.Types (CInt(..), CUInt(..))
167import Foreign.Ptr (Ptr)
168import Foreign.Storable (peek, peekByteOff, sizeOf)
169import GHC.IO.Device (IODeviceType(Stream))
170import GHC.IO.FD (fdFD, mkFD)
171import GHC.IO.Handle.FD (mkHandleFromFD)
172import Streamly.Prelude (SerialT)
173import Streamly.Internal.Data.Parser (Parser)
174import Streamly.Internal.Data.Array.Foreign.Type (Array(..))
175import System.IO (Handle, hClose, IOMode(ReadMode))
176#if !MIN_VERSION_base(4,10,0)
177import Control.Concurrent.MVar (readMVar)
178import Data.Typeable (cast)
179import GHC.IO.Exception (IOException(..), IOErrorType(..), ioException)
181import GHC.IO.Handle.Types (Handle__(..), Handle(FileHandle, DuplexHandle))
183import GHC.IO.Handle.FD (handleToFd)
186import qualified Data.IntMap.Lazy as Map
187import qualified Data.List.NonEmpty as NonEmpty
188import qualified Streamly.Internal.Data.Array.Foreign as A
189import qualified Streamly.Internal.Data.Fold as FL
190import qualified Streamly.Internal.Data.Parser as PR
191import qualified Streamly.Internal.Data.Stream.IsStream as S
192import qualified Streamly.Internal.FileSystem.Dir as Dir
193import qualified Streamly.Internal.FileSystem.Handle as FH
194import qualified Streamly.Internal.Unicode.Stream as U
196-------------------------------------------------------------------------------
197-- Subscription to events
198-------------------------------------------------------------------------------
200-- | Watch configuration, used to specify the events of interest and the
201-- behavior of the watch.
207 , createFlags :: Word32
210-------------------------------------------------------------------------------
212-------------------------------------------------------------------------------
214-- | Whether a setting is 'On' or 'Off'.
218data Toggle = On | Off
220toggle :: Toggle -> Toggle
224setFlag :: Word32 -> Toggle -> Config -> Config
225setFlag mask status cfg@Config{..} =
228 On -> createFlags .|. mask
229 Off -> createFlags .&. complement mask
230 in cfg {createFlags = flags}
232-------------------------------------------------------------------------------
234-------------------------------------------------------------------------------
236-- | Watch the whole directory tree recursively instead of watching just one
237-- level of directory.
243setRecursiveMode :: Bool -> Config -> Config
244setRecursiveMode rec cfg@Config{} = cfg {watchRec = rec}
247 "sys/inotify.h value IN_DONT_FOLLOW" iN_DONT_FOLLOW :: Word32
249-- | If the pathname to be watched is a symbolic link then watch the target of
250-- the symbolic link instead of the symbolic link itself.
256setFollowSymLinks :: Toggle -> Config -> Config
257setFollowSymLinks s = setFlag iN_DONT_FOLLOW (toggle s)
260 "sys/inotify.h value IN_EXCL_UNLINK" iN_EXCL_UNLINK :: Word32
262-- | If an object moves out of the directory being watched then stop watching
269setUnwatchMoved :: Toggle -> Config -> Config
270setUnwatchMoved = setFlag iN_EXCL_UNLINK
272#if HAVE_DECL_IN_MASK_CREATE
274 "sys/inotify.h value IN_MASK_CREATE" iN_MASK_CREATE :: Word32
278 "sys/inotify.h value IN_MASK_ADD" iN_MASK_ADD :: Word32
280-- | What to do if a watch already exists when 'openWatch' or 'addToWatch' is
286 AddIfExists -- ^ Do not set an existing setting to 'Off' only set to 'On'
287 | ReplaceIfExists -- ^ Replace the existing settings with new settings
288#if HAVE_DECL_IN_MASK_CREATE
289 | FailIfExists -- ^ Fail the API
292-- | When adding a new path to the watch, specify what to do if a watch already
293-- exists on that path.
295-- /default: FailIfExists/
299setWhenExists :: WhenExists -> Config -> Config
300setWhenExists val cfg =
302 AddIfExists -> setFlag iN_MASK_ADD On cfg
303 ReplaceIfExists -> setFlag iN_MASK_ADD Off cfg
304#if HAVE_DECL_IN_MASK_CREATE
305 FailIfExists -> setFlag iN_MASK_CREATE On cfg
309 "sys/inotify.h value IN_ONESHOT" iN_ONESHOT :: Word32
311-- | Watch the object only for one event and then remove it from the watch.
317setOneShot :: Toggle -> Config -> Config
318setOneShot = setFlag iN_ONESHOT
321 "sys/inotify.h value IN_ONLYDIR" iN_ONLYDIR :: Word32
323-- | Watch the object only if it is a directory. This provides a race-free way
324-- to ensure that the watched object is a directory.
330setOnlyDir :: Toggle -> Config -> Config
331setOnlyDir = setFlag iN_ONLYDIR
333-------------------------------------------------------------------------------
334-- Event types that can occur
335-------------------------------------------------------------------------------
338 "sys/inotify.h value IN_DELETE_SELF" iN_DELETE_SELF :: Word32
340-- | Report when the watched path itself gets deleted.
346setRootDeleted :: Toggle -> Config -> Config
347setRootDeleted = setFlag iN_DELETE_SELF
350 "sys/inotify.h value IN_MOVE_SELF" iN_MOVE_SELF :: Word32
352-- | Report when the watched root path itself gets renamed.
358setRootMoved :: Toggle -> Config -> Config
359setRootMoved = setFlag iN_MOVE_SELF
362 "sys/inotify.h value IN_ATTRIB" iN_ATTRIB :: Word32
364-- | Report when the metadata e.g. owner, permission modes, modifications times
365-- of an object changes.
371setMetadataChanged :: Toggle -> Config -> Config
372setMetadataChanged = setFlag iN_ATTRIB
375 "sys/inotify.h value IN_ACCESS" iN_ACCESS :: Word32
377-- | Report when a file is accessed.
383setAccessed :: Toggle -> Config -> Config
384setAccessed = setFlag iN_ACCESS
387 "sys/inotify.h value IN_OPEN" iN_OPEN :: Word32
389-- | Report when a file is opened.
395setOpened :: Toggle -> Config -> Config
396setOpened = setFlag iN_OPEN
399 "sys/inotify.h value IN_CLOSE_WRITE" iN_CLOSE_WRITE :: Word32
401-- | Report when a file that was opened for writes is closed.
407setWriteClosed :: Toggle -> Config -> Config
408setWriteClosed = setFlag iN_CLOSE_WRITE
411 "sys/inotify.h value IN_CLOSE_NOWRITE" iN_CLOSE_NOWRITE :: Word32
413-- | Report when a file that was opened for not writing is closed.
419setNonWriteClosed :: Toggle -> Config -> Config
420setNonWriteClosed = setFlag iN_CLOSE_NOWRITE
423 "sys/inotify.h value IN_CREATE" iN_CREATE :: Word32
425-- | Report when a file is created.
431setCreated :: Toggle -> Config -> Config
432setCreated = setFlag iN_CREATE
435 "sys/inotify.h value IN_DELETE" iN_DELETE :: Word32
437-- | Report when a file is deleted.
443setDeleted :: Toggle -> Config -> Config
444setDeleted = setFlag iN_DELETE
447 "sys/inotify.h value IN_MOVED_FROM" iN_MOVED_FROM :: Word32
449-- | Report the source of a move.
455setMovedFrom :: Toggle -> Config -> Config
456setMovedFrom = setFlag iN_MOVED_FROM
459 "sys/inotify.h value IN_MOVED_TO" iN_MOVED_TO :: Word32
461-- | Report the target of a move.
467setMovedTo :: Toggle -> Config -> Config
468setMovedTo = setFlag iN_MOVED_TO
471 "sys/inotify.h value IN_MODIFY" iN_MODIFY :: Word32
473-- | Report when a file is modified.
479setModified :: Toggle -> Config -> Config
480setModified = setFlag iN_MODIFY
482-- | Set all events 'On' or 'Off'.
488setAllEvents :: Toggle -> Config -> Config
492 . setMetadataChanged s
496 . setNonWriteClosed s
504-------------------------------------------------------------------------------
506-------------------------------------------------------------------------------
508-- The defaults are set in such a way that the behavior on macOS and Linux is
509-- as much compatible as possible.
513-- * 'setFollowSymLinks' 'On'
514-- * 'setUnwatchMoved' 'On'
515-- * 'setOneShot' 'Off'
516-- * 'setOnlyDir' 'Off'
517-- * 'setWhenExists' 'AddIfExists'
518-- * 'setAllEvents' 'On'
522defaultConfig :: Config
524 setWhenExists AddIfExists
531-------------------------------------------------------------------------------
532-- Open an event stream
533-------------------------------------------------------------------------------
535-- | A handle for a watch.
538 Handle -- File handle for the watch
540 (IntMap -- Key is the watch descriptor
541 ( Array Word8 -- Absolute path of the watch root
542 , Array Word8 -- Path of subdir relative to watch root
547-- Instead of using the watch descriptor we can provide APIs that use the path
548-- itself to identify the watch. That will require us to maintain a map from wd
549-- to path in the Watch handle.
551newtype WD = WD CInt deriving Show
553foreign import ccall unsafe
554 "sys/inotify.h inotify_init" c_inotify_init :: IO CInt
556-- | Create a 'Watch' handle. 'addToWatch' can be used to add paths being
557-- monitored by this watch.
561createWatch :: IO Watch
563 rawfd <- throwErrnoIfMinus1 "createWatch" c_inotify_init
564 -- we could use fdToHandle but it cannot determine the fd type
565 -- automatically for the inotify fd
570 (Just (Stream, 0, 0)) -- (IODeviceType, CDev, CIno)
571 False -- not a socket
572 False -- non-blocking is false
573 let fdString = "<createWatch file descriptor: " ++ show fd ++ ">"
580 True -- use non-blocking IO
581 Nothing -- TextEncoding (binary)
582 emptyMapRef <- newIORef Map.empty
583 return $ Watch h emptyMapRef
585foreign import ccall unsafe
586 "sys/inotify.h inotify_add_watch" c_inotify_add_watch
587 :: CInt -> CString -> CUInt -> IO CInt
589-- XXX we really do not know the path encoding, all we know is that it is "/"
590-- separated bytes. So these may fail or convert the path in an unexpected
591-- manner. We should ultimately remove all usage of these.
593toUtf8 :: MonadIO m => String -> m (Array Word8)
594toUtf8 = A.fromStream . U.encodeUtf8 . S.fromList
596utf8ToString :: Array Word8 -> String
597utf8ToString = runIdentity . S.toList . U.decodeUtf8' . A.toStream
599#if !MIN_VERSION_base(4,10,0)
600-- | Turn an existing Handle into a file descriptor. This function throws an
601-- IOError if the Handle does not reference a file descriptor.
602handleToFd :: Handle -> IO FD
603handleToFd h = case h of
604 FileHandle _ mv -> do
605 Handle__{haDevice = dev} <- readMVar mv
608 Nothing -> throwErr "not a file descriptor"
609 DuplexHandle{} -> throwErr "not a file handle"
613 throwErr msg = ioException $ IOError (Just h)
614 InappropriateType "handleToFd" msg Nothing Nothing
617-- | Add a trailing "/" at the end of the path if there is none. Do not add a
618-- "/" if the path is empty.
620ensureTrailingSlash :: Array Word8 -> Array Word8
621ensureTrailingSlash path =
622 if A.length path /= 0
624 let mx = A.getIndex path (A.length path - 1)
626 Nothing -> error "ensureTrailingSlash: Bug: Invalid index"
628 if x /= fromIntegral (ord '/')
629 then path <> A.fromCString# "/"#
633-- | @addToWatch cfg watch root subpath@ adds @subpath@ to the list of paths
634-- being monitored under @root@ via the watch handle @watch@. @root@ must be
635-- an absolute path and @subpath@ must be relative to @root@.
639addToWatch :: Config -> Watch -> Array Word8 -> Array Word8 -> IO ()
640addToWatch cfg@Config{..} watch@(Watch handle wdMap) root0 path0 = do
641 -- XXX do not add if the path is already added
642 -- XXX if the watch is added by the scan and not via an event we can
643 -- generate a create event assuming that the create may have been lost. We
644 -- can also mark in the map that this entry was added by the scan. So if an
645 -- actual create event later comes and tries to add this again then we can
646 -- ignore that and drop the create event to avoid duplicate create, because
647 -- we have already emitted it.
649 -- When a directory is added by the scan we should also emit create events
650 -- for files that may have got added to the dir. However, such create
651 -- events may get duplicated because of a race between the scan generated
652 -- versus real events.
654 -- Or we may distinguish between scan generated events and real events so
655 -- that the application can assume that other events may been lost and
656 -- handle it. For example, if it is a dir create the application can read
657 -- the dir to scan the files in it.
659 let root = ensureTrailingSlash root0
660 path = ensureTrailingSlash path0
661 absPath = root <> path
662 fd <- handleToFd handle
664 -- XXX we need to tolerate an error where we are adding a watch for a
665 -- non-existing file because the file may have got deleted by the time we
666 -- added the watch. Perhaps we can have a flag in config for this and keep
667 -- the default value to tolerate the error.
669 -- XXX The file may have even got deleted and then recreated which we will
670 -- never get to know, document this.
671 wd <- A.unsafeAsCString absPath $ \pathPtr ->
672 throwErrnoIfMinus1 ("addToWatch: " ++ utf8ToString absPath) $
673 c_inotify_add_watch (fdFD fd) pathPtr (CUInt createFlags)
675 -- We add the parent first so that we start getting events for any new
676 -- creates and add the new subdirectories on creates while we are adding
678 modifyIORef wdMap (Map.insert (fromIntegral wd) (root, path))
680 -- Now add the children. If we missed any creates while we were adding the
681 -- parent, this will make sure they are added too.
683 -- XXX Ensure that we generate events that we may have missed while we were
686 -- XXX toDirs currently uses paths as String, we need to convert it
687 -- to "/" separated by byte arrays.
689 S.mapM_ (\p -> addToWatch cfg watch root (path <> p))
691 $ Dir.toDirs $ utf8ToString absPath
693foreign import ccall unsafe
694 "sys/inotify.h inotify_rm_watch" c_inotify_rm_watch
695 :: CInt -> CInt -> IO CInt
697-- | Remove an absolute root path from a 'Watch', if a path was moved after
698-- adding you need to provide the original path which was used to add the
703removeFromWatch :: Watch -> Array Word8 -> IO ()
704removeFromWatch (Watch handle wdMap) path = do
705 fd <- handleToFd handle
706 km <- readIORef wdMap
707 wdMap1 <- foldlM (step fd) Map.empty (Map.toList km)
708 writeIORef wdMap wdMap1
712 step fd newMap (wd, v) = do
715 let err = "removeFromWatch: " ++ show (utf8ToString path)
716 rm = c_inotify_rm_watch (fdFD fd) (fromIntegral wd)
717 void $ throwErrnoIfMinus1 err rm
719 else return $ Map.insert wd v newMap
721-- | Given a 'Config' and list of @paths@ ("/" separated byte arrays) start
722-- monitoring the paths for file system events. Returns a 'Watch' handle which
723-- can then be used to read the event stream or to close the watch.
727openWatch :: Config -> NonEmpty (Array Word8) -> IO Watch
728openWatch cfg paths = do
730 mapM_ (\p -> addToWatch cfg w p (A.fromList [])) $ NonEmpty.toList paths
733-- | Close a 'Watch' handle.
737closeWatch :: Watch -> IO ()
738closeWatch (Watch h _) = hClose h
740-------------------------------------------------------------------------------
741-- Raw events read from the watch file handle
742-------------------------------------------------------------------------------
744newtype Cookie = Cookie Word32 deriving (Show, Eq)
746-- | An Event generated by the file system. Use the accessor functions to
753 , eventFlags :: Word32
754 , eventCookie :: Word32
755 , eventRelPath :: Array Word8
756 , eventMap :: IntMap (Array Word8, Array Word8)
757 } deriving (Show, Ord, Eq)
759-- The inotify event struct from the man page/header file:
761-- struct inotify_event {
762-- int wd; /* Watch descriptor */
763-- uint32_t mask; /* Mask describing event */
764-- uint32_t cookie; /* Unique cookie associating related
765-- events (for rename(2)) */
766-- uint32_t len; /* Size of name field */
767-- char name[]; /* Optional null-terminated name */
770-- XXX We can perhaps use parseD monad instance for fusing with parseMany? Need
771-- to measure the perf.
773readOneEvent :: Config -> Watch -> Parser IO Word8 Event
774readOneEvent cfg wt@(Watch _ wdMap) = do
775 let headerLen = (sizeOf (undefined :: CInt)) + 12
776 arr <- PR.takeEQ headerLen (A.writeN headerLen)
777 (ewd, eflags, cookie, pathLen) <- PR.fromEffect $ A.unsafeAsPtr arr readHeader
778 -- XXX need the "initial" in parsers to return a step type so that "take 0"
779 -- can return without an input. otherwise if pathLen is 0 we will keep
780 -- waiting to read one more char before we return this event.
784 -- XXX takeEndBy_ drops the separator so assumes a null
785 -- terminated path, we should use a takeWhile nested inside a
789 $ FL.takeEndBy_ (== 0)
790 $ FL.take pathLen (A.writeN pathLen)
791 let remaining = pathLen - A.length pth - 1
792 when (remaining /= 0) $ PR.takeEQ remaining FL.drain
794 else return $ A.fromList []
795 wdm <- PR.fromEffect $ readIORef wdMap
797 case Map.lookup (fromIntegral ewd) wdm of
800 error $ "readOneEvent: "
801 <> "Unknown watch descriptor: "
803 let -- "sub" is guaranteed to have a trailing "/"
805 -- Check for "ISDIR" first because it is less likely
806 isDirCreate = eflags .&. iN_ISDIR /= 0 && eflags .&. iN_CREATE /= 0
807 when (watchRec cfg && isDirCreate)
808 $ PR.fromEffect $ addToWatch cfg wt root sub1
809 -- XXX Handle IN_DELETE, IN_DELETE_SELF, IN_MOVE_SELF, IN_MOVED_FROM,
811 -- What if a large dir tree gets moved in to our hierarchy? Do we get a
812 -- single event for the top level dir in this case?
814 { eventWd = (fromIntegral ewd)
815 , eventFlags = eflags
816 , eventCookie = cookie
817 , eventRelPath = sub1
823 readHeader (ptr :: Ptr Word8) = do
824 let len = sizeOf (undefined :: CInt)
826 eflags <- peekByteOff ptr len
827 cookie <- peekByteOff ptr (len + 4)
828 pathLen :: Word32 <- peekByteOff ptr (len + 8)
829 return (ewd, eflags, cookie, fromIntegral pathLen)
831watchToStream :: Config -> Watch -> SerialT IO Event
832watchToStream cfg wt@(Watch handle _) = do
833 -- Do not use too small a buffer. As per inotify man page:
835 -- The behavior when the buffer given to read(2) is too small to return
836 -- information about the next event depends on the kernel version: in
837 -- kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2)
838 -- fails with the error EINVAL. Specifying a buffer of size
840 -- sizeof(struct inotify_event) + NAME_MAX + 1
842 -- will be sufficient to read at least one event.
843 S.parseMany (readOneEvent cfg wt) $ S.unfold FH.read handle
845-- | Start monitoring a list of file system paths for file system events with
846-- the supplied configuration operation over the 'defaultConfig'. The
847-- paths could be files or directories. When the path is a directory, only the
848-- files and directories directly under the watched directory are monitored,
849-- contents of subdirectories are not monitored. Monitoring starts from the
850-- current time onwards. The paths are specified as "/" separated 'Array' of
855-- ('setFollowSymLinks' On . 'setUnwatchMoved' Off)
856-- [Array.fromCString\# "dir"#]
862 (Config -> Config) -> NonEmpty (Array Word8) -> SerialT IO Event
863watchPathsWith f = watchTreesWith (f . setRecursiveMode False)
865-- | Like 'watchPathsWith' but uses the 'defaultConfig' options.
868-- watchPaths = watchPathsWith id
873watchPaths :: NonEmpty (Array Word8) -> SerialT IO Event
874watchPaths = watchPathsWith id
876-- XXX We should not go across the mount points of network file systems or file
877-- systems that are known to not generate any events.
879-- | Start monitoring a list of file system paths for file system events with
880-- the supplied configuration operation over the 'defaultConfig'. The
881-- paths could be files or directories. When the path is a directory, the
882-- whole directory tree under it is watched recursively. Monitoring starts from
883-- the current time onwards.
885-- Note that recrusive watch on a large directory tree could be expensive. When
886-- starting a watch, the whole tree must be read and watches are started on
887-- each directory in the tree. The initial time to start the watch as well as
888-- the memory required is proportional to the number of directories in the
891-- When new directories are created under the tree they are added to the watch
892-- on receiving the directory create event. However, the creation of a dir and
893-- adding a watch for it is not atomic. The implementation takes care of this
894-- and makes sure that watches are added for all directories. However, In the
895-- mean time, the directory may have received more events which may get lost.
896-- Handling of any such lost events is yet to be implemented.
898-- See the Linux __inotify__ man page for more details.
903 (Config -> Config) -> NonEmpty (Array Word8) -> SerialT IO Event
904watchTreesWith f paths = S.bracket before after (watchToStream cfg)
908 cfg = f defaultConfig
909 before = liftIO $ openWatch cfg paths
910 after = liftIO . closeWatch
912-- | Like 'watchTreesWith' but uses the 'defaultConfig' options.
915-- watchTrees = watchTreesWith id
918watchTrees :: NonEmpty (Array Word8) -> SerialT IO Event
919watchTrees = watchTreesWith id
921-------------------------------------------------------------------------------
922-- Examine event stream
923-------------------------------------------------------------------------------
925-- | Get the watch root corresponding to the 'Event'.
927-- Note that if a path was moved after adding to the watch, this will give the
928-- original path and not the new path after moving.
930-- TBD: we can possibly update the watch root on a move self event.
934getRoot :: Event -> Array Word8
938 case Map.lookup (fromIntegral eventWd) eventMap of
939 Just path -> fst path
941 error $ "Bug: getRoot: No path found corresponding to the "
942 ++ "watch descriptor " ++ show eventWd
945-- XXX should we use a Maybe here?
946-- | Get the file system object path for which the event is generated, relative
947-- to the watched root. The path is a "/" separated array of bytes.
951getRelPath :: Event -> Array Word8
952getRelPath Event{..} = eventRelPath
955-- | Get the absolute file system object path for which the event is generated.
956-- The path is a "/" separated array of bytes.
960getAbsPath :: Event -> Array Word8
961getAbsPath ev = getRoot ev <> getRelPath ev
963-- XXX should we use a Maybe?
964-- | Cookie is set when a rename occurs. The cookie value can be used to
965-- connect the 'isMovedFrom' and 'isMovedTo' events, if both the events belong
966-- to the same move operation then they will have the same cookie value.
970getCookie :: Event -> Cookie
971getCookie Event{..} = Cookie eventCookie
973-------------------------------------------------------------------------------
975-------------------------------------------------------------------------------
977getFlag :: Word32 -> Event -> Bool
978getFlag mask Event{..} = eventFlags .&. mask /= 0
980-------------------------------------------------------------------------------
982-------------------------------------------------------------------------------
985 "sys/inotify.h value IN_Q_OVERFLOW" iN_Q_OVERFLOW :: Word32
987-- XXX rename to isQOverflowed or hasOverflowed?
989-- macOS overflow API is more specific, it tells which paths have lost the
990-- events due to overflow.
992-- | Event queue overflowed (WD is invalid for this event) and we may have lost
993-- some events.. The user application must scan everything under the watched
994-- paths to know the current state.
998isOverflow :: Event -> Bool
999isOverflow = getFlag iN_Q_OVERFLOW
1001-------------------------------------------------------------------------------
1002-- Events affecting the watched path only
1003-------------------------------------------------------------------------------
1006 "sys/inotify.h value IN_IGNORED" iN_IGNORED :: Word32
1008-- Compare with isRootChanged on macOS. isRootChanged includes all these cases.
1010-- | A path was removed from the watch explicitly using 'removeFromWatch' or
1011-- automatically (file was deleted, or filesystem was unmounted).
1013-- /Occurs only for a watched path/
1017isRootUnwatched :: Event -> Bool
1018isRootUnwatched = getFlag iN_IGNORED
1020-- | Watched file/directory was itself deleted. (This event also occurs if an
1021-- object is moved to another filesystem, since mv(1) in effect copies the file
1022-- to the other filesystem and then deletes it from the original filesystem.)
1023-- In addition, an 'isRootUnwatched' event will subsequently be generated
1024-- for the watch descriptor.
1026-- /Occurs only for a watched path/
1030isRootDeleted :: Event -> Bool
1031isRootDeleted = getFlag iN_DELETE_SELF
1033-- | Watched file/directory was itself moved within the file system.
1035-- /Occurs only for a watched path/
1039isRootMoved :: Event -> Bool
1040isRootMoved = getFlag iN_MOVE_SELF
1043 "sys/inotify.h value IN_UNMOUNT" iN_UNMOUNT :: Word32
1045-- | Filesystem containing watched object was unmounted. In addition, an
1046-- 'isRootUnwatched' event will subsequently be generated for the watch
1049-- /Occurs only for a watched path/
1053isRootUnmounted :: Event -> Bool
1054isRootUnmounted = getFlag iN_UNMOUNT
1056-------------------------------------------------------------------------------
1057-- Metadata change Events
1058-------------------------------------------------------------------------------
1060-- macOS has multiple APIs for metadata change for different metadata.
1062-- | Determine whether the event indicates inode metadata change for an object
1063-- contained within the monitored path.
1065-- Metadata change may include, permissions (e.g., chmod(2)), timestamps
1066-- (e.g., utimensat(2)), extended attributes (setxattr(2)), link count (since
1067-- Linux 2.6.25; e.g., for the target of link(2) and for unlink(2)), and
1068-- user/group ID (e.g., chown(2)).
1070-- /Can occur for watched path or a file inside it/
1074isMetadataChanged :: Event -> Bool
1075isMetadataChanged = getFlag iN_ATTRIB
1077-------------------------------------------------------------------------------
1079-------------------------------------------------------------------------------
1081-- | File was accessed (e.g. read, execve).
1083-- /Occurs only for a file inside the watched directory/
1087isAccessed :: Event -> Bool
1088isAccessed = getFlag iN_ACCESS
1090-- | File or directory was opened.
1092-- /Occurs only for a file inside the watched directory/
1096isOpened :: Event -> Bool
1097isOpened = getFlag iN_OPEN
1099-- | File opened for writing was closed.
1101-- /Occurs only for a file inside the watched directory/
1105isWriteClosed :: Event -> Bool
1106isWriteClosed = getFlag iN_CLOSE_WRITE
1108-- XXX what if it was opened for append? Does NOWRITE mean all cases where the
1109-- mode was not write? A dir open comes in this category?
1111-- | File or directory opened for read but not write was closed.
1113-- /Can occur for watched path or a file inside it/
1117isNonWriteClosed :: Event -> Bool
1118isNonWriteClosed = getFlag iN_CLOSE_NOWRITE
1120-------------------------------------------------------------------------------
1122-------------------------------------------------------------------------------
1124-- On macOS this is not generated on hard linking but on Linux it is.
1126-- | File/directory created in watched directory (e.g., open(2) O_CREAT,
1127-- mkdir(2), link(2), symlink(2), bind(2) on a UNIX domain socket).
1129-- /Occurs only for an object inside the watched directory/
1133isCreated :: Event -> Bool
1134isCreated = getFlag iN_CREATE
1136-- | File/directory deleted from watched directory.
1138-- /Occurs only for an object inside the watched directory/
1142isDeleted :: Event -> Bool
1143isDeleted = getFlag iN_DELETE
1145-- XXX what if an object is moved in from outside or moved out of the monitored
1148-- | Generated for the original path when an object is moved from under a
1149-- monitored directory.
1151-- /Occurs only for an object inside the watched directory/
1155isMovedFrom :: Event -> Bool
1156isMovedFrom = getFlag iN_MOVED_FROM
1158-- | Generated for the new path when an object is moved under a monitored
1161-- /Occurs only for an object inside the watched directory/
1165isMovedTo :: Event -> Bool
1166isMovedTo = getFlag iN_MOVED_TO
1168-- | Determine whether the event indicates modification of an object within the
1169-- monitored path. This event is generated only for files and not directories.
1171-- /Occurs only for an object inside the watched directory/
1175isModified :: Event -> Bool
1176isModified = getFlag iN_MODIFY
1178-------------------------------------------------------------------------------
1179-- Information about path type (applicable only when 'setFileEvents' is 'On')
1180-------------------------------------------------------------------------------
1183 "sys/inotify.h value IN_ISDIR" iN_ISDIR :: Word32
1185-- | Determine whether the event is for a directory path.
1189isDir :: Event -> Bool
1190isDir = getFlag iN_ISDIR
1192-------------------------------------------------------------------------------
1194-------------------------------------------------------------------------------
1196-- | Convert an 'Event' record to a String representation.
1197showEvent :: Event -> String
1198showEvent ev@Event{..} =
1199 "--------------------------"
1200 ++ "\nWd = " ++ show eventWd
1201 ++ "\nRoot = " ++ show (utf8ToString $ getRoot ev)
1202 ++ "\nRelative Path = " ++ show (utf8ToString $ getRelPath ev)
1203 ++ "\nAbsolute Path = " ++ show (utf8ToString $ getAbsPath ev)
1204 ++ "\nCookie = " ++ show (getCookie ev)
1205 ++ "\nFlags " ++ show eventFlags
1207 ++ showev isOverflow "Overflow"
1209 ++ showev isRootUnwatched "RootUnwatched"
1210 ++ showev isRootDeleted "RootDeleted"
1211 ++ showev isRootMoved "RootMoved"
1212 ++ showev isRootUnmounted "RootUnmounted"
1214 ++ showev isMetadataChanged "MetadataChanged"
1216 ++ showev isAccessed "Accessed"
1217 ++ showev isOpened "Opened"
1218 ++ showev isWriteClosed "WriteClosed"
1219 ++ showev isNonWriteClosed "NonWriteClosed"
1221 ++ showev isCreated "Created"
1222 ++ showev isDeleted "Deleted"
1223 ++ showev isModified "Modified"
1224 ++ showev isMovedFrom "MovedFrom"
1225 ++ showev isMovedTo "MovedTo"
1227 ++ showev isDir "Dir"
1230 where showev f str = if f ev then "\n" ++ str else ""
1232#warning "Disabling module Streamly.Internal.FileSystem.Event.Linux. Does not support kernels older than 2.6.36."
1233module Streamly.Internal.FileSystem.Event.Linux () where
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list