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 : experimental
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.fromList "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
79 -- ** Events of Interest
80 -- *** Root Path Events
85 -- *** Item Level Metadata change
88 -- *** Item Level Access
94 -- *** Item CRUD events
108 -- Low level watch APIs
119 -- ** Root Level Events
126 -- ** Item Level Metadata change
129 -- ** Item Level Access
135 -- ** Item Level CRUD events
146 -- ** Exception Conditions
154import Control.Monad (void, when)
155import Control.Monad.IO.Class (MonadIO, liftIO)
156import Data.Bits ((.|.), (.&.), complement)
157import Data.Char (ord)
158import Data.Foldable (foldlM)
159import Data.Functor.Identity (runIdentity)
160import Data.IntMap.Lazy (IntMap)
161import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef)
162import Data.List.NonEmpty (NonEmpty)
163#if !(MIN_VERSION_base(4,13,0))
164import Data.Semigroup (Semigroup(..))
166import Data.Word (Word8, Word32)
167import Foreign.C.Error (throwErrnoIfMinus1)
168import Foreign.C.String (CString)
169import Foreign.C.Types (CInt(..), CUInt(..))
170import Foreign.Ptr (Ptr)
171import Foreign.Storable (peek, peekByteOff, sizeOf)
172import GHC.IO.Device (IODeviceType(Stream))
173import GHC.IO.FD (fdFD, mkFD)
174import GHC.IO.Handle.FD (mkHandleFromFD)
175import Streamly.Internal.Data.Stream (Stream)
176import Streamly.Internal.Data.Parser (Parser)
177import Streamly.Internal.Data.Array.Unboxed.Type (Array(..), byteLength)
178import System.Directory (doesDirectoryExist)
179import System.IO (Handle, hClose, IOMode(ReadMode))
180import GHC.IO.Handle.FD (handleToFd)
182import qualified Data.IntMap.Lazy as Map
183import qualified Data.List.NonEmpty as NonEmpty
184import qualified Streamly.Internal.Data.Array.Unboxed as A
185import qualified Streamly.Data.Fold as FL
186import qualified Streamly.Internal.Data.Parser as PR
187 (takeEQ, fromEffect, fromFold)
188import qualified Streamly.Internal.Data.Stream.IsStream as S
189import qualified Streamly.Internal.FileSystem.Dir as Dir
190import qualified Streamly.Internal.FileSystem.Handle as FH
191import qualified Streamly.Internal.Unicode.Stream as U
193-------------------------------------------------------------------------------
194-- Subscription to events
195-------------------------------------------------------------------------------
197-- | Watch configuration, used to specify the events of interest and the
198-- behavior of the watch.
204 , createFlags :: Word32
207-------------------------------------------------------------------------------
209-------------------------------------------------------------------------------
211-- | Whether a setting is 'On' or 'Off'.
215data Switch = On | Off deriving (Show, Eq)
217toggle :: Switch -> Switch
221setFlag :: Word32 -> Switch -> Config -> Config
222setFlag mask status cfg@Config{..} =
225 On -> createFlags .|. mask
226 Off -> createFlags .&. complement mask
227 in cfg {createFlags = flags}
229-------------------------------------------------------------------------------
231-------------------------------------------------------------------------------
233-- | Watch the whole directory tree recursively instead of watching just one
234-- level of directory.
240setRecursiveMode :: Switch -> Config -> Config
241setRecursiveMode rec cfg@Config{} = cfg {watchRec = rec == On}
244 "sys/inotify.h value IN_DONT_FOLLOW" iN_DONT_FOLLOW :: Word32
246-- | If the pathname to be watched is a symbolic link then watch the target of
247-- the symbolic link instead of the symbolic link itself.
249-- Note that the path location in the events is through the original symbolic
250-- link path rather than the resolved path.
256setFollowSymLinks :: Switch -> 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 :: Switch -> 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 :: Switch -> 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 :: Switch -> 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 :: Switch -> 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 :: Switch -> Config -> Config
359setRootMoved = setFlag iN_MOVE_SELF
361-- | Report when the watched root path itself gets deleted or renamed.
367setRootPathEvents :: Switch -> Config -> Config
368setRootPathEvents = setFlag (iN_DELETE_SELF .|. iN_MOVE_SELF)
371 "sys/inotify.h value IN_ATTRIB" iN_ATTRIB :: Word32
373-- | Report when the metadata e.g. owner, permission modes, modifications times
374-- of an object changes.
380setAttrsModified :: Switch -> Config -> Config
381setAttrsModified = setFlag iN_ATTRIB
384 "sys/inotify.h value IN_ACCESS" iN_ACCESS :: Word32
386-- | Report when a file is accessed.
392setAccessed :: Switch -> Config -> Config
393setAccessed = setFlag iN_ACCESS
396 "sys/inotify.h value IN_OPEN" iN_OPEN :: Word32
398-- | Report when a file is opened.
404setOpened :: Switch -> Config -> Config
405setOpened = setFlag iN_OPEN
408 "sys/inotify.h value IN_CLOSE_WRITE" iN_CLOSE_WRITE :: Word32
410-- | Report when a file that was opened for writes is closed.
416setWriteClosed :: Switch -> Config -> Config
417setWriteClosed = setFlag iN_CLOSE_WRITE
420 "sys/inotify.h value IN_CLOSE_NOWRITE" iN_CLOSE_NOWRITE :: Word32
422-- | Report when a file that was opened for not writing is closed.
428setNonWriteClosed :: Switch -> Config -> Config
429setNonWriteClosed = setFlag iN_CLOSE_NOWRITE
432 "sys/inotify.h value IN_CREATE" iN_CREATE :: Word32
434-- | Report when a file is created.
440setCreated :: Switch -> Config -> Config
441setCreated = setFlag iN_CREATE
444 "sys/inotify.h value IN_DELETE" iN_DELETE :: Word32
446-- | Report when a file is deleted.
452setDeleted :: Switch -> Config -> Config
453setDeleted = setFlag iN_DELETE
456 "sys/inotify.h value IN_MOVED_FROM" iN_MOVED_FROM :: Word32
458-- | Report the source of a move.
464setMovedFrom :: Switch -> Config -> Config
465setMovedFrom = setFlag iN_MOVED_FROM
468 "sys/inotify.h value IN_MOVED_TO" iN_MOVED_TO :: Word32
470-- | Report the target of a move.
476setMovedTo :: Switch -> Config -> Config
477setMovedTo = setFlag iN_MOVED_TO
480 "sys/inotify.h value IN_MODIFY" iN_MODIFY :: Word32
482-- | Report when a file is modified.
488setModified :: Switch -> Config -> Config
489setModified = setFlag iN_MODIFY
491-- | Set all tunable events 'On' or 'Off'. Equivalent to setting:
499-- * setNonWriteClosed
508setAllEvents :: Switch -> Config -> Config
516 . setNonWriteClosed s
523-------------------------------------------------------------------------------
525-------------------------------------------------------------------------------
527-- The defaults are set in such a way that the behavior on macOS and Linux is
528-- as much compatible as possible.
530-- | The default configuration settings are:
532-- * 'setFollowSymLinks' 'On'
533-- * 'setUnwatchMoved' 'On'
534-- * 'setOneShot' 'Off'
535-- * 'setOnlyDir' 'Off'
536-- * 'setWhenExists' 'AddIfExists'
538-- The tunable events enabled by default are:
548defaultConfig :: Config
550 setWhenExists AddIfExists
561-------------------------------------------------------------------------------
562-- Open an event stream
563-------------------------------------------------------------------------------
565-- | A handle for a watch.
568 Handle -- File handle for the watch
570 (IntMap -- Key is the watch descriptor
571 ( Array Word8 -- Absolute path of the watch root
572 , Array Word8 -- Path of subdir relative to watch root
577-- Instead of using the watch descriptor we can provide APIs that use the path
578-- itself to identify the watch. That will require us to maintain a map from wd
579-- to path in the Watch handle.
581newtype WD = WD CInt deriving Show
583foreign import ccall unsafe
584 "sys/inotify.h inotify_init" c_inotify_init :: IO CInt
586-- | Create a 'Watch' handle. 'addToWatch' can be used to add paths being
587-- monitored by this watch.
591createWatch :: IO Watch
593 rawfd <- throwErrnoIfMinus1 "createWatch" c_inotify_init
594 -- we could use fdToHandle but it cannot determine the fd type
595 -- automatically for the inotify fd
600 (Just (Stream, 0, 0)) -- (IODeviceType, CDev, CIno)
601 False -- not a socket
602 False -- non-blocking is false
603 let fdString = "<createWatch file descriptor: " ++ show fd ++ ">"
610 True -- use non-blocking IO
611 Nothing -- TextEncoding (binary)
612 emptyMapRef <- newIORef Map.empty
613 return $ Watch h emptyMapRef
615foreign import ccall unsafe
616 "sys/inotify.h inotify_add_watch" c_inotify_add_watch
617 :: CInt -> CString -> CUInt -> IO CInt
619-- XXX we really do not know the path encoding, all we know is that it is "/"
620-- separated bytes. So these may fail or convert the path in an unexpected
621-- manner. We should ultimately remove all usage of these.
623toUtf8 :: MonadIO m => String -> m (Array Word8)
624toUtf8 = A.fromStream . U.encodeUtf8 . S.fromList
626utf8ToString :: Array Word8 -> String
627utf8ToString = runIdentity . S.toList . U.decodeUtf8' . A.toStream
629-- | Add a trailing "/" at the end of the path if there is none. Do not add a
630-- "/" if the path is empty.
632ensureTrailingSlash :: Array Word8 -> Array Word8
633ensureTrailingSlash path =
634 if byteLength path /= 0
636 let mx = A.getIndex (byteLength path - 1) path
638 Nothing -> error "ensureTrailingSlash: Bug: Invalid index"
640 if x /= forwardSlashByte
641 then path <> forwardSlash
644 where forwardSlash = A.fromList [ forwardSlashByte ]
645 forwardSlashByte = fromIntegral (ord '/')
647removeTrailingSlash :: Array Word8 -> Array Word8
648removeTrailingSlash path =
649 if byteLength path /= 0
651 let n = byteLength path - 1
652 mx = A.getIndex n path
654 Nothing -> error "removeTrailingSlash: Bug: Invalid index"
656 if x == fromIntegral (ord '/')
657 then A.getSliceUnsafe 0 n path
661appendPaths :: Array Word8 -> Array Word8 -> Array Word8
663 | byteLength a == 0 = b
664 | byteLength b == 0 = a
665 | otherwise = ensureTrailingSlash a <> b
667-- | @addToWatch cfg watch root subpath@ adds @subpath@ to the list of paths
668-- being monitored under @root@ via the watch handle @watch@. @root@ must be
669-- an absolute path and @subpath@ must be relative to @root@.
673addToWatch :: Config -> Watch -> Array Word8 -> Array Word8 -> IO ()
674addToWatch cfg@Config{..} watch0@(Watch handle wdMap) root0 path0 = do
675 -- XXX do not add if the path is already added
676 -- XXX if the watch is added by the scan and not via an event we can
677 -- generate a create event assuming that the create may have been lost. We
678 -- can also mark in the map that this entry was added by the scan. So if an
679 -- actual create event later comes and tries to add this again then we can
680 -- ignore that and drop the create event to avoid duplicate create, because
681 -- we have already emitted it.
683 -- When a directory is added by the scan we should also emit create events
684 -- for files that may have got added to the dir. However, such create
685 -- events may get duplicated because of a race between the scan generated
686 -- versus real events.
688 -- Or we may distinguish between scan generated events and real events so
689 -- that the application can assume that other events may been lost and
690 -- handle it. For example, if it is a dir create the application can read
691 -- the dir to scan the files in it.
693 let root = removeTrailingSlash root0
694 path = removeTrailingSlash path0
695 absPath = appendPaths root path
696 putStrLn $ "root = " ++ utf8ToString root ++ " path = " ++ utf8ToString path ++ " absPath = " ++ utf8ToString absPath
698 fd <- handleToFd handle
700 -- XXX we need to tolerate an error where we are adding a watch for a
701 -- non-existing file because the file may have got deleted by the time we
702 -- added the watch. Perhaps we can have a flag in config for this and keep
703 -- the default value to tolerate the error.
705 -- XXX The file may have even got deleted and then recreated which we will
706 -- never get to know, document this.
707 wd <- A.asCStringUnsafe absPath $ \pathPtr ->
708 throwErrnoIfMinus1 ("addToWatch: " ++ utf8ToString absPath) $
709 c_inotify_add_watch (fdFD fd) pathPtr (CUInt createFlags)
711 -- We add the parent first so that we start getting events for any new
712 -- creates and add the new subdirectories on creates while we are adding
714 modifyIORef wdMap (Map.insert (fromIntegral wd) (root, path))
716 -- Now add the children. If we missed any creates while we were adding the
717 -- parent, this will make sure they are added too.
719 -- XXX Ensure that we generate events that we may have missed while we were
720 -- adding the dirs. That may generate spurious events though.
722 -- XXX toDirs currently uses paths as String, we need to convert it
723 -- to "/" separated by byte arrays.
724 pathIsDir <- doesDirectoryExist $ utf8ToString absPath
725 when (watchRec && pathIsDir) $ do
726 S.mapM_ (\p -> addToWatch cfg watch0 root (appendPaths path p))
728 $ Dir.toDirs $ utf8ToString absPath
730foreign import ccall unsafe
731 "sys/inotify.h inotify_rm_watch" c_inotify_rm_watch
732 :: CInt -> CInt -> IO CInt
734-- | Remove an absolute root path from a 'Watch', if a path was moved after
735-- adding you need to provide the original path which was used to add the
740removeFromWatch :: Watch -> Array Word8 -> IO ()
741removeFromWatch (Watch handle wdMap) path = do
742 fd <- handleToFd handle
743 km <- readIORef wdMap
744 wdMap1 <- foldlM (step fd) Map.empty (Map.toList km)
745 writeIORef wdMap wdMap1
749 step fd newMap (wd, v) = do
752 let err = "removeFromWatch: " ++ show (utf8ToString path)
753 rm = c_inotify_rm_watch (fdFD fd) (fromIntegral wd)
754 void $ throwErrnoIfMinus1 err rm
756 else return $ Map.insert wd v newMap
758-- | Given a 'Config' and list of @paths@ ("/" separated byte arrays) start
759-- monitoring the paths for file system events. Returns a 'Watch' handle which
760-- can then be used to read the event stream or to close the watch.
764openWatch :: Config -> NonEmpty (Array Word8) -> IO Watch
765openWatch cfg paths = do
768 (\root -> addToWatch cfg w root (A.fromList []))
769 $ NonEmpty.toList paths
772-- | Close a 'Watch' handle.
776closeWatch :: Watch -> IO ()
777closeWatch (Watch h _) = hClose h
779-------------------------------------------------------------------------------
780-- Raw events read from the watch file handle
781-------------------------------------------------------------------------------
783newtype Cookie = Cookie Word32 deriving (Show, Eq)
785-- | An Event generated by the file system. Use the accessor functions to
792 , eventFlags :: Word32
793 , eventCookie :: Word32
794 , eventRelPath :: Array Word8
795 , eventMap :: IntMap (Array Word8, Array Word8)
796 } deriving (Show, Ord, Eq)
798-- The inotify event struct from the man page/header file:
800-- struct inotify_event {
801-- int wd; /* Watch descriptor */
802-- uint32_t mask; /* Mask describing event */
803-- uint32_t cookie; /* Unique cookie associating related
804-- events (for rename(2)) */
805-- uint32_t len; /* Size of name field */
806-- char name[]; /* Optional null-terminated name */
809-- XXX We can perhaps use parseD monad instance for fusing with parseMany? Need
810-- to measure the perf.
812readOneEvent :: Config -> Watch -> Parser IO Word8 Event
813readOneEvent cfg wt@(Watch _ wdMap) = do
814 let headerLen = sizeOf (undefined :: CInt) + 12
815 arr <- PR.takeEQ headerLen (A.writeN headerLen)
816 (ewd, eflags, cookie, pathLen) <- PR.fromEffect $ A.asPtrUnsafe arr readHeader
817 -- XXX need the "initial" in parsers to return a step type so that "take 0"
818 -- can return without an input. otherwise if pathLen is 0 we will keep
819 -- waiting to read one more char before we return this event.
823 -- XXX takeEndBy_ drops the separator so assumes a null
824 -- terminated path, we should use a takeWhile nested inside a
828 $ FL.takeEndBy_ (== 0)
829 $ FL.take pathLen (A.writeN pathLen)
830 let remaining = pathLen - byteLength pth - 1
831 when (remaining /= 0) $ PR.takeEQ remaining FL.drain
833 else return $ A.fromList []
834 wdm <- PR.fromEffect $ readIORef wdMap
836 case Map.lookup (fromIntegral ewd) wdm of
839 error $ "readOneEvent: "
840 <> "Unknown watch descriptor: "
842 let sub1 = appendPaths sub path
843 -- Check for "ISDIR" first because it is less likely
844 isDirCreate = eflags .&. iN_ISDIR /= 0 && eflags .&. iN_CREATE /= 0
845 when (watchRec cfg && isDirCreate)
846 $ PR.fromEffect $ addToWatch cfg wt root sub1
847 -- XXX Handle IN_DELETE, IN_DELETE_SELF, IN_MOVE_SELF, IN_MOVED_FROM,
849 -- What if a large dir tree gets moved in to our hierarchy? Do we get a
850 -- single event for the top level dir in this case?
852 { eventWd = fromIntegral ewd
853 , eventFlags = eflags
854 , eventCookie = cookie
855 , eventRelPath = sub1
861 readHeader (ptr :: Ptr Word8) = do
862 let len = sizeOf (undefined :: CInt)
864 eflags <- peekByteOff ptr len
865 cookie <- peekByteOff ptr (len + 4)
866 pathLen :: Word32 <- peekByteOff ptr (len + 8)
867 return (ewd, eflags, cookie, fromIntegral pathLen)
869watchToStream :: Config -> Watch -> Stream IO Event
870watchToStream cfg wt@(Watch handle _) = do
871 -- Do not use too small a buffer. As per inotify man page:
873 -- The behavior when the buffer given to read(2) is too small to return
874 -- information about the next event depends on the kernel version: in
875 -- kernels before 2.6.21, read(2) returns 0; since kernel 2.6.21, read(2)
876 -- fails with the error EINVAL. Specifying a buffer of size
878 -- sizeof(struct inotify_event) + NAME_MAX + 1
880 -- will be sufficient to read at least one event.
881 S.parseMany (readOneEvent cfg wt) $ S.unfold FH.read handle
883-- XXX We should not go across the mount points of network file systems or file
884-- systems that are known to not generate any events.
886-- | Start monitoring a list of file system paths for file system events with
887-- the supplied configuration operation over the 'defaultConfig'. The
888-- paths could be files or directories. When recursive mode is set and the
889-- path is a directory, the whole directory tree under it is watched
890-- recursively. Monitoring starts from the current time onwards. The paths are
891-- specified as UTF-8 encoded 'Array' of 'Word8'.
893-- /Non-existing Paths:/ the API fails if a watch is started on a non-exsting
896-- /Performance:/ Note that recursive watch on a large directory tree could be
897-- expensive. When starting a watch, the whole tree must be read and watches
898-- are started on each directory in the tree. The initial time to start the
899-- watch as well as the memory required is proportional to the number of
900-- directories in the tree.
902-- /Bugs:/ When new directories are created under the tree they are added to
903-- the watch on receiving the directory create event. However, the creation of
904-- a dir and adding a watch for it is not atomic. The implementation takes
905-- care of this and makes sure that watches are added for all directories.
906-- However, In the mean time, the directory may have received more events which
907-- may get lost. Handling of any such lost events is yet to be implemented.
909-- See the Linux __inotify__ man page for more details.
913-- ('setFollowSymLinks' On . 'setUnwatchMoved' Off)
914-- [Array.fromList "dir"]
919watchWith :: (Config -> Config) -> NonEmpty (Array Word8) -> Stream IO Event
920watchWith f paths = S.bracket before after (watchToStream cfg)
924 cfg = f defaultConfig
925 before = liftIO $ openWatch cfg paths
926 after = liftIO . closeWatch
928-- | Same as 'watchWith' using 'defaultConfig' and recursive mode.
930-- >>> watchRecursive = watchWith (setRecursiveMode On)
932-- See 'watchWith' for pitfalls and bugs when using recursive watch on Linux.
936watchRecursive :: NonEmpty (Array Word8) -> Stream IO Event
937watchRecursive = watchWith (setRecursiveMode On)
939-- | Same as 'watchWith' using defaultConfig and non-recursive mode.
941-- >>> watch = watchWith id
945watch :: NonEmpty (Array Word8) -> Stream IO Event
948-------------------------------------------------------------------------------
949-- Examine event stream
950-------------------------------------------------------------------------------
952-- | Get the watch root corresponding to the 'Event'.
954-- Note that if a path was moved after adding to the watch, this will give the
955-- original path and not the new path after moving.
957-- TBD: we can possibly update the watch root on a move self event.
961getRoot :: Event -> Array Word8
965 case Map.lookup (fromIntegral eventWd) eventMap of
966 Just path -> fst path
968 error $ "Bug: getRoot: No path found corresponding to the "
969 ++ "watch descriptor " ++ show eventWd
972-- XXX should we use a Maybe here?
973-- | Get the file system object path for which the event is generated, relative
974-- to the watched root. The path is a "/" separated array of bytes.
978getRelPath :: Event -> Array Word8
979getRelPath Event{..} = eventRelPath
981-- | Get the absolute file system object path for which the event is generated.
983-- When the watch root is a symlink, the absolute path returned is via the
984-- original symlink and not through the resolved path.
988getAbsPath :: Event -> Array Word8
990 let relpath = getRelPath ev
992 in if byteLength relpath /= 0
993 then ensureTrailingSlash root <> relpath
994 else removeTrailingSlash root
996-- XXX should we use a Maybe?
997-- | Cookie is set when a rename occurs. The cookie value can be used to
998-- connect the 'isMovedFrom' and 'isMovedTo' events, if both the events belong
999-- to the same move operation then they will have the same cookie value.
1003getCookie :: Event -> Cookie
1004getCookie Event{..} = Cookie eventCookie
1006-------------------------------------------------------------------------------
1008-------------------------------------------------------------------------------
1010getFlag :: Word32 -> Event -> Bool
1011getFlag mask Event{..} = eventFlags .&. mask /= 0
1013-------------------------------------------------------------------------------
1015-------------------------------------------------------------------------------
1018 "sys/inotify.h value IN_Q_OVERFLOW" iN_Q_OVERFLOW :: Word32
1020-- XXX rename to isQOverflowed or hasOverflowed?
1022-- macOS overflow API is more specific, it tells which paths have lost the
1023-- events due to overflow.
1025-- | Event queue overflowed (WD is invalid for this event) and we may have lost
1026-- some events.. The user application must scan everything under the watched
1027-- paths to know the current state.
1031isEventsLost :: Event -> Bool
1032isEventsLost = getFlag iN_Q_OVERFLOW
1034-------------------------------------------------------------------------------
1035-- Events affecting the watched path only
1036-------------------------------------------------------------------------------
1039 "sys/inotify.h value IN_IGNORED" iN_IGNORED :: Word32
1041-- Compare with isRootChanged on macOS. isRootChanged includes all these cases.
1043-- | A path was removed from the watch explicitly using 'removeFromWatch' or
1044-- automatically (file was deleted, or filesystem was unmounted).
1046-- Note that in recursive watch mode all the subdirectories are watch roots,
1047-- therefore, they will all generate this event.
1049-- /Occurs only for a watched path/
1053isRootUnwatched :: Event -> Bool
1054isRootUnwatched = getFlag iN_IGNORED
1056-- | Watched file/directory was itself deleted. (This event also occurs if an
1057-- object is moved to another filesystem, since mv(1) in effect copies the file
1058-- to the other filesystem and then deletes it from the original filesystem.)
1059-- In addition, an 'isRootUnwatched' event will subsequently be generated
1060-- for the watch descriptor.
1062-- Note that in recursive watch mode all the subdirectories are watch roots,
1063-- therefore, they will all generate this event.
1065-- /Occurs only for a watched path/
1069isRootDeleted :: Event -> Bool
1070isRootDeleted = getFlag iN_DELETE_SELF
1072-- | Watched file/directory was itself moved within the file system.
1074-- Note that in recursive watch mode all the subdirectories are watch roots,
1075-- therefore, they will all generate this event.
1077-- /Occurs only for a watched path/
1081isRootMoved :: Event -> Bool
1082isRootMoved = getFlag iN_MOVE_SELF
1085 "sys/inotify.h value IN_UNMOUNT" iN_UNMOUNT :: Word32
1087-- | Filesystem containing watched object was unmounted. In addition, an
1088-- 'isRootUnwatched' event will subsequently be generated for the watch
1091-- /Occurs only for a watched path/
1095isRootUnmounted :: Event -> Bool
1096isRootUnmounted = getFlag iN_UNMOUNT
1098-- | Determine whether the event indicates a change of path of the monitored
1099-- object itself. Note that the object may become unreachable or deleted after
1102-- /Occurs only for a watched path/
1106isRootPathEvent :: Event -> Bool
1107isRootPathEvent = getFlag (iN_DELETE_SELF .|. iN_MOVE_SELF .|. iN_UNMOUNT)
1109-------------------------------------------------------------------------------
1110-- Metadata change Events
1111-------------------------------------------------------------------------------
1113-- macOS has multiple APIs for metadata change for different metadata.
1115-- | Determine whether the event indicates inode metadata change for an object
1116-- contained within the monitored path.
1118-- Metadata change may include, permissions (e.g., chmod(2)), timestamps
1119-- (e.g., utimensat(2)), extended attributes (setxattr(2)), link count (since
1120-- Linux 2.6.25; e.g., for the target of link(2) and for unlink(2)), and
1121-- user/group ID (e.g., chown(2)).
1123-- /Can occur for watched path or a file inside it/
1127isAttrsModified :: Event -> Bool
1128isAttrsModified = getFlag iN_ATTRIB
1130-------------------------------------------------------------------------------
1132-------------------------------------------------------------------------------
1134-- | File was accessed (e.g. read, execve).
1136-- /Occurs only for a file inside the watched directory/
1140isAccessed :: Event -> Bool
1141isAccessed = getFlag iN_ACCESS
1143-- | File or directory was opened.
1145-- /Occurs only for a file inside the watched directory/
1149isOpened :: Event -> Bool
1150isOpened = getFlag iN_OPEN
1152-- | File opened for writing was closed.
1154-- /Occurs only for a file inside the watched directory/
1158isWriteClosed :: Event -> Bool
1159isWriteClosed = getFlag iN_CLOSE_WRITE
1161-- XXX what if it was opened for append? Does NOWRITE mean all cases where the
1162-- mode was not write? A dir open comes in this category?
1164-- | File or directory opened for read but not write was closed.
1166-- /Can occur for watched path or a file inside it/
1170isNonWriteClosed :: Event -> Bool
1171isNonWriteClosed = getFlag iN_CLOSE_NOWRITE
1173-------------------------------------------------------------------------------
1175-------------------------------------------------------------------------------
1177-- On macOS this is not generated on hard linking but on Linux it is.
1179-- | File/directory created in watched directory (e.g., open(2) O_CREAT,
1180-- mkdir(2), link(2), symlink(2), bind(2) on a UNIX domain socket).
1182-- /Occurs only for an object inside the watched directory/
1186isCreated :: Event -> Bool
1187isCreated = getFlag iN_CREATE
1189-- | File/directory deleted from watched directory.
1191-- /Occurs only for an object inside the watched directory/
1195isDeleted :: Event -> Bool
1196isDeleted = getFlag iN_DELETE
1198-- XXX what if an object is moved in from outside or moved out of the monitored
1201-- | Generated for the original path when an object is moved from under a
1202-- monitored directory.
1204-- /Occurs only for an object inside the watched directory/
1208isMovedFrom :: Event -> Bool
1209isMovedFrom = getFlag iN_MOVED_FROM
1211-- | Generated for the new path when an object is moved under a monitored
1214-- /Occurs only for an object inside the watched directory/
1218isMovedTo :: Event -> Bool
1219isMovedTo = getFlag iN_MOVED_TO
1221-- | Generated for a path that is moved from or moved to the monitored
1224-- >>> isMoved ev = isMovedFrom ev || isMovedTo ev
1226-- /Occurs only for an object inside the watched directory/
1230isMoved :: Event -> Bool
1231isMoved ev = isMovedFrom ev || isMovedTo ev
1233-- | Determine whether the event indicates modification of an object within the
1234-- monitored path. This event is generated only for files and not directories.
1236-- /Occurs only for an object inside the watched directory/
1240isModified :: Event -> Bool
1241isModified = getFlag iN_MODIFY
1243-------------------------------------------------------------------------------
1244-- Information about path type (applicable only when 'setFileEvents' is 'On')
1245-------------------------------------------------------------------------------
1248 "sys/inotify.h value IN_ISDIR" iN_ISDIR :: Word32
1250-- | Determine whether the event is for a directory path.
1254isDir :: Event -> Bool
1255isDir = getFlag iN_ISDIR
1257-------------------------------------------------------------------------------
1259-------------------------------------------------------------------------------
1261-- | Convert an 'Event' record to a String representation.
1262showEvent :: Event -> String
1263showEvent ev@Event{..} =
1264 "--------------------------"
1265 ++ "\nWd = " ++ show eventWd
1266 ++ "\nRoot = " ++ show (utf8ToString $ getRoot ev)
1267 ++ "\nPath = " ++ show (utf8ToString $ getRelPath ev)
1268 ++ "\nCookie = " ++ show (getCookie ev)
1269 ++ "\nFlags " ++ show eventFlags
1271 ++ showev isEventsLost "Overflow"
1273 ++ showev isRootUnwatched "RootUnwatched"
1274 ++ showev isRootDeleted "RootDeleted"
1275 ++ showev isRootMoved "RootMoved"
1276 ++ showev isRootUnmounted "RootUnmounted"
1278 ++ showev isAttrsModified "AttrsModified"
1280 ++ showev isAccessed "Accessed"
1281 ++ showev isOpened "Opened"
1282 ++ showev isWriteClosed "WriteClosed"
1283 ++ showev isNonWriteClosed "NonWriteClosed"
1285 ++ showev isCreated "Created"
1286 ++ showev isDeleted "Deleted"
1287 ++ showev isModified "Modified"
1288 ++ showev isMovedFrom "MovedFrom"
1289 ++ showev isMovedTo "MovedTo"
1291 ++ showev isDir "Dir"
1294 where showev f str = if f ev then "\n" ++ str else ""
1296#warning "Disabling module Streamly.Internal.FileSystem.Event.Linux. Does not support kernels older than 2.6.36."
1297module 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